Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agentic-ide): a code editor for working by hand beside the agents

rubenluetke10-beep774134912014
diff --git a/jarvis/ui/web/frontend/package-lock.json b/jarvis/ui/web/frontend/package-lock.json
index f5b8af718d..ce807c4571 100644
--- a/jarvis/ui/web/frontend/package-lock.json
+++ b/jarvis/ui/web/frontend/package-lock.json
@@ -38,6 +38,7 @@
"html-to-image": "^1.11.13",
"lucide-react": "^0.445.0",
"material-icon-theme": "5.37.0",
+ "monaco-editor": "^0.57.0",
"onnxruntime-web": "1.31.0-dev.20260914-8d85527a0",
"qrcode.react": "^4.2.0",
"react": "^18.3.1",
@@ -2805,7 +2806,6 @@
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz",
"integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==",
"license": "MIT",
- "peer": true,
"dependencies": {
"undici-types": "~7.19.0"
}
@@ -2880,6 +2880,13 @@
"integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
"license": "MIT"
},
+ "node_modules/@types/trusted-types": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
+ "license": "MIT",
+ "optional": true
+ },
"node_modules/@types/unist": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
@@ -4200,6 +4207,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/dompurify": {
+ "version": "3.4.15",
+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.15.tgz",
+ "integrity": "sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==",
+ "license": "(MPL-2.0 OR Apache-2.0)",
+ "optionalDependencies": {
+ "@types/trusted-types": "^2.0.7"
+ }
+ },
"node_modules/draco3d": {
"version": "1.5.7",
"resolved": "https://registry.npmjs.org/draco3d/-/draco3d-1.5.7.tgz",
@@ -5428,6 +5444,18 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/marked": {
+ "version": "14.0.0",
+ "resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz",
+ "integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==",
+ "license": "MIT",
+ "bin": {
+ "marked": "bin/marked.js"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
"node_modules/material-icon-theme": {
"version": "5.37.0",
"resolved": "https://registry.npmjs.org/material-icon-theme/-/material-icon-theme-5.37.0.tgz",
@@ -6389,6 +6417,16 @@
"node": ">= 0.6"
}
},
+ "node_modules/monaco-editor": {
+ "version": "0.57.0",
+ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.57.0.tgz",
+ "integrity": "sha512-5BkI9KGoqrNvBGUe15/QlZq3OooZ8WLg1AxTpaqHRCP3HNpzPPZKE2EDz8M7c+VRmCeUw1Brp4cx/PWm3kI/5A==",
+ "license": "MIT",
+ "dependencies": {
+ "dompurify": "3.4.15",
+ "marked": "14.0.0"
+ }
+ },
"node_modules/motion-dom": {
"version": "12.38.0",
"resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.38.0.tgz",
diff --git a/jarvis/ui/web/frontend/package.json b/jarvis/ui/web/frontend/package.json
index 1033ba2700..4ccb993e2f 100644
--- a/jarvis/ui/web/frontend/package.json
+++ b/jarvis/ui/web/frontend/package.json
@@ -40,6 +40,7 @@
"html-to-image": "^1.11.13",
"lucide-react": "^0.445.0",
"material-icon-theme": "5.37.0",
+ "monaco-editor": "^0.57.0",
"onnxruntime-web": "1.31.0-dev.20260914-8d85527a0",
"qrcode.react": "^4.2.0",
"react": "^18.3.1",
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
new file mode 100644
index 0000000000..afedbc23c0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
@@ -0,0 +1,505 @@
+import { Suspense, lazy, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { useShallow } from "zustand/react/shallow";
+import {
+ AlertTriangle,
+ ChevronRight,
+ Copy,
+ ExternalLink,
+ FileDiff,
+ FileText,
+ FolderSearch,
+ Loader2,
+ SquareArrowOutUpRight,
+ SquareTerminal,
+ X,
+} from "lucide-react";
+
+import { fill, useT } from "@/i18n";
+import { attachToTerminal, openTerminalTarget } from "@/lib/agenticIdeApi";
+import { cn } from "@/lib/utils";
+import { useEventStore } from "@/store/events";
+import { revealInExplorer } from "@/store/ideExplorer";
+import { tabsOf, useCodeEditorStore, type EditorTab } from "@/store/codeEditor";
+import { FileTypeIcon } from "@/components/agentic/sidePanel/explorer/FileTypeIcon";
+import { absoluteWorkspacePath } from "@/components/agentic/sidePanel/explorer/explorerApi";
+import { ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "@/components/agentic/threads/ThreadPopover";
+import { checkDisk, discardFile, languageName, revertFile, saveAll, saveFile } from "./editorModels";
+import { QuickOpen } from "./QuickOpen";
+
+const EditorSurface = lazy(() => import("./EditorSurface"));
+
+/** How often the open file is compared with the disk while the editor is on screen. */
+const DISK_POLL_MS = 3000;
+const DISK_JITTER_MS = 1500;
+
+const baseName = (path: string) => path.split("/").pop() ?? path;
+
+interface PendingClose {
+ keys: string[];
+ fileKeys: string[];
+}
+
+function copyText(text: string): void {
+ void navigator.clipboard?.writeText(text).catch((error: unknown) =>
+ useEventStore.getState().pushToast("error", (error as Error).message),
+ );
+}
+
+/**
+ * The code editor, laid over the terminal grid of the Agentic IDE.
+ *
+ * Files open here from the side panel's Folder and Changes tabs, from a
+ * Ctrl+click on a path in a terminal, and from Go to File (Ctrl+P). The
+ * terminals stay mounted underneath; "Terminals" in the tab bar brings them
+ * back without closing a tab.
+ */
+export function CodeEditorStage({
+ workspaceId,
+ workspacePath,
+ stagedPane,
+}: {
+ workspaceId: string | null;
+ workspacePath: string;
+ stagedPane: string | null;
+}) {
+ const t = useT();
+ const stage = useRef<HTMLDivElement>(null);
+ const tabs = useCodeEditorStore(useShallow((state) => tabsOf(state, workspaceId)));
+ const activeKey = useCodeEditorStore((state) => (workspaceId ? (state.active[workspaceId] ?? null) : null));
+ const visible = useCodeEditorStore((state) => state.visible);
+ const quickOpen = useCodeEditorStore((state) => state.quickOpen);
+ const files = useCodeEditorStore((state) => state.files);
+ const [pending, setPending] = useState<PendingClose | null>(null);
+ const [menu, setMenu] = useState<EditorTab | null>(null);
+ const menuAnchor = useRef<HTMLElement | null>(null);
+ const pushToast = useEventStore((state) => state.pushToast);
+
+ const activeTab = tabs.find((tab) => tab.key === activeKey) ?? tabs[tabs.length - 1] ?? null;
+ const activeFile = activeTab ? files[activeTab.fileKey] : undefined;
+ const shown = visible && activeTab !== null;
+
+ // Closing the last tab hands the stage back to the terminals.
+ useEffect(() => {
+ if (visible && workspaceId && tabs.length === 0) useCodeEditorStore.getState().setVisible(false);
+ }, [visible, workspaceId, tabs.length]);
+
+ /** Close tabs, asking first when that would throw away unsaved edits. */
+ const requestClose = (keys: string[]) => {
+ const state = useCodeEditorStore.getState();
+ const closing = new Set(keys);
+ const remaining = new Set(state.tabs.filter((tab) => !closing.has(tab.key)).map((tab) => tab.fileKey));
+ const fileKeys = [
+ ...new Set(
+ state.tabs
+ .filter((tab) => closing.has(tab.key) && !remaining.has(tab.fileKey) && state.files[tab.fileKey]?.dirty)
+ .map((tab) => tab.fileKey),
+ ),
+ ];
+ if (fileKeys.length === 0) state.closeTabs(keys);
+ else setPending({ keys, fileKeys });
+ };
+
+ const requestCloseRef = useRef(requestClose);
+ requestCloseRef.current = requestClose;
+
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (!workspaceId || !(event.ctrlKey || event.metaKey) || event.altKey) return;
+ if (useEventStore.getState().activeSection !== "agentic-ide") return;
+ const target = event.target instanceof HTMLElement ? event.target : null;
+ // A terminal keeps every Ctrl key for its shell (Ctrl+P, Ctrl+W, …).
+ if (target?.closest(".xterm")) return;
+ const key = event.key.toLowerCase();
+ const state = useCodeEditorStore.getState();
+ if (key === "p" && !event.shiftKey) {
+ event.preventDefault();
+ event.stopPropagation();
+ state.setQuickOpen(true);
+ return;
+ }
+ const host = stage.current;
+ if (!state.visible || !host) return;
+ if (target && target !== document.body && !host.contains(target)) return;
+ const own = tabsOf(state, workspaceId);
+ const current = own.find((tab) => tab.key === state.active[workspaceId]) ?? own[own.length - 1];
+ if (!current) return;
+ const handled = () => {
+ event.preventDefault();
+ event.stopPropagation();
+ };
+ if (key === "s") {
+ handled();
+ if (event.shiftKey) void saveAll(workspaceId);
+ else void saveFile(current.fileKey);
+ } else if (key === "w" && !event.shiftKey) {
+ handled();
+ requestCloseRef.current([current.key]);
+ } else if (key === "tab" || key === "pagedown" || key === "pageup") {
+ handled();
+ state.cycle(workspaceId, event.shiftKey || key === "pageup" ? -1 : 1);
+ } else if (key === "t" && event.shiftKey) {
+ handled();
+ state.reopenClosed(workspaceId);
+ }
+ };
+ window.addEventListener("keydown", onKey, true);
+ return () => window.removeEventListener("keydown", onKey, true);
+ }, [workspaceId]);
+
+ // Notice an agent's edit to the open file: on a timer and when the window regains focus.
+ const activeFileKey = shown ? activeTab.fileKey : null;
+ useEffect(() => {
+ if (!activeFileKey) return;
+ let alive = true;
+ let timer: number | undefined;
+ const check = () => {
+ if (document.visibilityState === "visible" && useEventStore.getState().activeSection === "agentic-ide") {
+ void checkDisk(activeFileKey);
+ }
+ };
+ const tick = () => {
+ check();
+ if (alive) timer = window.setTimeout(tick, DISK_POLL_MS + Math.random() * DISK_JITTER_MS);
+ };
+ timer = window.setTimeout(tick, DISK_POLL_MS);
+ window.addEventListener("focus", check);
+ return () => {
+ alive = false;
+ window.clearTimeout(timer);
+ window.removeEventListener("focus", check);
+ };
+ }, [activeFileKey]);
+
+ const duplicateNames = useMemo(() => {
+ // Two different files with one name get their folder beside it; the edit
+ // and diff tab of one file do not.
+ const counts = new Map<string, number>();
+ for (const path of new Set(tabs.map((tab) => tab.path))) counts.set(baseName(path), (counts.get(baseName(path)) ?? 0) + 1);
+ return counts;
+ }, [tabs]);
+
+ if (!workspaceId) return null;
+
+ const openExternally = (path: string) =>
+ void openTerminalTarget(workspaceId, path).catch((error: unknown) => pushToast("error", (error as Error).message));
+ const absolute = (path: string) => absoluteWorkspacePath(workspacePath, path);
+
+ const quick = quickOpen ? <QuickOpen workspaceId={workspaceId} /> : null;
+ if (!shown) return quick;
+
+ const store = useCodeEditorStore.getState();
+ const segments = activeTab.path.split("/");
+
+ return (
+ <>
+ <div
+ ref={stage}
+ data-testid="code-editor"
+ data-path={activeTab.path}
+ className="absolute inset-0 z-20 flex min-h-0 flex-col bg-background"
+ >
+ {/* Tab bar */}
+ <div className="flex h-9 shrink-0 items-stretch border-b border-border/70 bg-sidebar">
+ <div role="tablist" aria-label={t("code_editor.tabs")} className="scrollbar-none flex min-w-0 flex-1 items-stretch overflow-x-auto">
+ {tabs.map((tab) => {
+ const file = files[tab.fileKey];
+ const active = tab.key === activeTab.key;
+ const name = baseName(tab.path);
+ const folder = tab.path.split("/").slice(-2, -1)[0];
+ return (
+ <div
+ key={tab.key}
+ role="tab"
+ aria-selected={active}
+ data-testid="code-editor-tab"
+ data-path={tab.path}
+ data-preview={tab.preview || undefined}
+ data-dirty={file?.dirty || undefined}
+ tabIndex={0}
+ title={tab.path}
+ onClick={() => store.activate(tab.key)}
+ onDoubleClick={() => store.pinTab(tab.key)}
+ onAuxClick={(event) => {
+ if (event.button === 1) {
+ event.preventDefault();
+ requestClose([tab.key]);
+ }
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") store.activate(tab.key);
+ }}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ menuAnchor.current = event.currentTarget;
+ setMenu(tab);
+ }}
+ className={cn(
+ "group relative flex min-w-0 max-w-[220px] shrink-0 cursor-pointer items-center gap-1.5 border-r border-border/50 pl-3 pr-1.5 text-[13px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
+ active ? "bg-background text-foreground-strong" : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground",
+ )}
+ >
+ {active && <span className="absolute inset-x-0 top-0 h-px bg-primary" aria-hidden />}
+ {tab.mode === "diff" ? <FileDiff className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden /> : <FileTypeIcon path={tab.path} />}
+ <span className={cn("truncate", tab.preview && "italic", file?.deleted && "line-through decoration-destructive/70")}>{name}</span>
+ {(duplicateNames.get(name) ?? 0) > 1 && folder && <span className="shrink-0 truncate text-[11px] text-muted-foreground">{folder}</span>}
+ <button
+ type="button"
+ aria-label={fill(t("code_editor.close_tab"), { file: name })}
+ title={t("code_editor.close_tab_hint")}
+ onClick={(event) => {
+ event.stopPropagation();
+ requestClose([tab.key]);
+ }}
+ className="group/close relative inline-flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {file?.dirty ? (
+ <>
+ <span className="h-2 w-2 rounded-full bg-foreground/70 group-hover/close:hidden" aria-hidden />
+ <X className="hidden h-3.5 w-3.5 group-hover/close:block" aria-hidden />
+ </>
+ ) : (
+ <X className={cn("h-3.5 w-3.5", !active && "opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100")} aria-hidden />
+ )}
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ <button
+ type="button"
+ data-testid="code-editor-hide"
+ onClick={() => store.setVisible(false)}
+ title={t("code_editor.show_terminals_hint")}
+ className="inline-flex shrink-0 items-center gap-1.5 border-l border-border/60 px-3 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
+ >
+ <SquareTerminal className="h-3.5 w-3.5" aria-hidden />
+ {t("code_editor.show_terminals")}
+ </button>
+ </div>
+
+ {/* Breadcrumbs and file actions */}
+ <div className="flex h-8 shrink-0 items-center gap-2 border-b border-border/50 px-3 text-xs text-muted-foreground">
+ <nav aria-label={t("code_editor.breadcrumbs")} className="flex min-w-0 flex-1 items-center gap-0.5 overflow-hidden">
+ {segments.map((segment, index) => (
+ <span key={`${segment}-${index}`} className="flex min-w-0 shrink items-center gap-0.5">
+ {index > 0 && <ChevronRight className="h-3 w-3 shrink-0 opacity-60" aria-hidden />}
+ <span className={cn("truncate", index === segments.length - 1 && "text-foreground")}>{segment}</span>
+ </span>
+ ))}
+ {activeTab.mode === "diff" && <span className="ml-1.5 shrink-0 rounded bg-secondary px-1.5 py-px text-[11px]">{t("code_editor.diff_badge")}</span>}
+ </nav>
+ <ActionButton
+ onClick={() => store.openFile(workspaceId, activeTab.path, { mode: activeTab.mode === "diff" ? "edit" : "diff", preview: false })}
+ icon={activeTab.mode === "diff" ? <FileText className="h-3.5 w-3.5" aria-hidden /> : <FileDiff className="h-3.5 w-3.5" aria-hidden />}
+ label={activeTab.mode === "diff" ? t("code_editor.open_file") : t("code_editor.open_changes")}
+ />
+ {stagedPane && (
+ <ActionButton
+ onClick={() =>
+ void attachToTerminal(stagedPane, { paths: [absolute(activeTab.path)] }).catch((error: unknown) =>
+ pushToast("error", (error as Error).message),
+ )
+ }
+ icon={<SquareArrowOutUpRight className="h-3.5 w-3.5" aria-hidden />}
+ label={fill(t("code_editor.reference_in"), { pane: stagedPane })}
+ />
+ )}
+ <ActionButton
+ onClick={() => openExternally(activeTab.path)}
+ icon={<ExternalLink className="h-3.5 w-3.5" aria-hidden />}
+ label={t("code_editor.open_externally")}
+ iconOnly
+ />
+ </div>
+
+ {activeFile?.conflict && (
+ <Banner tone="warning" testId="code-editor-conflict" text={t("code_editor.conflict")}>
+ <BannerButton onClick={() => void revertFile(activeTab.fileKey)}>{t("code_editor.conflict_load_disk")}</BannerButton>
+ <BannerButton onClick={() => void saveFile(activeTab.fileKey, { overwrite: true })}>{t("code_editor.conflict_keep_mine")}</BannerButton>
+ </Banner>
+ )}
+ {activeFile?.deleted && !activeFile.conflict && (
+ <Banner tone="muted" testId="code-editor-deleted" text={t("code_editor.deleted")} />
+ )}
+
+ <div className="relative min-h-0 flex-1">
+ <Suspense
+ fallback={
+ <p className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
+ {t("code_editor.starting")}
+ </p>
+ }
+ >
+ <EditorSurface tab={activeTab} onOpenExternally={openExternally} />
+ </Suspense>
+ </div>
+
+ <StatusBar fileKey={activeTab.fileKey} />
+ </div>
+
+ <ThreadPopover anchor={menuAnchor} open={menu !== null} onClose={() => setMenu(null)} label={t("code_editor.tab_menu")} width={230}>
+ {menu && (
+ <div role="menu">
+ <ThreadMenuItem icon={<X className="h-4 w-4" />} label={t("code_editor.menu.close")} hint="Ctrl+W" onSelect={() => { setMenu(null); requestClose([menu.key]); }} />
+ <ThreadMenuItem icon={<span aria-hidden />} label={t("code_editor.menu.close_others")} onSelect={() => { setMenu(null); requestClose(tabs.filter((tab) => tab.key !== menu.key).map((tab) => tab.key)); }} />
+ <ThreadMenuItem icon={<span aria-hidden />} label={t("code_editor.menu.close_saved")} onSelect={() => { setMenu(null); requestClose(tabs.filter((tab) => !files[tab.fileKey]?.dirty).map((tab) => tab.key)); }} />
+ <ThreadMenuItem icon={<span aria-hidden />} label={t("code_editor.menu.close_all")} onSelect={() => { setMenu(null); requestClose(tabs.map((tab) => tab.key)); }} />
+ <ThreadMenuSeparator />
+ <ThreadMenuItem icon={<Copy className="h-4 w-4" />} label={t("code_editor.menu.copy_path")} onSelect={() => { setMenu(null); copyText(absolute(menu.path)); }} />
+ <ThreadMenuItem icon={<span aria-hidden />} label={t("code_editor.menu.copy_relative_path")} onSelect={() => { setMenu(null); copyText(menu.path); }} />
+ <ThreadMenuItem icon={<FolderSearch className="h-4 w-4" />} label={t("code_editor.menu.reveal")} onSelect={() => { setMenu(null); revealInExplorer({ workspaceId, path: menu.path }); }} />
+ </div>
+ )}
+ </ThreadPopover>
+
+ {pending && (
+ <UnsavedDialog
+ count={pending.fileKeys.length}
+ name={baseName(files[pending.fileKeys[0]]?.path ?? "")}
+ onCancel={() => setPending(null)}
+ onDiscard={() => {
+ for (const key of pending.fileKeys) discardFile(key);
+ useCodeEditorStore.getState().closeTabs(pending.keys);
+ setPending(null);
+ }}
+ onSave={async () => {
+ const results = await Promise.all(pending.fileKeys.map((key) => saveFile(key)));
+ setPending(null);
+ if (results.every(Boolean)) useCodeEditorStore.getState().closeTabs(pending.keys);
+ }}
+ />
+ )}
+ {quick}
+ </>
+ );
+}
+
+function ActionButton({ onClick, icon, label, iconOnly = false }: { onClick: () => void; icon: ReactNode; label: string; iconOnly?: boolean }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ title={label}
+ aria-label={label}
+ className="inline-flex h-6 shrink-0 items-center gap-1.5 rounded px-1.5 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {icon}
+ {!iconOnly && <span className="hidden xl:inline">{label}</span>}
+ </button>
+ );
+}
+
+function Banner({ tone, text, testId, children }: { tone: "warning" | "muted"; text: string; testId: string; children?: ReactNode }) {
+ return (
+ <div
+ role="status"
+ data-testid={testId}
+ className={cn(
+ "flex shrink-0 flex-wrap items-center gap-2 border-b px-3 py-1.5 text-xs",
+ tone === "warning" ? "border-warning/40 bg-warning/10 text-foreground" : "border-border/60 bg-secondary/60 text-muted-foreground",
+ )}
+ >
+ <AlertTriangle className={cn("h-3.5 w-3.5 shrink-0", tone === "warning" ? "text-warning" : "text-muted-foreground")} aria-hidden />
+ <span className="min-w-0 flex-1">{text}</span>
+ {children}
+ </div>
+ );
+}
+
+function BannerButton({ onClick, children }: { onClick: () => void; children: ReactNode }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className="inline-flex h-6 items-center rounded-md border border-border bg-background px-2 text-xs text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {children}
+ </button>
+ );
+}
+
+function StatusBar({ fileKey }: { fileKey: string }) {
+ const t = useT();
+ const file = useCodeEditorStore((state) => state.files[fileKey]);
+ const cursor = useCodeEditorStore((state) => state.cursor);
+ if (!file) return null;
+ const ready = file.status === "ready" && cursor;
+ return (
+ <div
+ data-testid="code-editor-status"
+ className="flex h-6 shrink-0 items-center gap-3 border-t border-border/60 bg-sidebar px-3 text-[11px] tabular-nums text-muted-foreground"
+ >
+ <span className="min-w-0 flex-1 truncate">
+ {file.saving ? t("code_editor.status.saving") : file.dirty ? t("code_editor.status.unsaved") : file.status === "ready" ? t("code_editor.status.saved") : ""}
+ </span>
+ {ready && (
+ <>
+ <span>
+ {fill(t("code_editor.status.position"), { line: String(cursor.line), column: String(cursor.column) })}
+ {cursor.selected > 0 && ` ${fill(t("code_editor.status.selected"), { count: String(cursor.selected) })}`}
+ </span>
+ <span>{cursor.insertSpaces ? fill(t("code_editor.status.spaces"), { size: String(cursor.tabSize) }) : fill(t("code_editor.status.tabs"), { size: String(cursor.tabSize) })}</span>
+ <span>{file.encoding === "utf-8-sig" ? t("code_editor.status.utf8_bom") : "UTF-8"}</span>
+ <span>{file.eol === "\r\n" ? "CRLF" : "LF"}</span>
+ <span>{languageName(cursor.language)}</span>
+ </>
+ )}
+ </div>
+ );
+}
+
+function UnsavedDialog({
+ count,
+ name,
+ onSave,
+ onDiscard,
+ onCancel,
+}: {
+ count: number;
+ name: string;
+ onSave: () => void;
+ onDiscard: () => void;
+ onCancel: () => void;
+}) {
+ const t = useT();
+ const saveButton = useRef<HTMLButtonElement>(null);
+ useEffect(() => saveButton.current?.focus(), []);
+ return (
+ <div
+ role="presentation"
+ className="fixed inset-0 z-[86] flex items-center justify-center bg-background/60 p-4"
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ onCancel();
+ }
+ }}
+ >
+ <section
+ role="alertdialog"
+ aria-modal="true"
+ aria-labelledby="code-editor-unsaved-title"
+ data-testid="code-editor-unsaved"
+ className="w-full max-w-sm rounded-xl border border-border bg-popover p-4 text-popover-foreground shadow-float"
+ >
+ <h2 id="code-editor-unsaved-title" className="text-sm font-semibold text-foreground-strong">
+ {count === 1 ? fill(t("code_editor.unsaved.title_one"), { file: name }) : fill(t("code_editor.unsaved.title_many"), { count: String(count) })}
+ </h2>
+ <p className="mt-1.5 text-xs text-muted-foreground">{t("code_editor.unsaved.body")}</p>
+ <div className="mt-4 flex justify-end gap-2">
+ <button type="button" onClick={onCancel} className="h-8 rounded-md px-3 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ {t("code_editor.unsaved.cancel")}
+ </button>
+ <button type="button" onClick={onDiscard} className="h-8 rounded-md border border-border px-3 text-xs text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ {t("code_editor.unsaved.discard")}
+ </button>
+ <button ref={saveButton} type="button" onClick={onSave} className="h-8 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ {t("code_editor.unsaved.save")}
+ </button>
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx b/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx
new file mode 100644
index 0000000000..284ba7db04
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx
@@ -0,0 +1,216 @@
+import { useEffect, useRef, type MouseEvent } from "react";
+import { ExternalLink, FileWarning, Loader2 } from "lucide-react";
+
+import { fill, useT } from "@/i18n";
+import { workspaceFileUrl } from "@/lib/agenticIdeApi";
+import { cn } from "@/lib/utils";
+import { useCodeEditorStore, type EditorTab } from "@/store/codeEditor";
+import { languageFor, loadFile, loadHead, modelOf, rememberViewState, viewStateOf } from "./editorModels";
+import { EDITOR_OPTIONS, applyTheme, monaco } from "./monacoRuntime";
+
+type CodeEditor = monaco.editor.ICodeEditor;
+
+/** Report the cursor, selection and indentation to the status bar. */
+function reportCursor(editor: CodeEditor): void {
+ const model = editor.getModel();
+ const position = editor.getPosition();
+ if (!model || !position) {
+ useCodeEditorStore.getState().setCursor(null);
+ return;
+ }
+ const selected = (editor.getSelections() ?? []).reduce((sum, range) => sum + model.getValueLengthInRange(range), 0);
+ const options = model.getOptions();
+ useCodeEditorStore.getState().setCursor({
+ line: position.lineNumber,
+ column: position.column,
+ selected,
+ language: model.getLanguageId(),
+ insertSpaces: options.insertSpaces,
+ tabSize: options.tabSize,
+ });
+}
+
+function watchCursor(editor: CodeEditor): monaco.IDisposable[] {
+ return [
+ editor.onDidChangeCursorSelection(() => reportCursor(editor)),
+ editor.onDidChangeModel(() => reportCursor(editor)),
+ editor.onDidChangeModelOptions(() => reportCursor(editor)),
+ ];
+}
+
+// Monaco draws its own context menu; the app-wide edit menu must not open on top.
+const keepContextMenu = (event: MouseEvent) => event.stopPropagation();
+
+/**
+ * The text area of the code editor: one long-lived editor for every edit tab
+ * (switching tabs swaps the model and restores that tab's cursor and scroll)
+ * and one diff editor, created the first time a Changes entry is opened.
+ */
+export default function EditorSurface({
+ tab,
+ onOpenExternally,
+}: {
+ tab: EditorTab;
+ onOpenExternally: (path: string) => void;
+}) {
+ const t = useT();
+ const codeHost = useRef<HTMLDivElement>(null);
+ const diffHost = useRef<HTMLDivElement>(null);
+ const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
+ const diffRef = useRef<monaco.editor.IStandaloneDiffEditor | null>(null);
+ const shown = useRef<string | null>(null);
+ const handledReveal = useRef(0);
+ const file = useCodeEditorStore((state) => state.files[tab.fileKey]);
+ const reveal = useCodeEditorStore((state) => state.reveal);
+ const status = file?.status ?? "loading";
+ const ready = status === "ready";
+
+ // Follow the app's light/dark switch. Watching the class on <html> (not a
+ // prop) matters: the theme provider repaints the document in its own effect,
+ // which runs after this component's, so a prop-driven re-read would still see
+ // the previous theme's colours.
+ useEffect(() => {
+ const root = document.documentElement;
+ const sync = () => applyTheme(root.classList.contains("dark"));
+ sync();
+ const observer = new MutationObserver(sync);
+ observer.observe(root, { attributes: true, attributeFilter: ["class", "style"] });
+ return () => observer.disconnect();
+ }, []);
+
+ useEffect(() => {
+ const editor = monaco.editor.create(codeHost.current!, { ...EDITOR_OPTIONS, model: null, theme: "jarvis" });
+ editorRef.current = editor;
+ const watchers = watchCursor(editor);
+ return () => {
+ if (shown.current) rememberViewState(shown.current, editor.saveViewState());
+ for (const watcher of watchers) watcher.dispose();
+ editor.dispose();
+ diffRef.current?.dispose();
+ diffRef.current = null;
+ editorRef.current = null;
+ useCodeEditorStore.getState().setCursor(null);
+ };
+ }, []);
+
+ useEffect(() => {
+ if (status === "loading") void loadFile(tab.fileKey);
+ }, [tab.fileKey, status]);
+
+ // Edit tabs: put this tab's model into the shared editor.
+ useEffect(() => {
+ const editor = editorRef.current;
+ const model = modelOf(tab.fileKey);
+ if (tab.mode !== "edit" || !ready || !editor || !model) return;
+ if (editor.getModel() !== model || shown.current !== tab.key) {
+ if (shown.current && editor.getModel()) rememberViewState(shown.current, editor.saveViewState());
+ editor.setModel(model);
+ const state = viewStateOf(tab.key);
+ if (state) editor.restoreViewState(state);
+ shown.current = tab.key;
+ }
+ reportCursor(editor);
+ editor.focus();
+ }, [tab.key, tab.fileKey, tab.mode, ready]);
+
+ // Diff tabs: the committed text on the left, the live (editable) buffer on the right.
+ useEffect(() => {
+ if (tab.mode !== "diff" || !ready) return;
+ let alive = true;
+ let watchers: monaco.IDisposable[] = [];
+ void loadHead(tab.fileKey).then((original) => {
+ const modified = modelOf(tab.fileKey);
+ if (!alive || !original || !modified || !diffHost.current) return;
+ let diff = diffRef.current;
+ if (!diff) {
+ diff = monaco.editor.createDiffEditor(diffHost.current, {
+ ...EDITOR_OPTIONS,
+ minimap: { enabled: false },
+ originalEditable: false,
+ renderSideBySide: true,
+ useInlineViewWhenSpaceIsLimited: true,
+ renderSideBySideInlineBreakpoint: 900,
+ theme: "jarvis",
+ });
+ diffRef.current = diff;
+ }
+ diff.setModel({ original, modified });
+ const right = diff.getModifiedEditor();
+ watchers = watchCursor(right);
+ reportCursor(right);
+ right.focus();
+ });
+ return () => {
+ alive = false;
+ for (const watcher of watchers) watcher.dispose();
+ };
+ }, [tab.key, tab.fileKey, tab.mode, ready]);
+
+ // "Open at line": a Ctrl+click on `file.py:42` in a terminal, or Quick Open's `name:42`.
+ useEffect(() => {
+ if (!ready || !reveal || reveal.fileKey !== tab.fileKey || reveal.nonce === handledReveal.current) return;
+ const editor = tab.mode === "diff" ? diffRef.current?.getModifiedEditor() : editorRef.current;
+ if (!editor || editor.getModel() !== modelOf(tab.fileKey)) return;
+ handledReveal.current = reveal.nonce;
+ const position = { lineNumber: reveal.line, column: reveal.column };
+ editor.setPosition(position);
+ editor.revealPositionInCenter(position);
+ editor.focus();
+ }, [reveal, ready, tab.fileKey, tab.mode, tab.key]);
+
+ const notice = (() => {
+ if (status === "loading") {
+ return (
+ <p className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
+ {t("code_editor.loading")}
+ </p>
+ );
+ }
+ if (status === "image") {
+ return (
+ <img
+ src={workspaceFileUrl(tab.workspaceId, tab.path)}
+ alt={tab.path.split("/").pop() ?? tab.path}
+ className="max-h-full max-w-full rounded-md border border-border/60 object-contain"
+ />
+ );
+ }
+ if (status === "ready") return null;
+ const message =
+ status === "binary"
+ ? t("code_editor.binary")
+ : status === "too_large"
+ ? t("code_editor.too_large")
+ : fill(t("code_editor.load_failed"), { error: file?.error ?? "" });
+ return (
+ <div className="flex max-w-sm flex-col items-center gap-3 text-center">
+ <FileWarning className="h-8 w-8 text-muted-foreground/70" aria-hidden />
+ <p className="text-sm text-muted-foreground">{message}</p>
+ {status !== "error" && (
+ <button
+ type="button"
+ onClick={() => onOpenExternally(tab.path)}
+ className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border px-3 text-xs text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <ExternalLink className="h-3.5 w-3.5" aria-hidden />
+ {t("code_editor.open_externally")}
+ </button>
+ )}
+ </div>
+ );
+ })();
+
+ const showCode = ready && tab.mode === "edit";
+ return (
+ <div className="relative h-full min-h-0 w-full" data-testid="code-editor-surface" data-language={languageFor(tab.path)}>
+ <div ref={codeHost} onContextMenu={keepContextMenu} className={cn("absolute inset-0", !showCode && "invisible")} />
+ <div
+ ref={diffHost}
+ onContextMenu={keepContextMenu}
+ className={cn("absolute inset-0", tab.mode !== "diff" && "invisible", !ready && "invisible")}
+ />
+ {notice && <div className="absolute inset-0 flex items-center justify-center p-6">{notice}</div>}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/QuickOpen.tsx b/jarvis/ui/web/frontend/src/components/agentic/editor/QuickOpen.tsx
new file mode 100644
index 0000000000..442164541e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/QuickOpen.tsx
@@ -0,0 +1,148 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useShallow } from "zustand/react/shallow";
+import { Loader2, Search } from "lucide-react";
+
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { tabsOf, useCodeEditorStore } from "@/store/codeEditor";
+import { FileTypeIcon } from "@/components/agentic/sidePanel/explorer/FileTypeIcon";
+import { fetchFileList } from "./editorApi";
+import { parseQuickOpen, rankPaths } from "./quickOpenMatch";
+
+/** A listing is reused for this long, so Ctrl+P twice in a row opens instantly. */
+const LIST_TTL_MS = 20_000;
+const listCache = new Map<string, { at: number; paths: string[]; truncated: boolean }>();
+
+/** Drop a workspace's cached listing after the explorer created, renamed or deleted something. */
+export function forgetFileList(workspaceId: string): void {
+ listCache.delete(workspaceId);
+}
+
+/**
+ * Go to File (Ctrl+P): type part of a name, Enter opens it. `name:42` opens at
+ * line 42. With nothing typed the open tabs are offered first.
+ */
+export function QuickOpen({ workspaceId }: { workspaceId: string }) {
+ const t = useT();
+ const close = () => useCodeEditorStore.getState().setQuickOpen(false);
+ const openTabs = useCodeEditorStore(useShallow((state) => tabsOf(state, workspaceId)));
+ const [query, setQuery] = useState("");
+ const [paths, setPaths] = useState<string[] | null>(() => listCache.get(workspaceId)?.paths ?? null);
+ const [error, setError] = useState("");
+ const [cursor, setCursor] = useState(0);
+ const input = useRef<HTMLInputElement>(null);
+ const list = useRef<HTMLUListElement>(null);
+
+ useEffect(() => {
+ input.current?.focus();
+ const cached = listCache.get(workspaceId);
+ if (cached && Date.now() - cached.at < LIST_TTL_MS) return;
+ let alive = true;
+ fetchFileList(workspaceId)
+ .then((answer) => {
+ listCache.set(workspaceId, { at: Date.now(), ...answer });
+ if (alive) setPaths(answer.paths);
+ })
+ .catch((err: unknown) => alive && setError((err as Error).message));
+ return () => {
+ alive = false;
+ };
+ }, [workspaceId]);
+
+ const parsed = parseQuickOpen(query);
+ const results = useMemo(() => {
+ if (!parsed.needle) {
+ const recent = [...openTabs].reverse().map((tab) => tab.path);
+ const unique = [...new Set(recent)];
+ return [...unique, ...(paths ?? []).filter((path) => !unique.includes(path))].slice(0, 50);
+ }
+ return rankPaths(paths ?? [], parsed.needle);
+ }, [parsed.needle, paths, openTabs]);
+
+ useEffect(() => setCursor(0), [parsed.needle]);
+ useEffect(() => {
+ list.current?.querySelector<HTMLElement>(`[data-index="${cursor}"]`)?.scrollIntoView({ block: "nearest" });
+ }, [cursor]);
+
+ const choose = (path: string | undefined) => {
+ if (!path) return;
+ close();
+ useCodeEditorStore.getState().openFile(workspaceId, path, { preview: false, line: parsed.line, column: parsed.column });
+ };
+
+ return (
+ <div
+ role="presentation"
+ className="fixed inset-0 z-[85] flex justify-center bg-background/40 px-4 pt-[12vh]"
+ onMouseDown={(event) => {
+ if (event.target === event.currentTarget) close();
+ }}
+ >
+ <section
+ role="dialog"
+ aria-modal="true"
+ aria-label={t("code_editor.quick_open.title")}
+ data-testid="code-editor-quick-open"
+ className="flex h-fit max-h-[60vh] w-full max-w-[620px] flex-col overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-float"
+ >
+ <label className="flex h-11 shrink-0 items-center gap-2 border-b border-border/70 px-3">
+ <Search className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
+ <input
+ ref={input}
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ event.preventDefault();
+ const step = event.key === "ArrowDown" ? 1 : -1;
+ setCursor((current) => Math.max(0, Math.min(results.length - 1, current + step)));
+ } else if (event.key === "Enter") {
+ event.preventDefault();
+ choose(results[cursor]);
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ close();
+ }
+ }}
+ placeholder={t("code_editor.quick_open.placeholder")}
+ aria-label={t("code_editor.quick_open.placeholder")}
+ aria-controls="code-editor-quick-open-list"
+ aria-activedescendant={results.length ? `quick-open-${cursor}` : undefined}
+ className="min-w-0 flex-1 bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground"
+ />
+ {!paths && !error && <Loader2 className="h-4 w-4 shrink-0 animate-spin text-muted-foreground" aria-hidden />}
+ </label>
+ <ul ref={list} id="code-editor-quick-open-list" role="listbox" className="scrollbar-jarvis min-h-0 flex-1 overflow-y-auto py-1">
+ {error && <li className="px-3 py-2 text-xs text-destructive">{error}</li>}
+ {paths && results.length === 0 && <li className="px-3 py-2 text-xs text-muted-foreground">{t("code_editor.quick_open.no_match")}</li>}
+ {results.map((path, index) => {
+ const slash = path.lastIndexOf("/");
+ return (
+ <li
+ key={path}
+ id={`quick-open-${index}`}
+ data-index={index}
+ role="option"
+ aria-selected={index === cursor}
+ onMouseMove={() => setCursor(index)}
+ onMouseDown={(event) => {
+ event.preventDefault();
+ choose(path);
+ }}
+ className={cn(
+ "flex h-8 cursor-pointer items-center gap-2 px-3 text-[13px]",
+ index === cursor && "bg-secondary",
+ )}
+ >
+ <FileTypeIcon path={path} />
+ <span className="shrink-0 text-foreground">{path.slice(slash + 1)}</span>
+ {slash > 0 && <span className="min-w-0 truncate text-xs text-muted-foreground">{path.slice(0, slash)}</span>}
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts
new file mode 100644
index 0000000000..f98d24a1b0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts
@@ -0,0 +1,142 @@
+/** The code editor's file reads and writes against an open workspace. */
+
+export type TextEncoding = "utf-8" | "utf-8-sig";
+export type LineEnding = "\n" | "\r\n";
+
+export interface TextFile {
+ workspace_id: string;
+ /** POSIX path relative to the workspace root. */
+ path: string;
+ /** Exact file text; null when the file is binary or too large to edit. */
+ text: string | null;
+ /** Content hash; a save names it so an agent's edit is never overwritten. */
+ version: string;
+ size: number;
+ encoding: TextEncoding;
+ eol: LineEnding;
+ binary: boolean;
+ too_large: boolean;
+}
+
+/** A save was refused because the file changed on disk since it was loaded. */
+export class SaveConflictError extends Error {
+ constructor(
+ message: string,
+ /** The file's version now; null when it was deleted. */
+ readonly currentVersion: string | null,
+ ) {
+ super(message);
+ this.name = "SaveConflictError";
+ }
+}
+
+/** A delete was refused because this computer has no trash to move it to. */
+export class TrashUnavailableError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "TrashUnavailableError";
+ }
+}
+
+const base = (workspaceId: string) => `/api/agentic-ide/workspaces/${encodeURIComponent(workspaceId)}`;
+const query = (path: string) => new URLSearchParams({ path }).toString();
+
+async function failure(res: Response): Promise<{ message: string; detail: unknown }> {
+ let detail: unknown = null;
+ try {
+ detail = ((await res.json()) as { detail?: unknown }).detail ?? null;
+ } catch {
+ /* the status code is all there is */
+ }
+ const message =
+ typeof detail === "string"
+ ? detail
+ : detail && typeof detail === "object" && typeof (detail as { message?: unknown }).message === "string"
+ ? (detail as { message: string }).message
+ : `Request failed (${res.status}).`;
+ return { message, detail };
+}
+
+async function send<T>(url: string, init?: RequestInit): Promise<T> {
+ const res = await fetch(url, { cache: "no-store", ...init });
+ if (!res.ok) throw new Error((await failure(res)).message);
+ return (await res.json()) as T;
+}
+
+function json(method: string, body: unknown): RequestInit {
+ return { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
+}
+
+export function loadTextFile(workspaceId: string, path: string): Promise<TextFile> {
+ return send<TextFile>(`${base(workspaceId)}/text-file?${query(path)}`);
+}
+
+/** The file's version on disk now; null when it no longer exists. */
+export async function fetchFileVersion(workspaceId: string, path: string): Promise<string | null> {
+ const answer = await send<{ version: string | null }>(`${base(workspaceId)}/text-file/version?${query(path)}`);
+ return answer.version;
+}
+
+export interface SaveRequest {
+ path: string;
+ text: string;
+ expectedVersion: string | null;
+ encoding: TextEncoding;
+ /** Allowed to create the file when it does not exist (a new or deleted file). */
+ create?: boolean;
+}
+
+export async function saveTextFile(workspaceId: string, request: SaveRequest): Promise<TextFile> {
+ const res = await fetch(
+ `${base(workspaceId)}/text-file`,
+ json("PUT", {
+ path: request.path,
+ text: request.text,
+ expected_version: request.expectedVersion,
+ encoding: request.encoding,
+ create: request.create ?? false,
+ }),
+ );
+ if (res.status === 409) {
+ const { message, detail } = await failure(res);
+ const current = (detail as { current_version?: string | null } | null)?.current_version ?? null;
+ throw new SaveConflictError(message, current);
+ }
+ if (!res.ok) throw new Error((await failure(res)).message);
+ return (await res.json()) as TextFile;
+}
+
+/** The file's text at the last commit; null for a file git does not know. */
+export async function fetchHeadText(workspaceId: string, path: string): Promise<string | null> {
+ const answer = await send<{ text: string | null }>(`${base(workspaceId)}/head-text?${query(path)}`);
+ return answer.text;
+}
+
+export interface FileList {
+ paths: string[];
+ truncated: boolean;
+}
+
+export function fetchFileList(workspaceId: string): Promise<FileList> {
+ return send<FileList>(`${base(workspaceId)}/file-list`);
+}
+
+export function createEntry(workspaceId: string, path: string, kind: "file" | "directory"): Promise<{ path: string }> {
+ return send(`${base(workspaceId)}/entries`, json("POST", { path, kind }));
+}
+
+export function moveEntry(workspaceId: string, source: string, destination: string): Promise<{ path: string }> {
+ return send(`${base(workspaceId)}/entries/move`, json("POST", { source, destination }));
+}
+
+/** Move to the system trash, or delete for good when `permanent` is set. */
+export async function deleteEntry(workspaceId: string, path: string, permanent = false): Promise<{ trashed: boolean }> {
+ const res = await fetch(`${base(workspaceId)}/entries/delete`, json("POST", { path, permanent }));
+ if (res.status === 409) {
+ const { message, detail } = await failure(res);
+ if ((detail as { trash_unavailable?: boolean } | null)?.trash_unavailable) throw new TrashUnavailableError(message);
+ throw new Error(message);
+ }
+ if (!res.ok) throw new Error((await failure(res)).message);
+ return (await res.json()) as { trashed: boolean };
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts
new file mode 100644
index 0000000000..f22b797489
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts
@@ -0,0 +1,346 @@
+import type * as Monaco from "monaco-editor/editor/editor.api";
+
+import { useEventStore } from "@/store/events";
+import { useCodeEditorStore, type EditorFile } from "@/store/codeEditor";
+import {
+ SaveConflictError,
+ fetchFileVersion,
+ fetchHeadText,
+ loadTextFile,
+ saveTextFile,
+ type LineEnding,
+} from "./editorApi";
+
+/**
+ * The open files' text, held in the editor engine's models.
+ *
+ * Only a TYPE import of the engine lives here, so this module stays in the main
+ * chunk and the multi-megabyte engine loads lazily with the editor surface,
+ * which hands it over through {@link setMonaco}. Until then nothing here can
+ * hold text, and nothing needs to: no file loads before the surface mounts.
+ *
+ * "Dirty" is computed the way desktop editors do it — the model's alternative
+ * version id against the one recorded at the last load or save — so undoing
+ * back to the saved text clears the dot again.
+ */
+type MonacoApi = typeof Monaco;
+
+interface Entry {
+ model: Monaco.editor.ITextModel;
+ /** Alternative version id at the last load or save; -1 = never saved as is. */
+ saved: number;
+ listener: Monaco.IDisposable;
+}
+
+let api: MonacoApi | null = null;
+const entries = new Map<string, Entry>();
+const heads = new Map<string, Monaco.editor.ITextModel>();
+const viewStates = new Map<string, Monaco.editor.ICodeEditorViewState | null>();
+
+export function setMonaco(monaco: MonacoApi): void {
+ api = monaco;
+}
+
+export function monacoApi(): MonacoApi | null {
+ return api;
+}
+
+const store = () => useCodeEditorStore.getState();
+
+const IMAGE_FILE = /\.(png|jpe?g|gif|webp|svg|bmp|ico|avif)$/i;
+
+export const isImagePath = (path: string) => IMAGE_FILE.test(path);
+
+/** The engine's language id for a file name, `plaintext` when nothing claims it. */
+export function languageFor(path: string): string {
+ if (!api) return "plaintext";
+ const name = (path.split("/").pop() ?? path).toLowerCase();
+ const dot = name.lastIndexOf(".");
+ const extension = dot > 0 ? name.slice(dot) : "";
+ const languages = api.languages.getLanguages();
+ const byName = languages.find((language) => language.filenames?.some((entry) => entry.toLowerCase() === name));
+ if (byName) return byName.id;
+ const byExtension =
+ extension && languages.find((language) => language.extensions?.some((entry) => entry.toLowerCase() === extension));
+ return byExtension ? byExtension.id : "plaintext";
+}
+
+/** A language id as people say it ("Python", "TypeScript"). */
+export function languageName(id: string): string {
+ const language = api?.languages.getLanguages().find((entry) => entry.id === id);
+ return language?.aliases?.[0] ?? id;
+}
+
+function uriFor(workspaceId: string, path: string, scheme = "file"): Monaco.Uri {
+ return api!.Uri.from({ scheme, path: `/${encodeURIComponent(workspaceId)}/${path}` });
+}
+
+function eolSequence(eol: LineEnding): Monaco.editor.EndOfLineSequence {
+ return eol === "\r\n" ? api!.editor.EndOfLineSequence.CRLF : api!.editor.EndOfLineSequence.LF;
+}
+
+function syncDirty(fileKey: string): void {
+ const entry = entries.get(fileKey);
+ const file = store().files[fileKey];
+ if (!entry || !file) return;
+ const dirty = entry.model.getAlternativeVersionId() !== entry.saved;
+ if (dirty !== file.dirty) store().patchFile(fileKey, { dirty });
+}
+
+function createEntry(
+ fileKey: string,
+ file: Pick<EditorFile, "workspaceId" | "path">,
+ text: string,
+ eol: LineEnding,
+ saved: boolean,
+): Entry {
+ const model = api!.editor.createModel(text, languageFor(file.path), uriFor(file.workspaceId, file.path));
+ // Text without a line break says nothing about its line ending; set it
+ // before the saved marker is taken so a fresh load is never dirty.
+ model.setEOL(eolSequence(eol));
+ const entry: Entry = {
+ model,
+ saved: saved ? model.getAlternativeVersionId() : -1,
+ listener: model.onDidChangeContent(() => syncDirty(fileKey)),
+ };
+ entries.set(fileKey, entry);
+ return entry;
+}
+
+export function modelOf(fileKey: string): Monaco.editor.ITextModel | null {
+ return entries.get(fileKey)?.model ?? null;
+}
+
+export function rememberViewState(tabKey: string, state: Monaco.editor.ICodeEditorViewState | null): void {
+ viewStates.set(tabKey, state);
+}
+
+export function viewStateOf(tabKey: string): Monaco.editor.ICodeEditorViewState | null {
+ return viewStates.get(tabKey) ?? null;
+}
+
+function disposeFile(fileKey: string): void {
+ const entry = entries.get(fileKey);
+ if (entry) {
+ entry.listener.dispose();
+ entry.model.dispose();
+ entries.delete(fileKey);
+ }
+ heads.get(fileKey)?.dispose();
+ heads.delete(fileKey);
+ for (const key of [...viewStates.keys()]) if (key.endsWith(`:${fileKey}`)) viewStates.delete(key);
+}
+
+// A file record leaving the store (its last tab closed) frees its models.
+useCodeEditorStore.subscribe((state, previous) => {
+ for (const key of Object.keys(previous.files)) if (!state.files[key]) disposeFile(key);
+});
+
+/** Put text read from disk into a buffer, keeping undo, and call it saved. */
+function replaceFromDisk(entry: Entry, text: string, eol: LineEnding): void {
+ const { model } = entry;
+ if (model.getValue() !== text) {
+ model.pushEOL(eolSequence(eol));
+ model.pushEditOperations([], [{ range: model.getFullModelRange(), text }], () => null);
+ model.pushStackElement();
+ }
+ entry.saved = model.getAlternativeVersionId();
+}
+
+function toast(message: string): void {
+ useEventStore.getState().pushToast("error", message);
+}
+
+/** Load a file's text from disk into its model (or record why it cannot be edited). */
+export async function loadFile(fileKey: string): Promise<void> {
+ const file = store().files[fileKey];
+ if (!file || !api) return;
+ if (isImagePath(file.path)) {
+ store().patchFile(fileKey, { status: "image" });
+ return;
+ }
+ try {
+ const loaded = await loadTextFile(file.workspaceId, file.path);
+ if (!store().files[fileKey]) return;
+ if (loaded.text === null) {
+ store().patchFile(fileKey, { status: loaded.too_large ? "too_large" : "binary", version: loaded.version });
+ return;
+ }
+ const existing = entries.get(fileKey);
+ if (existing) replaceFromDisk(existing, loaded.text, loaded.eol);
+ else createEntry(fileKey, file, loaded.text, loaded.eol, true);
+ store().patchFile(fileKey, {
+ status: "ready",
+ error: "",
+ version: loaded.version,
+ encoding: loaded.encoding,
+ eol: loaded.eol,
+ deleted: false,
+ conflict: null,
+ dirty: false,
+ });
+ } catch (error) {
+ if (!store().files[fileKey]) return;
+ // A file deleted on disk (a deleted entry in Changes) opens as an empty
+ // buffer marked deleted: its diff shows what was removed, and a save
+ // brings it back.
+ const missing = await fetchFileVersion(file.workspaceId, file.path).then(
+ (version) => version === null,
+ () => false,
+ );
+ if (missing && store().files[fileKey] && !entries.has(fileKey)) {
+ createEntry(fileKey, file, "", "\n", true);
+ store().patchFile(fileKey, { status: "ready", error: "", version: null, deleted: true, dirty: false });
+ return;
+ }
+ if (store().files[fileKey]) store().patchFile(fileKey, { status: "error", error: (error as Error).message });
+ }
+}
+
+/** The committed text a diff tab compares against; empty for a new file. */
+export async function loadHead(fileKey: string): Promise<Monaco.editor.ITextModel | null> {
+ const file = store().files[fileKey];
+ if (!file || !api) return null;
+ const cached = heads.get(fileKey);
+ if (cached) return cached;
+ let text: string | null = null;
+ try {
+ text = await fetchHeadText(file.workspaceId, file.path);
+ } catch (error) {
+ toast((error as Error).message);
+ }
+ if (!store().files[fileKey]) return null;
+ const model = api.editor.createModel(text ?? "", languageFor(file.path), uriFor(file.workspaceId, file.path, "jarvis-head"));
+ heads.set(fileKey, model);
+ return model;
+}
+
+/**
+ * Write a buffer to disk.
+ *
+ * `overwrite` is the conflict bar's "Keep mine": it saves over whatever is on
+ * disk now. Without it a save names the version it was based on, and a file an
+ * agent changed meanwhile turns into a conflict instead of being overwritten.
+ */
+export async function saveFile(fileKey: string, { overwrite = false } = {}): Promise<boolean> {
+ const file = store().files[fileKey];
+ const entry = entries.get(fileKey);
+ if (!file || !entry || file.saving) return false;
+ const expected = overwrite ? (file.conflict?.diskVersion ?? null) : file.version;
+ const create = overwrite ? file.conflict?.diskVersion == null : file.deleted || file.version === null;
+ const sent = entry.model.getAlternativeVersionId();
+ store().patchFile(fileKey, { saving: true });
+ try {
+ const saved = await saveTextFile(file.workspaceId, {
+ path: file.path,
+ text: entry.model.getValue(),
+ expectedVersion: expected,
+ encoding: file.encoding,
+ create,
+ });
+ entry.saved = sent;
+ store().patchFile(fileKey, {
+ saving: false,
+ version: saved.version,
+ eol: saved.eol,
+ deleted: false,
+ conflict: null,
+ dirty: entry.model.getAlternativeVersionId() !== sent,
+ });
+ return true;
+ } catch (error) {
+ if (error instanceof SaveConflictError) {
+ store().patchFile(fileKey, { saving: false, conflict: { diskVersion: error.currentVersion } });
+ } else {
+ store().patchFile(fileKey, { saving: false });
+ toast((error as Error).message);
+ }
+ return false;
+ }
+}
+
+export async function saveAll(workspaceId: string): Promise<void> {
+ const dirty = Object.entries(store().files).filter(([, file]) => file.workspaceId === workspaceId && file.dirty);
+ for (const [key] of dirty) await saveFile(key);
+}
+
+/** Throw the buffer away and show what is on disk now. */
+export async function revertFile(fileKey: string): Promise<void> {
+ const file = store().files[fileKey];
+ const entry = entries.get(fileKey);
+ if (!file || !entry) return;
+ try {
+ const loaded = await loadTextFile(file.workspaceId, file.path);
+ if (loaded.text === null) {
+ toast("The file on disk can no longer be edited here.");
+ return;
+ }
+ replaceFromDisk(entry, loaded.text, loaded.eol);
+ store().patchFile(fileKey, {
+ version: loaded.version,
+ encoding: loaded.encoding,
+ eol: loaded.eol,
+ deleted: false,
+ conflict: null,
+ dirty: false,
+ });
+ } catch (error) {
+ toast((error as Error).message);
+ }
+}
+
+/** Forget unsaved edits without touching disk (closing with "Don't save"). */
+export function discardFile(fileKey: string): void {
+ disposeFile(fileKey);
+ if (store().files[fileKey]) store().patchFile(fileKey, { dirty: false, status: "loading" });
+}
+
+/**
+ * Notice an agent's edit to an open file.
+ *
+ * A clean buffer quietly follows the disk, keeping its undo history and the
+ * view where it was; a buffer with unsaved edits gets a conflict bar instead.
+ */
+export async function checkDisk(fileKey: string): Promise<void> {
+ const before = store().files[fileKey];
+ if (!before || before.saving || before.status === "loading" || before.status === "error") return;
+ let version: string | null;
+ try {
+ version = await fetchFileVersion(before.workspaceId, before.path);
+ } catch {
+ return; // the next check asks again; a failed poll changes nothing
+ }
+ const file = store().files[fileKey];
+ if (!file || file.saving) return;
+ if (version === null) {
+ if (!file.deleted) store().patchFile(fileKey, { deleted: true });
+ return;
+ }
+ if (version === file.version && !file.deleted) return;
+ if (file.status !== "ready") {
+ await loadFile(fileKey);
+ return;
+ }
+ if (!file.dirty) await revertFile(fileKey);
+ else if (file.conflict?.diskVersion !== version) store().patchFile(fileKey, { conflict: { diskVersion: version } });
+}
+
+/**
+ * Carry open buffers along with an explorer rename, before the store moves
+ * the tabs: a moved file keeps its unsaved edits under its new name.
+ */
+export function moveModels(workspaceId: string, from: string, to: string): void {
+ if (!api) return;
+ const prefix = `${workspaceId}\u0000`;
+ for (const [fileKey, entry] of [...entries]) {
+ if (!fileKey.startsWith(prefix)) continue;
+ const path = fileKey.slice(prefix.length);
+ if (path !== from && !path.startsWith(`${from}/`)) continue;
+ const moved = to + path.slice(from.length);
+ const text = entry.model.getValue();
+ const eol = entry.model.getEOL() === "\r\n" ? "\r\n" : "\n";
+ const dirty = entry.model.getAlternativeVersionId() !== entry.saved;
+ disposeFile(fileKey);
+ createEntry(`${prefix}${moved}`, { workspaceId, path: moved }, text, eol, !dirty);
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/monacoRuntime.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/monacoRuntime.ts
new file mode 100644
index 0000000000..309482bb55
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/monacoRuntime.ts
@@ -0,0 +1,118 @@
+/**
+ * The Monaco editor engine, set up for the desktop app.
+ *
+ * Reached only through the lazily imported editor surface, so the engine's
+ * several megabytes never load on the app's boot path (AP-26) — only the first
+ * time someone opens a file. Everything is bundled locally: no CDN, so the
+ * editor works offline.
+ *
+ * Deliberately lean: the editor core with all its editing features, syntax
+ * highlighting for every language Monaco ships, and the JSON language service.
+ * The TypeScript, CSS and HTML language services would add about 9 MB of
+ * workers for completions that the coding agents beside the editor already
+ * provide.
+ */
+import * as monaco from "monaco-editor/editor/editor.api";
+import "monaco-editor/features/register.all";
+import "monaco-editor/languages/definitions/register.all";
+import "monaco-editor/languages/features/json/register";
+import EditorWorker from "monaco-editor/editor/editor.worker?worker";
+import JsonWorker from "monaco-editor/languages/features/json/json.worker?worker";
+
+import { setMonaco } from "./editorModels";
+
+declare global {
+ interface Window {
+ MonacoEnvironment?: { getWorker: (workerId: string, label: string) => Worker };
+ }
+}
+
+self.MonacoEnvironment = {
+ getWorker(_workerId: string, label: string) {
+ return label === "json" ? new JsonWorker() : new EditorWorker();
+ },
+};
+
+setMonaco(monaco);
+
+let probe: CanvasRenderingContext2D | null | undefined;
+
+/** A theme token (`--background: 0 0% 100%`) as the `#rrggbb[aa]` Monaco needs. */
+function tokenHex(name: string, fallback: string): string {
+ const raw = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+ if (!raw) return fallback;
+ if (probe === undefined) probe = document.createElement("canvas").getContext("2d");
+ if (!probe) return fallback;
+ // The canvas normalises any CSS colour; an unparseable one keeps the reset.
+ probe.fillStyle = fallback;
+ probe.fillStyle = /^[\d.]+(deg)?\s/.test(raw) ? `hsl(${raw})` : raw;
+ const value = String(probe.fillStyle);
+ if (value.startsWith("#")) return value;
+ const parts = value.match(/[\d.]+/g)?.map(Number) ?? [];
+ if (parts.length < 3) return fallback;
+ const [red, green, blue, alpha = 1] = parts;
+ return `#${[red, green, blue, Math.round(alpha * 255)].map((part) => part.toString(16).padStart(2, "0")).join("")}`;
+}
+
+/** Re-read the app's colour tokens into the editor theme (light or dark). */
+export function applyTheme(dark: boolean): void {
+ const background = tokenHex("--background", dark ? "#171717" : "#ffffff");
+ const foreground = tokenHex("--foreground", dark ? "#e5e5e5" : "#171717");
+ const muted = tokenHex("--muted-foreground", dark ? "#a3a3a3" : "#737373");
+ const border = tokenHex("--border", dark ? "#2e2e2e" : "#e5e5e5");
+ const lift = tokenHex("--secondary", dark ? "#262626" : "#f5f5f5");
+ const popover = tokenHex("--popover", background);
+ monaco.editor.defineTheme("jarvis", {
+ base: dark ? "vs-dark" : "vs",
+ inherit: true,
+ rules: [],
+ colors: {
+ "editor.background": background,
+ "editor.foreground": foreground,
+ "editorGutter.background": background,
+ "minimap.background": background,
+ "editorLineNumber.foreground": `${muted.slice(0, 7)}99`,
+ "editorLineNumber.activeForeground": foreground,
+ "editor.lineHighlightBackground": `${lift.slice(0, 7)}aa`,
+ "editor.lineHighlightBorder": "#00000000",
+ "editorIndentGuide.background1": border,
+ "editorWidget.background": popover,
+ "editorWidget.border": border,
+ "editorSuggestWidget.background": popover,
+ "editorSuggestWidget.border": border,
+ "editorHoverWidget.background": popover,
+ "editorHoverWidget.border": border,
+ "input.background": lift,
+ "input.border": border,
+ "focusBorder": border,
+ "scrollbar.shadow": "#00000000",
+ "diffEditor.border": border,
+ },
+ });
+ monaco.editor.setTheme("jarvis");
+}
+
+export const EDITOR_OPTIONS: monaco.editor.IEditorOptions & monaco.editor.IGlobalEditorOptions = {
+ automaticLayout: true,
+ fontFamily: '"JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
+ fontSize: 13,
+ lineHeight: 20,
+ minimap: { enabled: true, renderCharacters: false, maxColumn: 100 },
+ stickyScroll: { enabled: true },
+ bracketPairColorization: { enabled: true },
+ guides: { bracketPairs: "active", indentation: true },
+ smoothScrolling: true,
+ cursorSmoothCaretAnimation: "on",
+ renderWhitespace: "selection",
+ scrollBeyondLastLine: false,
+ padding: { top: 8, bottom: 8 },
+ // Hovers and the suggest list may overflow the editor's box instead of
+ // being clipped by the stage around it.
+ fixedOverflowWidgets: true,
+ // The app has no browser zoom, and Ctrl+wheel belongs to the app zoom.
+ mouseWheelZoom: false,
+ // The find widget floats over the text instead of pushing it down.
+ find: { addExtraSpaceOnTop: false, seedSearchStringFromSelection: "selection" },
+};
+
+export { monaco };
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/quickOpenMatch.test.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/quickOpenMatch.test.ts
new file mode 100644
index 0000000000..5da684e68c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/quickOpenMatch.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+
+import { parseQuickOpen, rankPaths, scorePath } from "./quickOpenMatch";
+
+const PATHS = [
+ "jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx",
+ "jarvis/agentic_ide/file_editing.py",
+ "tests/unit/agentic_ide/test_file_editing.py",
+ "docs/editing-guide.md",
+ "README.md",
+];
+
+describe("quick open matching", () => {
+ it("needs the letters in order", () => {
+ expect(scorePath("README.md", "rdm")).not.toBeNull();
+ expect(scorePath("README.md", "mdr")).toBeNull();
+ });
+
+ it("ranks a file-name hit above a hit spread over the folders", () => {
+ expect(rankPaths(PATHS, "fileediting")[0]).toBe("jarvis/agentic_ide/file_editing.py");
+ expect(rankPaths(PATHS, "readme")[0]).toBe("README.md");
+ expect(rankPaths(PATHS, "ideview")[0]).toBe("jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx");
+ });
+
+ it("reads a line and column after the name", () => {
+ expect(parseQuickOpen("app.ts:42")).toEqual({ needle: "app.ts", line: 42, column: undefined });
+ expect(parseQuickOpen(" src\\App .ts:3:9 ")).toEqual({ needle: "src/app.ts", line: 3, column: 9 });
+ expect(parseQuickOpen("app.ts")).toEqual({ needle: "app.ts", line: undefined, column: undefined });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/quickOpenMatch.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/quickOpenMatch.ts
new file mode 100644
index 0000000000..962bdb8634
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/quickOpenMatch.ts
@@ -0,0 +1,61 @@
+/**
+ * Quick Open's matching: the typed letters must appear in the path in order;
+ * hits in the file name, at word starts and in runs rank higher.
+ */
+
+const WORD_START = new Set(["/", "_", "-", ".", " "]);
+
+/** A score for `path` against a lowercased, space-free `query`; null when it does not match. */
+export function scorePath(path: string, query: string): number | null {
+ if (!query) return 0;
+ const lower = path.toLowerCase();
+ const nameStart = lower.lastIndexOf("/") + 1;
+ const name = lower.slice(nameStart);
+ let score = 0;
+ let from = 0;
+ let previous = -2;
+ for (const char of query) {
+ const index = lower.indexOf(char, from);
+ if (index < 0) return null;
+ score += 1;
+ if (index === previous + 1) score += 3;
+ if (index >= nameStart) score += 2;
+ if (index === 0 || WORD_START.has(lower[index - 1])) score += 2;
+ previous = index;
+ from = index + 1;
+ }
+ if (name.startsWith(query)) score += 15;
+ else if (name.includes(query)) score += 10;
+ // Shorter paths first among equals: `src/app.ts` before `src/legacy/old/app.ts`.
+ return score - path.length * 0.01;
+}
+
+export interface QuickOpenQuery {
+ needle: string;
+ line?: number;
+ column?: number;
+}
+
+/** Split `main.py:42:7` into what to match and where to jump. */
+export function parseQuickOpen(raw: string): QuickOpenQuery {
+ const trimmed = raw.trim();
+ const match = /^(.*?):(\d+)(?::(\d+))?$/.exec(trimmed);
+ const text = match ? match[1] : trimmed;
+ return {
+ needle: text.toLowerCase().replace(/\\/g, "/").replace(/\s+/g, ""),
+ line: match ? Number(match[2]) : undefined,
+ column: match?.[3] ? Number(match[3]) : undefined,
+ };
+}
+
+/** The best `limit` paths for a query, best first. */
+export function rankPaths(paths: readonly string[], needle: string, limit = 50): string[] {
+ if (!needle) return paths.slice(0, limit);
+ const scored: { path: string; score: number }[] = [];
+ for (const path of paths) {
+ const score = scorePath(path, needle);
+ if (score !== null) scored.push({ path, score });
+ }
+ scored.sort((a, b) => b.score - a.score);
+ return scored.slice(0, limit).map((entry) => entry.path);
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx
index 0705ae729d..79478aa7d1 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx
@@ -6,7 +6,8 @@ import { WORKSPACE_PATH_TYPE } from "@/components/agentic/paneDrop";
import { activateTerminalLink } from "@/lib/terminalLinks";
import { useEventStore } from "@/store/events";
import { useIdeChatStore } from "@/store/ideChat";
-import { useExplorerPathRouting, useIdeExplorerStore } from "@/store/ideExplorer";
+import { useCodeEditorStore } from "@/store/codeEditor";
+import { parsePrintedPath, useExplorerPathRouting } from "@/store/ideExplorer";
import { useIdeSidePanelStore } from "@/store/ideSidePanel";
const CHANGES = {
@@ -28,32 +29,14 @@ const CHANGES = {
],
};
-const DIFF = {
- workspace_id: "w1",
- path: "src/app.ts",
- status: "modified",
- binary: false,
- added: 1,
- removed: 1,
- truncated: false,
- hunks: [
- {
- header: "@@ -1,2 +1,2 @@",
- lines: [
- { kind: "ctx", text: "keep", old_no: 1, new_no: 1 },
- { kind: "del", text: "before", old_no: 2, new_no: null },
- { kind: "add", text: "after", old_no: null, new_no: 2 },
- ],
- },
- ],
-};
-
-const calls: string[] = [];
+const calls: { url: string; body: string }[] = [];
function respond(url: string): unknown {
if (url.includes("/changes")) return CHANGES;
- if (url.includes("/diff?")) return DIFF;
+ if (url.includes("/text-file/version")) return { version: url.includes("src") ? null : "v1" };
+ if (url.includes("/entries")) return { path: "src/new.ts", trashed: true };
if (url.includes("/files")) {
+ if (url.includes("?path=")) return { workspace_id: "w1", root_name: "app", path: "src", truncated: false, entries: [] };
return { workspace_id: "w1", root_name: "app", path: "", truncated: false, entries: [
{ name: "src", path: "src", is_directory: true, is_symlink: false },
{ name: "README.md", path: "README.md", is_directory: false, is_symlink: false },
@@ -64,14 +47,14 @@ function respond(url: string): unknown {
beforeEach(() => {
calls.length = 0;
- vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
- calls.push(url);
+ calls.push({ url, body: String(init?.body ?? "") });
return new Response(JSON.stringify(respond(url)), { status: 200, headers: { "Content-Type": "application/json" } });
}));
useEventStore.setState({ activeSection: "agentic-ide" });
useIdeChatStore.setState({ workspace: { id: "w1", name: "App", path: "/code/app" }, stagedPane: null });
- useIdeExplorerStore.setState({ opened: { changes: null, files: null } });
+ useCodeEditorStore.setState({ tabs: [], active: {}, files: {}, visible: false, reveal: null, closed: [] });
useIdeSidePanelStore.setState({ open: false, tabs: ["agents", "changes", "files"], active: "agents" });
});
@@ -111,15 +94,13 @@ describe("ExplorerPanel", () => {
expect(data[WORKSPACE_PATH_TYPE]).toBe("/code/app/src/app.ts");
});
- it("opens a changed file as a diff with removed and added lines", async () => {
+ it("opens a changed file as a diff tab in the code editor", async () => {
render(<ExplorerPanel view="changes" />);
const [row] = await screen.findAllByTestId("explorer-change-row");
fireEvent.click(row);
- const diff = await screen.findByTestId("explorer-diff");
- expect(diff.querySelector('[data-kind="del"]')?.textContent).toContain("before");
- expect(diff.querySelector('[data-kind="add"]')?.textContent).toContain("after");
- expect(diff.querySelector('[data-kind="del"]')?.className).toContain("bg-destructive/10");
- expect(diff.querySelector('[data-kind="add"]')?.className).toContain("bg-success/10");
+ const { tabs, visible } = useCodeEditorStore.getState();
+ expect(tabs).toMatchObject([{ path: "src/app.ts", mode: "diff", preview: true }]);
+ expect(visible).toBe(true);
});
it("shows the folder as a lazy tree in the Folder tab", async () => {
@@ -130,23 +111,79 @@ describe("ExplorerPanel", () => {
// The folder holds a change, so it carries the marker while collapsed.
await waitFor(() => expect(rows[0].querySelector(".bg-success\\/80")).not.toBeNull());
});
+
+ it("opens a file as a preview tab on click and keeps it on double click", async () => {
+ render(<ExplorerPanel view="files" />);
+ await waitFor(() => expect(screen.getAllByTestId("explorer-tree-row")).toHaveLength(2));
+ const readme = screen.getAllByTestId("explorer-tree-row")[1];
+ fireEvent.click(readme);
+ expect(useCodeEditorStore.getState().tabs).toMatchObject([{ path: "README.md", mode: "edit", preview: true }]);
+ fireEvent.doubleClick(readme);
+ expect(useCodeEditorStore.getState().tabs).toMatchObject([{ path: "README.md", preview: false }]);
+ });
+
+ it("creates a new file from the header and opens it", async () => {
+ render(<ExplorerPanel view="files" />);
+ await waitFor(() => expect(screen.getAllByTestId("explorer-tree-row")).toHaveLength(2));
+ fireEvent.click(screen.getByTestId("explorer-new-file"));
+ const field = await screen.findByTestId("explorer-name-field");
+ fireEvent.change(field, { target: { value: "src/new.ts" } });
+ fireEvent.keyDown(field, { key: "Enter" });
+ await waitFor(() => expect(useCodeEditorStore.getState().tabs).toMatchObject([{ path: "src/new.ts", preview: false }]));
+ const create = calls.find((call) => call.url.endsWith("/entries"));
+ expect(JSON.parse(create!.body)).toEqual({ path: "src/new.ts", kind: "file" });
+ });
+
+ it("asks before deleting and sends the file to the trash", async () => {
+ render(<ExplorerPanel view="files" />);
+ await waitFor(() => expect(screen.getAllByTestId("explorer-tree-row")).toHaveLength(2));
+ fireEvent.keyDown(screen.getAllByTestId("explorer-tree-row")[1], { key: "Delete" });
+ expect(calls.some((call) => call.url.includes("/entries/delete"))).toBe(false);
+ fireEvent.click(await screen.findByTestId("explorer-delete-confirm"));
+ await waitFor(() => expect(calls.some((call) => call.url.includes("/entries/delete"))).toBe(true));
+ const sent = calls.find((call) => call.url.includes("/entries/delete"));
+ expect(JSON.parse(sent!.body)).toEqual({ path: "README.md", permanent: false });
+ });
});
describe("terminal path clicks", () => {
- it("open the file in the Folder tab instead of the OS when the IDE is mounted", async () => {
+ it("open a printed file in the editor at its line", async () => {
renderHook(() => useExplorerPathRouting());
act(() =>
- activateTerminalLink(new MouseEvent("click", { button: 0, ctrlKey: true }), "src/app.ts", { workspaceId: "w1" }),
+ activateTerminalLink(new MouseEvent("click", { button: 0, ctrlKey: true }), "README.md:12:3", { workspaceId: "w1" }),
);
- expect(useIdeExplorerStore.getState().opened.files).toEqual({ workspaceId: "w1", path: "src/app.ts" });
- expect(useIdeSidePanelStore.getState()).toMatchObject({ open: true, active: "files" });
- expect(calls.some((url) => url.includes("terminal-target"))).toBe(false);
+ await waitFor(() => expect(useCodeEditorStore.getState().tabs).toMatchObject([{ path: "README.md", preview: false }]));
+ expect(useCodeEditorStore.getState().reveal).toMatchObject({ line: 12, column: 3 });
+ expect(calls.some((call) => call.url.includes("terminal-target"))).toBe(false);
+ });
+
+ it("show a printed folder in the Folder tab", async () => {
+ renderHook(() => useExplorerPathRouting());
+ act(() => activateTerminalLink(new MouseEvent("click", { button: 0, ctrlKey: true }), "src/", { workspaceId: "w1" }));
+ await waitFor(() => expect(useIdeSidePanelStore.getState()).toMatchObject({ open: true, active: "files" }));
+ expect(useCodeEditorStore.getState().tabs).toEqual([]);
});
it("fall back to the OS for another workspace's pane", () => {
renderHook(() => useExplorerPathRouting());
activateTerminalLink(new MouseEvent("click", { button: 0, ctrlKey: true }), "src/app.ts", { workspaceId: "w9" });
- expect(useIdeExplorerStore.getState().opened.files).toBeNull();
- expect(calls.some((url) => url.includes("terminal-target"))).toBe(true);
+ expect(useCodeEditorStore.getState().tabs).toEqual([]);
+ expect(calls.some((call) => call.url.includes("terminal-target"))).toBe(true);
+ });
+});
+
+describe("parsePrintedPath", () => {
+ it("reads line suffixes, absolute paths and file URIs", () => {
+ expect(parsePrintedPath("/code/app", "src/a.ts:4:2")).toEqual({ path: "src/a.ts", line: 4, column: 2 });
+ expect(parsePrintedPath("/code/app", "src/a.ts(7,1)")).toEqual({ path: "src/a.ts", line: 7, column: 1 });
+ expect(parsePrintedPath("/code/app", "/code/app/src/a.ts#L9")).toEqual({ path: "src/a.ts", line: 9, column: undefined });
+ expect(parsePrintedPath("C:\\Code\\App", "c:\\code\\app\\x.py:3")).toEqual({ path: "x.py", line: 3, column: undefined });
+ expect(parsePrintedPath("/code/app", "file:///code/app/b.md")).toMatchObject({ path: "b.md" });
+ });
+
+ it("refuses paths outside the workspace", () => {
+ expect(parsePrintedPath("/code/app", "/etc/passwd").path).toBeNull();
+ expect(parsePrintedPath("/code/app", "../secret.txt").path).toBeNull();
+ expect(parsePrintedPath("/code/app", "/code/application/x").path).toBeNull();
});
});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.tsx
index c037c38310..d98c4e4c74 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.tsx
@@ -1,44 +1,49 @@
-import { useCallback, useEffect, useMemo, useRef, useState, type DragEvent } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type DragEvent, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type ReactNode } from "react";
import {
- ArrowLeft,
ChevronRight,
+ ChevronsDownUp,
+ Copy,
ExternalLink,
+ FilePlus,
Folder,
FolderOpen,
+ FolderPlus,
GitBranch,
Loader2,
+ Pencil,
RefreshCw,
Search,
SquareArrowOutUpRight,
+ SquarePen,
+ Trash2,
X,
} from "lucide-react";
import { fill, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import {
attachToTerminal,
- fetchWorkspaceFilePreview,
fetchWorkspaceFiles,
openTerminalTarget,
- workspaceFileUrl,
type WorkspaceFileItem,
- type WorkspaceFilePreviewResponse,
} from "@/lib/agenticIdeApi";
import { WORKSPACE_PATH_TYPE } from "@/components/agentic/paneDrop";
import { AgentMark } from "@/components/agentic/AgentMark";
+import { createEntry, deleteEntry, moveEntry, TrashUnavailableError } from "@/components/agentic/editor/editorApi";
+import { moveModels } from "@/components/agentic/editor/editorModels";
+import { forgetFileList } from "@/components/agentic/editor/QuickOpen";
+import { ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "@/components/agentic/threads/ThreadPopover";
+import { useCodeEditorStore, isUnder } from "@/store/codeEditor";
import { useEventStore } from "@/store/events";
import { useIdeChatStore } from "@/store/ideChat";
import { useIdeExplorerStore, type ExplorerView } from "@/store/ideExplorer";
import { paneTitleFrom, recapsFor, usePaneRecapPoll, usePaneRecapsStore } from "@/store/paneRecaps";
import { useWorkspacePanesStore } from "@/store/workspacePanes";
-import { DiffView } from "./DiffView";
import {
absoluteWorkspacePath,
- fetchFileDiff,
fetchWorkspaceChanges,
type ChangeAuthor,
type ChangeStatus,
type ChangedFile,
- type FileDiff,
type WorkspaceChanges,
} from "./explorerApi";
import { FileTypeIcon } from "./FileTypeIcon";
@@ -65,6 +70,7 @@ const STATUS_LETTER: Record<ChangeStatus, string> = {
const baseName = (path: string) => path.split("/").filter(Boolean).pop() ?? path;
const parentPath = (path: string) => path.split("/").slice(0, -1).join("/");
+const joinPath = (folder: string, name: string) => (folder ? `${folder}/${name}` : name);
/** Start a drag that a terminal pane turns into a file reference. */
function startFileDrag(event: DragEvent, absolute: string): void {
@@ -170,25 +176,40 @@ function ChangeAuthors({ authors, workspaceId }: { authors: ChangeAuthor[]; work
);
}
+function HeaderButton({ label, onClick, children, testId }: { label: string; onClick: () => void; children: ReactNode; testId?: string }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ aria-label={label}
+ title={label}
+ data-testid={testId}
+ className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {children}
+ </button>
+ );
+}
+
/**
* The Changes tab (what the agents changed, and which agent) or the Folder tab
- * (the workspace's folder as a tree); either opens any file's diff — drag a
- * row onto a terminal to reference that file.
+ * (the workspace's folder as a tree). A click opens the file in the code
+ * editor — a changed file as its diff; drag a row onto a terminal to
+ * reference that file.
*/
export function ExplorerPanel({ view }: { view: ExplorerView }) {
const t = useT();
const workspace = useIdeChatStore((state) => state.workspace);
- const stagedPane = useIdeChatStore((state) => state.stagedPane);
- const opened = useIdeExplorerStore((state) => state.opened[view]);
- const openIn = useIdeExplorerStore((state) => state.open);
- const closeIn = useIdeExplorerStore((state) => state.close);
- const close = () => closeIn(view);
// Pane titles for the "changed by" line.
usePaneRecapPoll();
- const pushToast = useEventStore((state) => state.pushToast);
const [filter, setFilter] = useState("");
const workspaceId = workspace?.id ?? null;
const { changes, error: changesError, refresh } = useWorkspaceChanges(workspaceId);
+ const [treeNonce, setTreeNonce] = useState(0);
+ const [collapseNonce, setCollapseNonce] = useState(0);
+ const [creating, setCreating] = useState<{ folder: string; kind: "file" | "directory"; nonce: number } | null>(null);
+ const editorTabs = useCodeEditorStore((state) => (workspaceId ? state.tabs.filter((tab) => tab.workspaceId === workspaceId).length : 0));
+ const editorVisible = useCodeEditorStore((state) => state.visible);
const changeMap = useMemo(() => {
const map = new Map<string, ChangedFile>();
@@ -211,38 +232,10 @@ export function ExplorerPanel({ view }: { view: ExplorerView }) {
}
const absolute = (relative: string) => absoluteWorkspacePath(workspace.path, relative);
- const referenceInPane = async (relative: string) => {
- if (!stagedPane) return;
- try {
- await attachToTerminal(stagedPane, { paths: [absolute(relative)] });
- } catch (error) {
- pushToast("error", (error as Error).message);
- }
- };
-
- if (opened && opened.workspaceId === workspaceId) {
- return (
- <FileViewer
- workspaceId={workspaceId}
- path={opened.path}
- change={changeMap}
- onBack={close}
- onReference={stagedPane ? referenceInPane : undefined}
- referenceLabel={stagedPane ? fill(t("ide_side_panel.explorer.reference_in"), { pane: stagedPane }) : ""}
- onOpenExternally={(path) =>
- void openTerminalTarget(workspaceId, path).catch((error: unknown) =>
- pushToast("error", (error as Error).message),
- )
- }
- absolute={absolute}
- />
- );
- }
-
const needle = filter.trim().toLowerCase();
const changedFiles = (changes?.files ?? []).filter((file) => !needle || file.path.toLowerCase().includes(needle));
- const openFile = (path: string) => openIn(view, { workspaceId, path });
const changeCount = changes?.files.length ?? 0;
+ const editor = useCodeEditorStore.getState();
return (
<section
@@ -252,7 +245,7 @@ export function ExplorerPanel({ view }: { view: ExplorerView }) {
className="flex h-full min-h-0 flex-col"
>
<div className="shrink-0 space-y-2 border-b border-border/60 px-3 pb-2.5 pt-3">
- <div className="flex items-center gap-2">
+ <div className="flex items-center gap-1.5">
<FolderOpen className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
<span className="min-w-0 truncate text-sm font-semibold text-foreground" title={workspace.path}>
{baseName(workspace.path.replace(/\\/g, "/")) || workspace.name}
@@ -274,31 +267,68 @@ export function ExplorerPanel({ view }: { view: ExplorerView }) {
{changeCount}
</span>
)}
+ <span className="ml-auto flex shrink-0 items-center">
+ {view === "files" && (
+ <>
+ <HeaderButton label={t("ide_side_panel.explorer.new_file")} testId="explorer-new-file" onClick={() => setCreating({ folder: "", kind: "file", nonce: Date.now() })}>
+ <FilePlus className="h-3.5 w-3.5" aria-hidden />
+ </HeaderButton>
+ <HeaderButton label={t("ide_side_panel.explorer.new_folder")} onClick={() => setCreating({ folder: "", kind: "directory", nonce: Date.now() })}>
+ <FolderPlus className="h-3.5 w-3.5" aria-hidden />
+ </HeaderButton>
+ <HeaderButton label={t("ide_side_panel.explorer.collapse_all")} onClick={() => setCollapseNonce((value) => value + 1)}>
+ <ChevronsDownUp className="h-3.5 w-3.5" aria-hidden />
+ </HeaderButton>
+ </>
+ )}
+ <HeaderButton
+ label={t("ide_side_panel.explorer.refresh")}
+ onClick={() => {
+ refresh();
+ setTreeNonce((value) => value + 1);
+ forgetFileList(workspaceId);
+ }}
+ >
+ <RefreshCw className="h-3.5 w-3.5" aria-hidden />
+ </HeaderButton>
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <label className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-lg border border-border/60 bg-background/50 px-2.5 focus-within:border-ring">
+ <Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
+ <input
+ value={filter}
+ onChange={(event) => setFilter(event.target.value)}
+ placeholder={t("ide_side_panel.explorer.filter")}
+ aria-label={t("ide_side_panel.explorer.filter")}
+ className="min-w-0 flex-1 bg-transparent text-xs text-foreground outline-none placeholder:text-muted-foreground"
+ />
+ {filter && (
+ <button type="button" aria-label={t("ide_side_panel.explorer.clear_filter")} onClick={() => setFilter("")} className="text-muted-foreground hover:text-foreground">
+ <X className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ )}
+ </label>
<button
type="button"
- onClick={refresh}
- aria-label={t("ide_side_panel.explorer.refresh")}
- title={t("ide_side_panel.explorer.refresh")}
- className="ml-auto inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={() => editor.setQuickOpen(true)}
+ title={t("ide_side_panel.explorer.quick_open_hint")}
+ className="inline-flex h-8 shrink-0 items-center rounded-lg border border-border/60 px-2 text-[11px] text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
- <RefreshCw className="h-3.5 w-3.5" aria-hidden />
+ Ctrl+P
</button>
</div>
- <label className="flex h-8 items-center gap-2 rounded-lg border border-border/60 bg-background/50 px-2.5 focus-within:border-ring">
- <Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
- <input
- value={filter}
- onChange={(event) => setFilter(event.target.value)}
- placeholder={t("ide_side_panel.explorer.filter")}
- aria-label={t("ide_side_panel.explorer.filter")}
- className="min-w-0 flex-1 bg-transparent text-xs text-foreground outline-none placeholder:text-muted-foreground"
- />
- {filter && (
- <button type="button" aria-label={t("ide_side_panel.explorer.clear_filter")} onClick={() => setFilter("")} className="text-muted-foreground hover:text-foreground">
- <X className="h-3.5 w-3.5" aria-hidden />
- </button>
- )}
- </label>
+ {editorTabs > 0 && !editorVisible && (
+ <button
+ type="button"
+ data-testid="explorer-show-editor"
+ onClick={() => editor.setVisible(true)}
+ className="flex h-8 w-full items-center justify-center gap-1.5 rounded-lg border border-border/60 text-xs text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <SquarePen className="h-3.5 w-3.5" aria-hidden />
+ {fill(t("ide_side_panel.explorer.show_editor"), { count: editorTabs })}
+ </button>
+ )}
</div>
<div className="scrollbar-jarvis min-h-0 flex-1 overflow-y-auto py-1.5">
@@ -328,7 +358,8 @@ export function ExplorerPanel({ view }: { view: ExplorerView }) {
type="button"
draggable
onDragStart={(event) => startFileDrag(event, absolute(file.path))}
- onClick={() => !file.is_directory && openFile(file.path)}
+ onClick={() => !file.is_directory && editor.openFile(workspaceId, file.path, { mode: "diff" })}
+ onDoubleClick={() => !file.is_directory && editor.openFile(workspaceId, file.path, { mode: "diff", preview: false })}
data-testid="explorer-change-row"
data-path={file.path}
title={`${file.path} — ${t("ide_side_panel.explorer.drag_hint")}`}
@@ -372,7 +403,12 @@ export function ExplorerPanel({ view }: { view: ExplorerView }) {
filter={needle}
changeMap={changeMap}
changedFolders={changedFolders}
- onOpen={openFile}
+ changesKey={changes?.files.map((file) => `${file.path}:${file.status}`).join("|") ?? ""}
+ reloadNonce={treeNonce}
+ collapseNonce={collapseNonce}
+ creating={creating}
+ onCreatingDone={() => setCreating(null)}
+ onCreate={(folder, kind) => setCreating({ folder, kind, nonce: Date.now() })}
absolute={absolute}
/>
)}
@@ -386,17 +422,102 @@ interface TreeProps {
filter: string;
changeMap: Map<string, ChangedFile>;
changedFolders: Set<string>;
- onOpen: (path: string) => void;
+ /** Changes whenever git's list of changed files does: agents created or deleted something. */
+ changesKey: string;
+ reloadNonce: number;
+ collapseNonce: number;
+ creating: { folder: string; kind: "file" | "directory"; nonce: number } | null;
+ onCreatingDone: () => void;
+ onCreate: (folder: string, kind: "file" | "directory") => void;
absolute: (relative: string) => string;
}
-/** The folder, one lazily loaded level at a time. */
-function FileTree({ workspaceId, filter, changeMap, changedFolders, onOpen, absolute }: TreeProps) {
+type Row =
+ | { kind: "item"; item: WorkspaceFileItem; depth: number }
+ | { kind: "create"; folder: string; entry: "file" | "directory"; depth: number };
+
+/** The inline name field for a new entry or a rename. */
+function NameField({
+ initial,
+ depth,
+ icon,
+ onSubmit,
+ onCancel,
+}: {
+ initial: string;
+ depth: number;
+ icon: ReactNode;
+ onSubmit: (name: string) => void;
+ onCancel: () => void;
+}) {
+ const field = useRef<HTMLInputElement>(null);
+ const done = useRef(false);
+ useEffect(() => {
+ const input = field.current;
+ if (!input) return;
+ input.focus();
+ // Select the name without its extension, the way a rename usually wants it.
+ const dot = initial.lastIndexOf(".");
+ input.setSelectionRange(0, dot > 0 ? dot : initial.length);
+ }, [initial]);
+ const finish = (submit: boolean) => {
+ if (done.current) return;
+ done.current = true;
+ const value = field.current?.value.trim() ?? "";
+ if (submit && value && value !== initial) onSubmit(value);
+ else onCancel();
+ };
+ return (
+ <div style={{ paddingLeft: 10 + depth * 14 + 20 }} className="flex h-7 items-center gap-1.5 pr-3">
+ {icon}
+ <input
+ ref={field}
+ defaultValue={initial}
+ data-testid="explorer-name-field"
+ onKeyDown={(event) => {
+ event.stopPropagation();
+ if (event.key === "Enter") finish(true);
+ else if (event.key === "Escape") finish(false);
+ }}
+ onBlur={() => finish(true)}
+ className="min-w-0 flex-1 rounded border border-ring bg-background px-1.5 py-0.5 text-[13px] text-foreground outline-none"
+ />
+ </div>
+ );
+}
+
+/** The folder, one lazily loaded level at a time, with the usual file actions. */
+function FileTree({
+ workspaceId,
+ filter,
+ changeMap,
+ changedFolders,
+ changesKey,
+ reloadNonce,
+ collapseNonce,
+ creating,
+ onCreatingDone,
+ onCreate,
+ absolute,
+}: TreeProps) {
const t = useT();
+ const pushToast = useEventStore((state) => state.pushToast);
+ const stagedPane = useIdeChatStore((state) => state.stagedPane);
+ const activePath = useCodeEditorStore((state) => {
+ const key = state.active[workspaceId];
+ return state.tabs.find((tab) => tab.key === key)?.path ?? null;
+ });
+ const revealed = useIdeExplorerStore((state) => state.revealed);
const [children, setChildren] = useState<Record<string, WorkspaceFileItem[]>>({});
const [expanded, setExpanded] = useState<Set<string>>(() => new Set([""]));
const [loading, setLoading] = useState<Set<string>>(() => new Set());
const [error, setError] = useState("");
+ const [renaming, setRenaming] = useState<string | null>(null);
+ const [focused, setFocused] = useState<string | null>(null);
+ const [menu, setMenu] = useState<{ path: string; isDirectory: boolean } | null>(null);
+ const [confirm, setConfirm] = useState<{ path: string; isDirectory: boolean; permanent: boolean } | null>(null);
+ const menuAnchor = useRef<HTMLElement | null>(null);
+ const list = useRef<HTMLUListElement>(null);
const loaded = useRef<Set<string>>(new Set());
const load = useCallback(
@@ -406,7 +527,7 @@ function FileTree({ workspaceId, filter, changeMap, changedFolders, onOpen, abso
const answer = await fetchWorkspaceFiles(workspaceId, path);
loaded.current.add(path);
setChildren((current) => ({ ...current, [path]: answer.entries }));
- if (answer.error) setError(answer.error);
+ setError(answer.error ?? "");
} catch (err) {
setError((err as Error).message);
} finally {
@@ -427,30 +548,173 @@ function FileTree({ workspaceId, filter, changeMap, changedFolders, onOpen, abso
void load("");
}, [load]);
+ useEffect(() => {
+ if (collapseNonce) setExpanded(new Set([""]));
+ }, [collapseNonce]);
+
+ // Agents add and delete files all the time: re-read the open folders when
+ // git's picture changes, and on Refresh.
+ const expandedRef = useRef(expanded);
+ expandedRef.current = expanded;
+ const reloadOpen = useCallback(() => {
+ for (const path of loaded.current) if (expandedRef.current.has(path)) void load(path);
+ }, [load]);
+ const firstKey = useRef(true);
+ useEffect(() => {
+ if (firstKey.current) {
+ firstKey.current = false;
+ return;
+ }
+ reloadOpen();
+ }, [changesKey, reloadNonce, reloadOpen]);
+
+ const expand = useCallback(
+ (path: string) => {
+ setExpanded((current) => (current.has(path) ? current : new Set(current).add(path)));
+ if (!loaded.current.has(path)) void load(path);
+ },
+ [load],
+ );
+
const toggle = (path: string) => {
- setExpanded((current) => {
- const next = new Set(current);
- if (next.has(path)) next.delete(path);
- else {
- next.add(path);
- if (!loaded.current.has(path)) void load(path);
- }
- return next;
- });
+ if (expanded.has(path)) {
+ setExpanded((current) => {
+ const next = new Set(current);
+ next.delete(path);
+ return next;
+ });
+ } else expand(path);
};
- const rows: { item: WorkspaceFileItem; depth: number }[] = [];
+ // "Reveal in Explorer": open every folder above the path and scroll to it.
+ useEffect(() => {
+ if (!revealed || revealed.workspaceId !== workspaceId) return;
+ const parts = revealed.path.split("/");
+ for (let index = 1; index < parts.length; index += 1) expand(parts.slice(0, index).join("/"));
+ setFocused(revealed.path);
+ }, [revealed, workspaceId, expand]);
+
+ useEffect(() => {
+ if (!focused) return;
+ const rows = list.current?.querySelectorAll<HTMLElement>('[data-testid="explorer-tree-row"]') ?? [];
+ const row = [...rows].find((entry) => entry.dataset.path === focused);
+ row?.scrollIntoView?.({ block: "nearest" });
+ }, [focused, children]);
+
+ // The file on screen in the editor is shown in the tree, folders opened to it.
+ useEffect(() => {
+ if (!activePath) return;
+ const parts = activePath.split("/");
+ for (let index = 1; index < parts.length; index += 1) expand(parts.slice(0, index).join("/"));
+ setFocused(activePath);
+ }, [activePath, expand]);
+
+ // A new entry is typed inside its folder, so that folder must be open.
+ useEffect(() => {
+ if (creating?.folder) expand(creating.folder);
+ }, [creating, expand]);
+
+ const editor = useCodeEditorStore.getState();
+ const fail = (err: unknown) => pushToast("error", (err as Error).message);
+
+ const create = async (folder: string, kind: "file" | "directory", name: string) => {
+ onCreatingDone();
+ const path = joinPath(folder, name.replace(/\\/g, "/"));
+ try {
+ const created = await createEntry(workspaceId, path, kind);
+ forgetFileList(workspaceId);
+ // "a/b/c.ts" may have created folders on the way; re-read from the top one.
+ const top = joinPath(folder, path.slice(folder ? folder.length + 1 : 0).split("/")[0]);
+ await load(folder);
+ if (top !== created.path) expand(top);
+ setFocused(created.path);
+ if (kind === "file") editor.openFile(workspaceId, created.path, { preview: false });
+ } catch (err) {
+ fail(err);
+ }
+ };
+
+ const rename = async (path: string, name: string) => {
+ setRenaming(null);
+ const destination = joinPath(parentPath(path), name);
+ try {
+ const moved = await moveEntry(workspaceId, path, destination);
+ forgetFileList(workspaceId);
+ moveModels(workspaceId, path, moved.path);
+ editor.renamePath(workspaceId, path, moved.path);
+ setExpanded((current) => {
+ const next = new Set<string>();
+ for (const entry of current) next.add(isUnder(entry, path) ? moved.path + entry.slice(path.length) : entry);
+ return next;
+ });
+ loaded.current = new Set([...loaded.current].filter((entry) => !isUnder(entry, path)));
+ await load(parentPath(path));
+ setFocused(moved.path);
+ } catch (err) {
+ fail(err);
+ }
+ };
+
+ const remove = async (path: string, permanent: boolean) => {
+ setConfirm(null);
+ try {
+ await deleteEntry(workspaceId, path, permanent);
+ forgetFileList(workspaceId);
+ editor.markDeleted(workspaceId, path);
+ await load(parentPath(path));
+ } catch (err) {
+ if (err instanceof TrashUnavailableError) {
+ const isDirectory = (children[parentPath(path)] ?? []).find((entry) => entry.path === path)?.is_directory ?? false;
+ setConfirm({ path, isDirectory, permanent: true });
+ } else fail(err);
+ }
+ };
+
+ const copy = (text: string) => void navigator.clipboard?.writeText(text).catch(fail);
+
+ const rows: Row[] = [];
const walk = (path: string, depth: number) => {
+ if (creating && creating.folder === path) rows.push({ kind: "create", folder: path, entry: creating.kind, depth });
for (const item of sortEntries(children[path] ?? [])) {
+ // Only entries that really sit inside this folder; a bad listing must not loop.
+ if (path && !item.path.startsWith(`${path}/`)) continue;
const matches = !filter || item.name.toLowerCase().includes(filter);
if (matches || item.is_directory) {
- if (matches) rows.push({ item, depth });
+ if (matches) rows.push({ kind: "item", item, depth });
if (item.is_directory && expanded.has(item.path)) walk(item.path, matches ? depth + 1 : depth);
}
}
};
walk("", 0);
+ const onRowKey = (event: ReactKeyboardEvent, item: WorkspaceFileItem) => {
+ if (event.key === "F2") {
+ event.preventDefault();
+ setRenaming(item.path);
+ } else if (event.key === "Delete") {
+ event.preventDefault();
+ setConfirm({ path: item.path, isDirectory: item.is_directory, permanent: false });
+ } else if (event.key === "ArrowRight" && item.is_directory && !expanded.has(item.path)) {
+ event.preventDefault();
+ expand(item.path);
+ } else if (event.key === "ArrowLeft" && item.is_directory && expanded.has(item.path)) {
+ event.preventDefault();
+ toggle(item.path);
+ } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ event.preventDefault();
+ const buttons = [...(list.current?.querySelectorAll<HTMLElement>('[data-testid="explorer-tree-row"]') ?? [])];
+ const index = buttons.indexOf(event.currentTarget as HTMLElement);
+ buttons[index + (event.key === "ArrowDown" ? 1 : -1)]?.focus();
+ }
+ };
+
+ const openMenu = (event: ReactMouseEvent<HTMLElement>, path: string, isDirectory: boolean) => {
+ event.preventDefault();
+ event.stopPropagation();
+ menuAnchor.current = event.currentTarget;
+ setMenu({ path, isDirectory });
+ };
+
if (!children[""] && loading.has("")) {
return (
<p className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">
@@ -460,54 +724,206 @@ function FileTree({ workspaceId, filter, changeMap, changedFolders, onOpen, abso
);
}
+ const menuFolder = menu ? (menu.isDirectory ? menu.path : parentPath(menu.path)) : "";
+ const pick = (action: () => void) => () => {
+ setMenu(null);
+ action();
+ };
+
return (
- <ul data-testid="explorer-tree" role="tree" aria-label={t("ide_side_panel.explorer.view_files")}>
- {error && <li className="px-3 py-2 text-[11px] text-destructive">{error}</li>}
- {rows.map(({ item, depth }) => {
- const change = changeMap.get(item.path);
- const open = expanded.has(item.path);
- const FolderIcon = open ? FolderOpen : Folder;
- const hasChangeInside = item.is_directory && changedFolders.has(item.path);
- return (
- <li key={item.path} role="treeitem" aria-expanded={item.is_directory ? open : undefined}>
- <button
- type="button"
- draggable
- onDragStart={(event) => startFileDrag(event, absolute(item.path))}
- onClick={() => (item.is_directory ? toggle(item.path) : onOpen(item.path))}
- data-testid="explorer-tree-row"
- data-path={item.path}
- title={item.path}
- style={{ paddingLeft: 10 + depth * 14 }}
- className="flex h-7 w-full items-center gap-1.5 pr-3 text-left text-[13px] hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none"
- >
- <ChevronRight
- aria-hidden
+ <>
+ <ul
+ ref={list}
+ data-testid="explorer-tree"
+ role="tree"
+ aria-label={t("ide_side_panel.explorer.view_files")}
+ className="min-h-full"
+ onContextMenu={(event) => openMenu(event, "", true)}
+ >
+ {error && <li className="px-3 py-2 text-[11px] text-destructive">{error}</li>}
+ {rows.map((row) => {
+ if (row.kind === "create") {
+ return (
+ <li key={`create-${row.folder}`} role="none">
+ <NameField
+ initial=""
+ depth={row.depth}
+ icon={row.entry === "directory" ? <Folder className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden /> : <FilePlus className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />}
+ onSubmit={(name) => void create(row.folder, row.entry, name)}
+ onCancel={onCreatingDone}
+ />
+ </li>
+ );
+ }
+ const { item, depth } = row;
+ const change = changeMap.get(item.path);
+ const open = expanded.has(item.path);
+ const FolderIcon = open ? FolderOpen : Folder;
+ const hasChangeInside = item.is_directory && changedFolders.has(item.path);
+ const icon = item.is_directory ? (
+ <FolderIcon aria-hidden className={cn("h-4 w-4 shrink-0", change ? STATUS_TONE[change.status] : "text-muted-foreground")} />
+ ) : (
+ <FileTypeIcon path={item.name} />
+ );
+ if (renaming === item.path) {
+ return (
+ <li key={item.path} role="none">
+ <NameField initial={item.name} depth={depth} icon={icon} onSubmit={(name) => void rename(item.path, name)} onCancel={() => setRenaming(null)} />
+ </li>
+ );
+ }
+ const current = !item.is_directory && item.path === activePath;
+ return (
+ <li key={item.path} role="treeitem" aria-expanded={item.is_directory ? open : undefined} aria-selected={current || undefined}>
+ <button
+ type="button"
+ draggable
+ onDragStart={(event) => startFileDrag(event, absolute(item.path))}
+ onClick={() => {
+ setFocused(item.path);
+ if (item.is_directory) toggle(item.path);
+ else editor.openFile(workspaceId, item.path);
+ }}
+ onDoubleClick={() => !item.is_directory && editor.openFile(workspaceId, item.path, { preview: false })}
+ onKeyDown={(event) => onRowKey(event, item)}
+ onContextMenu={(event) => openMenu(event, item.path, item.is_directory)}
+ data-testid="explorer-tree-row"
+ data-path={item.path}
+ data-active={current || undefined}
+ title={item.path}
+ style={{ paddingLeft: 10 + depth * 14 }}
className={cn(
- "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform duration-150 motion-reduce:transition-none",
- !item.is_directory && "invisible",
- open && "rotate-90",
+ "flex h-7 w-full items-center gap-1.5 pr-3 text-left text-[13px] hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none",
+ current && "bg-secondary",
+ focused === item.path && "ring-1 ring-inset ring-ring/50",
)}
- />
- {item.is_directory ? (
- <FolderIcon
+ >
+ <ChevronRight
aria-hidden
- className={cn("h-4 w-4 shrink-0", change ? STATUS_TONE[change.status] : "text-muted-foreground")}
+ className={cn(
+ "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform duration-150 motion-reduce:transition-none",
+ !item.is_directory && "invisible",
+ open && "rotate-90",
+ )}
/>
- ) : (
- <FileTypeIcon path={item.name} />
- )}
- <span className={cn("min-w-0 flex-1 truncate", change ? STATUS_TONE[change.status] : "text-foreground/90")}>
- {item.name}
- </span>
- {loading.has(item.path) && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground" aria-hidden />}
- {hasChangeInside && !change && <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-success/80" aria-hidden />}
- {change && <StatusLetter status={change.status} />}
- </button>
- </li>
- );
- })}
- </ul>
+ {icon}
+ <span className={cn("min-w-0 flex-1 truncate", change ? STATUS_TONE[change.status] : "text-foreground/90")}>{item.name}</span>
+ {loading.has(item.path) && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground" aria-hidden />}
+ {hasChangeInside && !change && <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-success/80" aria-hidden />}
+ {change && <StatusLetter status={change.status} />}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+
+ <ThreadPopover anchor={menuAnchor} open={menu !== null} onClose={() => setMenu(null)} label={t("ide_side_panel.explorer.menu_label")} width={240}>
+ {menu && (
+ <div role="menu" data-testid="explorer-menu">
+ <ThreadMenuItem icon={<FilePlus className="h-4 w-4" />} label={t("ide_side_panel.explorer.new_file")} onSelect={pick(() => onCreate(menuFolder, "file"))} />
+ <ThreadMenuItem icon={<FolderPlus className="h-4 w-4" />} label={t("ide_side_panel.explorer.new_folder")} onSelect={pick(() => onCreate(menuFolder, "directory"))} />
+ {menu.path && (
+ <>
+ <ThreadMenuSeparator />
+ {!menu.isDirectory && (
+ <ThreadMenuItem icon={<SquarePen className="h-4 w-4" />} label={t("ide_side_panel.explorer.open_editor")} onSelect={pick(() => editor.openFile(workspaceId, menu.path, { preview: false }))} />
+ )}
+ {stagedPane && (
+ <ThreadMenuItem
+ icon={<SquareArrowOutUpRight className="h-4 w-4" />}
+ label={fill(t("ide_side_panel.explorer.reference_in"), { pane: stagedPane })}
+ onSelect={pick(() => void attachToTerminal(stagedPane, { paths: [absolute(menu.path)] }).catch(fail))}
+ />
+ )}
+ <ThreadMenuItem icon={<ExternalLink className="h-4 w-4" />} label={t("ide_side_panel.explorer.open_externally")} onSelect={pick(() => void openTerminalTarget(workspaceId, menu.path).catch(fail))} />
+ <ThreadMenuSeparator />
+ <ThreadMenuItem icon={<Copy className="h-4 w-4" />} label={t("ide_side_panel.explorer.copy_path")} onSelect={pick(() => copy(absolute(menu.path)))} />
+ <ThreadMenuItem icon={<span aria-hidden />} label={t("ide_side_panel.explorer.copy_relative_path")} onSelect={pick(() => copy(menu.path))} />
+ <ThreadMenuSeparator />
+ <ThreadMenuItem icon={<Pencil className="h-4 w-4" />} label={t("ide_side_panel.explorer.rename")} hint="F2" onSelect={pick(() => setRenaming(menu.path))} />
+ <ThreadMenuItem
+ icon={<Trash2 className="h-4 w-4" />}
+ label={t("ide_side_panel.explorer.delete")}
+ hint="Del"
+ danger
+ onSelect={pick(() => setConfirm({ path: menu.path, isDirectory: menu.isDirectory, permanent: false }))}
+ />
+ </>
+ )}
+ </div>
+ )}
+ </ThreadPopover>
+
+ {confirm && (
+ <DeleteDialog
+ name={baseName(confirm.path)}
+ isDirectory={confirm.isDirectory}
+ permanent={confirm.permanent}
+ onCancel={() => setConfirm(null)}
+ onConfirm={() => void remove(confirm.path, confirm.permanent)}
+ />
+ )}
+ </>
+ );
+}
+
+function DeleteDialog({
+ name,
+ isDirectory,
+ permanent,
+ onConfirm,
+ onCancel,
+}: {
+ name: string;
+ isDirectory: boolean;
+ permanent: boolean;
+ onConfirm: () => void;
+ onCancel: () => void;
+}) {
+ const t = useT();
+ const confirmButton = useRef<HTMLButtonElement>(null);
+ useEffect(() => confirmButton.current?.focus(), []);
+ const title = permanent ? "ide_side_panel.explorer.delete_permanent_title" : isDirectory ? "ide_side_panel.explorer.delete_folder_title" : "ide_side_panel.explorer.delete_file_title";
+ return (
+ <div
+ role="presentation"
+ className="fixed inset-0 z-[86] flex items-center justify-center bg-background/60 p-4"
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ onCancel();
+ }
+ }}
+ >
+ <section
+ role="alertdialog"
+ aria-modal="true"
+ aria-labelledby="explorer-delete-title"
+ data-testid="explorer-delete-dialog"
+ className="w-full max-w-sm rounded-xl border border-border bg-popover p-4 text-popover-foreground shadow-float"
+ >
+ <h2 id="explorer-delete-title" className="text-sm font-semibold text-foreground-strong">
+ {fill(t(title), { file: name })}
+ </h2>
+ <p className="mt-1.5 text-xs text-muted-foreground">
+ {t(permanent ? "ide_side_panel.explorer.delete_permanent_body" : "ide_side_panel.explorer.delete_body")}
+ </p>
+ <div className="mt-4 flex justify-end gap-2">
+ <button type="button" onClick={onCancel} className="h-8 rounded-md px-3 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ {t("ide_side_panel.explorer.cancel")}
+ </button>
+ <button
+ ref={confirmButton}
+ type="button"
+ onClick={onConfirm}
+ data-testid="explorer-delete-confirm"
+ className="h-8 rounded-md bg-destructive px-3 text-xs font-medium text-destructive-foreground hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {t(permanent ? "ide_side_panel.explorer.delete_permanent" : "ide_side_panel.explorer.delete")}
+ </button>
+ </div>
+ </section>
+ </div>
);
}
@@ -525,145 +941,3 @@ function sortEntries(entries: WorkspaceFileItem[]): WorkspaceFileItem[] {
: 1,
);
}
-
-const IMAGE_EXTENSIONS = /\.(png|jpe?g|gif|webp|svg|bmp|ico|avif)$/i;
-
-interface ViewerProps {
- workspaceId: string;
- path: string;
- change: Map<string, ChangedFile>;
- onBack: () => void;
- onReference?: (relative: string) => void;
- referenceLabel: string;
- onOpenExternally: (path: string) => void;
- absolute: (relative: string) => string;
-}
-
-/** One file: its diff when it changed, else its contents. */
-function FileViewer({ workspaceId, path, change, onBack, onReference, referenceLabel, onOpenExternally, absolute }: ViewerProps) {
- const t = useT();
- const [diff, setDiff] = useState<FileDiff | null>(null);
- const [preview, setPreview] = useState<WorkspaceFilePreviewResponse | null>(null);
- const [error, setError] = useState("");
-
- useEffect(() => {
- let alive = true;
- setDiff(null);
- setPreview(null);
- setError("");
- void (async () => {
- try {
- const answer = await fetchFileDiff(workspaceId, path);
- if (!alive) return;
- setDiff(answer);
- if (answer.hunks.length === 0 && !answer.binary && answer.status !== "deleted") {
- const body = await fetchWorkspaceFilePreview(workspaceId, answer.path);
- if (alive) setPreview(body);
- }
- } catch (err) {
- if (alive) setError((err as Error).message);
- }
- })();
- return () => {
- alive = false;
- };
- }, [workspaceId, path]);
-
- const relative = diff?.path ?? path;
- const known = change.get(relative);
- const status = diff && diff.status !== "unchanged" ? diff.status : known?.status;
-
- return (
- <section data-testid="explorer-viewer" data-path={relative} className="flex h-full min-h-0 flex-col">
- <div className="shrink-0 border-b border-border/60 px-2 py-2">
- <div className="flex items-center gap-1.5">
- <button
- type="button"
- onClick={onBack}
- aria-label={t("ide_side_panel.explorer.back")}
- title={t("ide_side_panel.explorer.back")}
- className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- <ArrowLeft className="h-4 w-4" aria-hidden />
- </button>
- <span
- draggable
- onDragStart={(event) => startFileDrag(event, absolute(relative))}
- title={t("ide_side_panel.explorer.drag_hint")}
- className="flex min-w-0 flex-1 cursor-grab items-center gap-2"
- >
- <FileTypeIcon path={relative} />
- <span className="flex min-w-0 flex-col leading-tight">
- <span className={cn("truncate text-[13px] font-semibold", status ? STATUS_TONE[status as ChangeStatus] : "text-foreground")}>
- {baseName(relative)}
- </span>
- {parentPath(relative) && <span className="truncate text-[10.5px] text-muted-foreground">{parentPath(relative)}</span>}
- </span>
- </span>
- {diff && (diff.added > 0 || diff.removed > 0) && <ChangeCounts file={diff} />}
- </div>
- <div className="mt-2 flex flex-wrap gap-1.5 pl-8">
- {onReference && (
- <button
- type="button"
- data-testid="explorer-reference"
- onClick={() => onReference(relative)}
- className="inline-flex h-7 items-center gap-1.5 rounded-md border border-border/70 px-2 text-xs text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- <SquareArrowOutUpRight className="h-3.5 w-3.5" aria-hidden />
- {referenceLabel}
- </button>
- )}
- <button
- type="button"
- onClick={() => onOpenExternally(relative)}
- className="inline-flex h-7 items-center gap-1.5 rounded-md border border-border/70 px-2 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- <ExternalLink className="h-3.5 w-3.5" aria-hidden />
- {t("ide_side_panel.explorer.open_externally")}
- </button>
- </div>
- </div>
- <div className="scrollbar-jarvis min-h-0 flex-1 overflow-auto">
- {error ? (
- <p className="px-4 py-3 text-xs text-destructive">{error}</p>
- ) : !diff ? (
- <p className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">
- <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
- {t("ide_side_panel.explorer.loading")}
- </p>
- ) : diff.binary ? (
- IMAGE_EXTENSIONS.test(relative) && diff.status !== "deleted" ? (
- <img src={workspaceFileUrl(workspaceId, relative)} alt={baseName(relative)} className="m-3 max-w-[calc(100%-24px)] rounded-md border border-border/60" />
- ) : (
- <p className="px-4 py-3 text-xs text-muted-foreground">{t("ide_side_panel.explorer.binary")}</p>
- )
- ) : diff.hunks.length > 0 ? (
- <>
- <DiffView hunks={diff.hunks} />
- {diff.truncated && <p className="px-4 py-2 text-[11px] text-muted-foreground">{t("ide_side_panel.explorer.truncated")}</p>}
- </>
- ) : IMAGE_EXTENSIONS.test(relative) ? (
- <img src={workspaceFileUrl(workspaceId, relative)} alt={baseName(relative)} className="m-3 max-w-[calc(100%-24px)] rounded-md border border-border/60" />
- ) : preview?.text != null ? (
- <div className="min-w-max py-1 font-mono text-[12px] leading-[1.55]">
- <p className="px-3 pb-1 font-sans text-[11px] text-muted-foreground">{t("ide_side_panel.explorer.unchanged")}</p>
- {preview.text.split("\n").map((line, index) => (
- <div key={index} className="flex">
- <span className="w-10 shrink-0 select-none pr-3 text-right tabular-nums text-muted-foreground/70">{index + 1}</span>
- <span className="whitespace-pre pr-4 text-foreground/85">{line || " "}</span>
- </div>
- ))}
- </div>
- ) : preview ? (
- <p className="px-4 py-3 text-xs text-muted-foreground">{t("ide_side_panel.explorer.binary")}</p>
- ) : (
- <p className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">
- <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
- {t("ide_side_panel.explorer.loading")}
- </p>
- )}
- </div>
- </section>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/i18n/code-editor-i18n-parity.test.ts b/jarvis/ui/web/frontend/src/i18n/code-editor-i18n-parity.test.ts
new file mode 100644
index 0000000000..0f89cb4b4b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/i18n/code-editor-i18n-parity.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import en from "./locales/en.json";
+import de from "./locales/de.json";
+import es from "./locales/es.json";
+
+type Locale = Record<string, unknown>;
+
+function flatten(value: Locale, prefix = ""): string[] {
+ return Object.entries(value).flatMap(([key, nested]) => {
+ const path = prefix ? `${prefix}.${key}` : key;
+ return nested && typeof nested === "object"
+ ? flatten(nested as Locale, path)
+ : [path];
+ });
+}
+
+const keys = (locale: Locale) =>
+ flatten((locale.code_editor ?? {}) as Locale).sort();
+
+describe("code editor i18n parity", () => {
+ it("en defines the code editor section", () => {
+ expect(keys(en as Locale).length).toBeGreaterThan(0);
+ });
+
+ for (const [language, locale] of Object.entries({ de, es })) {
+ it(`${language} has the same code editor keys as en`, () => {
+ expect(keys(locale as Locale)).toEqual(keys(en as Locale));
+ });
+ }
+});
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 415af1ceb4..809bcba657 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -6116,6 +6116,61 @@
"control_turn": "Agentenarbeit",
"verifying": "Ausführung abgeschlossen; Ergebnis wird geprüft."
},
+ "code_editor": {
+ "loading": "Wird geöffnet…",
+ "starting": "Editor startet…",
+ "binary": "Diese Datei ist kein Text und lässt sich hier nicht bearbeiten.",
+ "too_large": "Diese Datei ist größer als 5 MB und zu groß zum Bearbeiten.",
+ "load_failed": "Die Datei konnte nicht geöffnet werden ({error}).",
+ "open_externally": "Auf diesem Computer öffnen",
+ "tabs": "Geöffnete Dateien",
+ "close_tab": "{file} schließen",
+ "close_tab_hint": "Schließen (Strg+W)",
+ "show_terminals": "Terminals",
+ "show_terminals_hint": "Terminals zeigen; deine Dateien bleiben offen",
+ "breadcrumbs": "Dateipfad",
+ "diff_badge": "Änderungen seit dem letzten Commit",
+ "open_file": "Datei öffnen",
+ "open_changes": "Änderungen zeigen",
+ "reference_in": "In {pane} referenzieren",
+ "conflict": "Ein Agent hat diese Datei auf der Festplatte geändert, während du ungespeicherte Änderungen hattest.",
+ "conflict_load_disk": "Seine Version laden",
+ "conflict_keep_mine": "Meine behalten",
+ "deleted": "Diese Datei wurde auf der Festplatte gelöscht. Speichern legt sie neu an.",
+ "tab_menu": "Tab-Aktionen",
+ "menu": {
+ "close": "Schließen",
+ "close_others": "Andere schließen",
+ "close_saved": "Gespeicherte schließen",
+ "close_all": "Alle schließen",
+ "copy_path": "Pfad kopieren",
+ "copy_relative_path": "Relativen Pfad kopieren",
+ "reveal": "Im Ordner zeigen"
+ },
+ "status": {
+ "saving": "Speichert…",
+ "unsaved": "Ungespeicherte Änderungen",
+ "saved": "Gespeichert",
+ "position": "Z. {line}, Sp. {column}",
+ "selected": "({count} ausgewählt)",
+ "spaces": "Leerzeichen: {size}",
+ "tabs": "Tabgröße: {size}",
+ "utf8_bom": "UTF-8 mit BOM"
+ },
+ "unsaved": {
+ "title_one": "Änderungen an {file} speichern?",
+ "title_many": "Änderungen an {count} Dateien speichern?",
+ "body": "Ohne Speichern gehen deine Änderungen verloren.",
+ "save": "Speichern",
+ "discard": "Nicht speichern",
+ "cancel": "Abbrechen"
+ },
+ "quick_open": {
+ "title": "Gehe zu Datei",
+ "placeholder": "Dateinamen tippen; :42 springt zu Zeile 42",
+ "no_match": "Keine Datei passt."
+ }
+ },
"ide_side_panel": {
"aria": "Seitenleiste",
"tabs_aria": "Tabs der Seitenleiste",
@@ -6151,9 +6206,24 @@
"truncated": "Die Liste wurde gekürzt; öffne den Ordner für den Rest.",
"reference_in": "In {pane} referenzieren",
"open_externally": "Auf diesem Computer öffnen",
- "back": "Zurück",
- "binary": "Diese Datei lässt sich nicht als Text anzeigen.",
- "unchanged": "Seit dem letzten Commit unverändert."
+ "new_file": "Neue Datei",
+ "new_folder": "Neuer Ordner",
+ "collapse_all": "Alle Ordner einklappen",
+ "quick_open_hint": "Gehe zu Datei (Strg+P)",
+ "show_editor": "Editor zeigen ({count} offen)",
+ "menu_label": "Dateiaktionen",
+ "open_editor": "Im Editor öffnen",
+ "copy_path": "Pfad kopieren",
+ "copy_relative_path": "Relativen Pfad kopieren",
+ "rename": "Umbenennen",
+ "delete": "Löschen",
+ "delete_file_title": "{file} löschen?",
+ "delete_folder_title": "Den Ordner {file} mit allem Inhalt löschen?",
+ "delete_permanent_title": "{file} endgültig löschen?",
+ "delete_body": "Es landet im Papierkorb und lässt sich von dort wiederherstellen.",
+ "delete_permanent_body": "Dieser Computer hat keinen Papierkorb. Endgültiges Löschen lässt sich nicht rückgängig machen.",
+ "delete_permanent": "Endgültig löschen",
+ "cancel": "Abbrechen"
},
"tabs": {
"git": "Git",
@@ -6813,8 +6883,8 @@
"ember": {
"description": "Ein Babydrache: bläst beim Nachdenken Rauchringe, speit bei Erfolg Feuer."
},
- "cocoa": {
- "description": "Ein schokobrauner Labrador-Welpe: legt beim Zuhören den Kopf schief, buddelt beim Arbeiten, flitzt bei Erfolg im Kreis."
+ "cocoa": {
+ "description": "Ein schokobrauner Labrador-Welpe: legt beim Zuhören den Kopf schief, buddelt beim Arbeiten, flitzt bei Erfolg im Kreis."
}
},
"create_dialog": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index a2de358f99..8c064cbda7 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -6149,6 +6149,61 @@
"control_turn": "Agent work",
"verifying": "Execution finished; verifying the result."
},
+ "code_editor": {
+ "loading": "Opening…",
+ "starting": "Starting the editor…",
+ "binary": "This file is not text, so it cannot be edited here.",
+ "too_large": "This file is larger than 5 MB, too large to edit here.",
+ "load_failed": "The file could not be opened ({error}).",
+ "open_externally": "Open on this computer",
+ "tabs": "Open files",
+ "close_tab": "Close {file}",
+ "close_tab_hint": "Close (Ctrl+W)",
+ "show_terminals": "Terminals",
+ "show_terminals_hint": "Show the terminals; your files stay open",
+ "breadcrumbs": "File path",
+ "diff_badge": "Changes since the last commit",
+ "open_file": "Open file",
+ "open_changes": "Show changes",
+ "reference_in": "Reference in {pane}",
+ "conflict": "An agent changed this file on disk while you had unsaved edits.",
+ "conflict_load_disk": "Load their version",
+ "conflict_keep_mine": "Keep mine",
+ "deleted": "This file was deleted on disk. Saving creates it again.",
+ "tab_menu": "Tab actions",
+ "menu": {
+ "close": "Close",
+ "close_others": "Close others",
+ "close_saved": "Close saved",
+ "close_all": "Close all",
+ "copy_path": "Copy path",
+ "copy_relative_path": "Copy relative path",
+ "reveal": "Reveal in Folder"
+ },
+ "status": {
+ "saving": "Saving…",
+ "unsaved": "Unsaved changes",
+ "saved": "Saved",
+ "position": "Ln {line}, Col {column}",
+ "selected": "({count} selected)",
+ "spaces": "Spaces: {size}",
+ "tabs": "Tab size: {size}",
+ "utf8_bom": "UTF-8 with BOM"
+ },
+ "unsaved": {
+ "title_one": "Save changes to {file}?",
+ "title_many": "Save changes to {count} files?",
+ "body": "Your changes are lost if you do not save them.",
+ "save": "Save",
+ "discard": "Do not save",
+ "cancel": "Cancel"
+ },
+ "quick_open": {
+ "title": "Go to file",
+ "placeholder": "Type a file name; add :42 to jump to line 42",
+ "no_match": "No file matches."
+ }
+ },
"ide_side_panel": {
"aria": "Side panel",
"tabs_aria": "Side panel tabs",
@@ -6184,9 +6239,24 @@
"truncated": "The list was shortened; open the folder for the rest.",
"reference_in": "Reference in {pane}",
"open_externally": "Open on this computer",
- "back": "Back",
- "binary": "This file cannot be shown as text.",
- "unchanged": "Unchanged since the last commit."
+ "new_file": "New file",
+ "new_folder": "New folder",
+ "collapse_all": "Collapse all folders",
+ "quick_open_hint": "Go to file (Ctrl+P)",
+ "show_editor": "Show editor ({count} open)",
+ "menu_label": "File actions",
+ "open_editor": "Open in editor",
+ "copy_path": "Copy path",
+ "copy_relative_path": "Copy relative path",
+ "rename": "Rename",
+ "delete": "Delete",
+ "delete_file_title": "Delete {file}?",
+ "delete_folder_title": "Delete the folder {file} and everything in it?",
+ "delete_permanent_title": "Delete {file} permanently?",
+ "delete_body": "It goes to the trash, so you can still restore it.",
+ "delete_permanent_body": "This computer has no trash to move it to. A permanent delete cannot be undone.",
+ "delete_permanent": "Delete permanently",
+ "cancel": "Cancel"
},
"tabs": {
"git": "Git",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 9c170a8fbf..74cfbbcb3c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -6116,6 +6116,61 @@
"control_turn": "Trabajo del agente",
"verifying": "Ejecución finalizada; verificando el resultado."
},
+ "code_editor": {
+ "loading": "Abriendo…",
+ "starting": "Iniciando el editor…",
+ "binary": "Este archivo no es texto, así que no se puede editar aquí.",
+ "too_large": "Este archivo supera los 5 MB y es demasiado grande para editarlo aquí.",
+ "load_failed": "No se pudo abrir el archivo ({error}).",
+ "open_externally": "Abrir en este equipo",
+ "tabs": "Archivos abiertos",
+ "close_tab": "Cerrar {file}",
+ "close_tab_hint": "Cerrar (Ctrl+W)",
+ "show_terminals": "Terminales",
+ "show_terminals_hint": "Mostrar las terminales; tus archivos siguen abiertos",
+ "breadcrumbs": "Ruta del archivo",
+ "diff_badge": "Cambios desde el último commit",
+ "open_file": "Abrir archivo",
+ "open_changes": "Ver cambios",
+ "reference_in": "Referenciar en {pane}",
+ "conflict": "Un agente cambió este archivo en el disco mientras tenías cambios sin guardar.",
+ "conflict_load_disk": "Cargar su versión",
+ "conflict_keep_mine": "Mantener la mía",
+ "deleted": "Este archivo se eliminó del disco. Al guardar se vuelve a crear.",
+ "tab_menu": "Acciones de pestaña",
+ "menu": {
+ "close": "Cerrar",
+ "close_others": "Cerrar las demás",
+ "close_saved": "Cerrar las guardadas",
+ "close_all": "Cerrar todas",
+ "copy_path": "Copiar ruta",
+ "copy_relative_path": "Copiar ruta relativa",
+ "reveal": "Mostrar en la carpeta"
+ },
+ "status": {
+ "saving": "Guardando…",
+ "unsaved": "Cambios sin guardar",
+ "saved": "Guardado",
+ "position": "Lín. {line}, col. {column}",
+ "selected": "({count} seleccionados)",
+ "spaces": "Espacios: {size}",
+ "tabs": "Tamaño de tabulación: {size}",
+ "utf8_bom": "UTF-8 con BOM"
+ },
+ "unsaved": {
+ "title_one": "¿Guardar los cambios en {file}?",
+ "title_many": "¿Guardar los cambios en {count} archivos?",
+ "body": "Si no los guardas, tus cambios se pierden.",
+ "save": "Guardar",
+ "discard": "No guardar",
+ "cancel": "Cancelar"
+ },
+ "quick_open": {
+ "title": "Ir a archivo",
+ "placeholder": "Escribe un nombre; añade :42 para ir a la línea 42",
+ "no_match": "Ningún archivo coincide."
+ }
+ },
"ide_side_panel": {
"aria": "Panel lateral",
"tabs_aria": "Pestañas del panel lateral",
@@ -6151,9 +6206,24 @@
"truncated": "La lista se acortó; abre la carpeta para ver el resto.",
"reference_in": "Referenciar en {pane}",
"open_externally": "Abrir en este equipo",
- "back": "Volver",
- "binary": "Este archivo no se puede mostrar como texto.",
- "unchanged": "Sin cambios desde el último commit."
+ "new_file": "Nuevo archivo",
+ "new_folder": "Nueva carpeta",
+ "collapse_all": "Contraer todas las carpetas",
+ "quick_open_hint": "Ir a archivo (Ctrl+P)",
+ "show_editor": "Mostrar editor ({count} abiertos)",
+ "menu_label": "Acciones de archivo",
+ "open_editor": "Abrir en el editor",
+ "copy_path": "Copiar ruta",
+ "copy_relative_path": "Copiar ruta relativa",
+ "rename": "Cambiar nombre",
+ "delete": "Eliminar",
+ "delete_file_title": "¿Eliminar {file}?",
+ "delete_folder_title": "¿Eliminar la carpeta {file} y todo su contenido?",
+ "delete_permanent_title": "¿Eliminar {file} definitivamente?",
+ "delete_body": "Irá a la papelera, así que aún podrás restaurarlo.",
+ "delete_permanent_body": "Este equipo no tiene papelera. Una eliminación definitiva no se puede deshacer.",
+ "delete_permanent": "Eliminar definitivamente",
+ "cancel": "Cancelar"
},
"tabs": {
"git": "Git",
diff --git a/jarvis/ui/web/frontend/src/store/codeEditor.test.ts b/jarvis/ui/web/frontend/src/store/codeEditor.test.ts
new file mode 100644
index 0000000000..4ecc71d1e6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/store/codeEditor.test.ts
@@ -0,0 +1,81 @@
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { reloadHeld } from "@/lib/reloadHold";
+import { fileKeyOf, tabKeyOf, tabsOf, useCodeEditorStore } from "./codeEditor";
+
+const store = () => useCodeEditorStore.getState();
+const paths = () => store().tabs.map((tab) => `${tab.path}${tab.preview ? "*" : ""}`);
+
+beforeEach(() => {
+ useCodeEditorStore.setState({ tabs: [], active: {}, files: {}, visible: false, quickOpen: false, cursor: null, reveal: null, closed: [] });
+});
+
+describe("code editor tabs", () => {
+ it("lets a single-click preview tab be replaced by the next one", () => {
+ store().openFile("w1", "a.ts");
+ store().openFile("w1", "b.ts");
+ expect(paths()).toEqual(["b.ts*"]);
+ expect(store().files[fileKeyOf("w1", "a.ts")]).toBeUndefined();
+ expect(store().visible).toBe(true);
+ });
+
+ it("keeps a pinned tab and opens the next one beside it", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w1", "b.ts");
+ store().openFile("w1", "c.ts");
+ expect(paths()).toEqual(["a.ts", "c.ts*"]);
+ });
+
+ it("pins a preview tab once its buffer has unsaved edits", () => {
+ store().openFile("w1", "a.ts");
+ store().patchFile(fileKeyOf("w1", "a.ts"), { dirty: true });
+ store().openFile("w1", "b.ts");
+ expect(paths()).toEqual(["a.ts", "b.ts*"]);
+ expect(reloadHeld()).toBe(true);
+ store().patchFile(fileKeyOf("w1", "a.ts"), { dirty: false });
+ expect(reloadHeld()).toBe(false);
+ });
+
+ it("shows the right neighbour after closing the active tab, and can reopen it", () => {
+ for (const path of ["a.ts", "b.ts", "c.ts"]) store().openFile("w1", path, { preview: false });
+ store().activate(tabKeyOf("edit", fileKeyOf("w1", "a.ts")));
+ store().closeTab(tabKeyOf("edit", fileKeyOf("w1", "a.ts")));
+ expect(store().active.w1).toBe(tabKeyOf("edit", fileKeyOf("w1", "b.ts")));
+ store().closeTabs([tabKeyOf("edit", fileKeyOf("w1", "b.ts")), tabKeyOf("edit", fileKeyOf("w1", "c.ts"))]);
+ expect(store().active.w1).toBeNull();
+ store().reopenClosed("w1");
+ expect(paths()).toEqual(["c.ts"]);
+ });
+
+ it("keeps an edit tab and a diff tab of the same file apart", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w1", "a.ts", { mode: "diff", preview: false });
+ expect(store().tabs.map((tab) => tab.mode)).toEqual(["edit", "diff"]);
+ expect(Object.keys(store().files)).toEqual([fileKeyOf("w1", "a.ts")]);
+ });
+
+ it("cycles through one workspace's tabs only", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w2", "x.ts", { preview: false });
+ store().openFile("w1", "b.ts", { preview: false });
+ store().cycle("w1", 1);
+ expect(store().active.w1).toBe(tabKeyOf("edit", fileKeyOf("w1", "a.ts")));
+ expect(tabsOf(store(), "w2").map((tab) => tab.path)).toEqual(["x.ts"]);
+ });
+
+ it("moves open files along with a folder rename and marks deleted ones", () => {
+ store().openFile("w1", "src/a.ts", { preview: false });
+ store().openFile("w1", "srcx/b.ts", { preview: false });
+ store().renamePath("w1", "src", "lib");
+ expect(paths()).toEqual(["lib/a.ts", "srcx/b.ts"]);
+ expect(store().active.w1).toBe(tabKeyOf("edit", fileKeyOf("w1", "srcx/b.ts")));
+ store().markDeleted("w1", "lib");
+ expect(store().files[fileKeyOf("w1", "lib/a.ts")]).toMatchObject({ deleted: true, version: null });
+ expect(store().files[fileKeyOf("w1", "srcx/b.ts")].deleted).toBe(false);
+ });
+
+ it("asks the editor to reveal a line", () => {
+ store().openFile("w1", "a.ts", { line: 42, column: 3 });
+ expect(store().reveal).toMatchObject({ fileKey: fileKeyOf("w1", "a.ts"), line: 42, column: 3 });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/store/codeEditor.ts b/jarvis/ui/web/frontend/src/store/codeEditor.ts
new file mode 100644
index 0000000000..52162b2674
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/store/codeEditor.ts
@@ -0,0 +1,310 @@
+import { create } from "zustand";
+
+import { setReloadHold } from "@/lib/reloadHold";
+import type { LineEnding, TextEncoding } from "@/components/agentic/editor/editorApi";
+
+/**
+ * The Agentic IDE's code editor: which files are open as tabs, and what is
+ * known about each file on disk.
+ *
+ * The text itself lives in the editor engine's models (see
+ * `components/agentic/editor/editorModels.ts`); this store holds only what the
+ * React chrome draws — tabs, dirty dots, conflict bars, the status bar.
+ *
+ * Tabs follow the familiar desktop-editor rules: a single click opens a
+ * *preview* tab (italic) that the next single click replaces; a double click,
+ * an edit or a save keeps it. Tabs belong to one workspace, so switching
+ * workspaces shows that workspace's own tabs.
+ */
+export type EditorMode = "edit" | "diff";
+
+export interface EditorTab {
+ key: string;
+ fileKey: string;
+ workspaceId: string;
+ /** POSIX path relative to the workspace root. */
+ path: string;
+ mode: EditorMode;
+ preview: boolean;
+}
+
+export type FileStatus = "loading" | "ready" | "binary" | "too_large" | "image" | "error";
+
+export interface EditorFile {
+ workspaceId: string;
+ path: string;
+ status: FileStatus;
+ error: string;
+ /** Version on disk the buffer is based on; null for a file not on disk. */
+ version: string | null;
+ encoding: TextEncoding;
+ eol: LineEnding;
+ dirty: boolean;
+ /** Deleted on disk while open; the buffer is kept and a save recreates it. */
+ deleted: boolean;
+ /** The file changed on disk while the buffer had unsaved edits. */
+ conflict: { diskVersion: string | null } | null;
+ saving: boolean;
+}
+
+export interface CursorInfo {
+ line: number;
+ column: number;
+ selected: number;
+ language: string;
+ insertSpaces: boolean;
+ tabSize: number;
+}
+
+export interface RevealRequest {
+ fileKey: string;
+ line: number;
+ column: number;
+ nonce: number;
+}
+
+interface ClosedTab {
+ workspaceId: string;
+ path: string;
+ mode: EditorMode;
+}
+
+export interface OpenOptions {
+ mode?: EditorMode;
+ /** Single-click opens replace each other; false keeps the tab. */
+ preview?: boolean;
+ line?: number;
+ column?: number;
+}
+
+interface CodeEditorState {
+ tabs: EditorTab[];
+ /** The active tab per workspace. */
+ active: Record<string, string | null>;
+ files: Record<string, EditorFile>;
+ /** Whether the editor covers the terminals (tabs stay open when hidden). */
+ visible: boolean;
+ quickOpen: boolean;
+ cursor: CursorInfo | null;
+ reveal: RevealRequest | null;
+ closed: ClosedTab[];
+ openFile: (workspaceId: string, path: string, options?: OpenOptions) => void;
+ closeTab: (key: string) => void;
+ closeTabs: (keys: string[]) => void;
+ activate: (key: string) => void;
+ pinTab: (key: string) => void;
+ cycle: (workspaceId: string, step: 1 | -1) => void;
+ reopenClosed: (workspaceId: string) => void;
+ patchFile: (fileKey: string, patch: Partial<EditorFile>) => void;
+ setVisible: (visible: boolean) => void;
+ setQuickOpen: (open: boolean) => void;
+ setCursor: (cursor: CursorInfo | null) => void;
+ /** After a rename in the explorer: every open file under `from` moves to `to`. */
+ renamePath: (workspaceId: string, from: string, to: string) => void;
+ /** After a delete in the explorer: open files under `path` are marked deleted. */
+ markDeleted: (workspaceId: string, path: string) => void;
+}
+
+export const fileKeyOf = (workspaceId: string, path: string) => `${workspaceId}\u0000${path}`;
+export const tabKeyOf = (mode: EditorMode, fileKey: string) => `${mode}:${fileKey}`;
+
+/** True when `path` is `root` itself or lies inside the folder `root`. */
+export const isUnder = (path: string, root: string) => path === root || path.startsWith(`${root}/`);
+
+const MAX_CLOSED = 20;
+
+const newFile = (workspaceId: string, path: string): EditorFile => ({
+ workspaceId,
+ path,
+ status: "loading",
+ error: "",
+ version: null,
+ encoding: "utf-8",
+ eol: "\n",
+ dirty: false,
+ deleted: false,
+ conflict: null,
+ saving: false,
+});
+
+/** Drop file records no tab refers to any more. */
+function prune(files: Record<string, EditorFile>, tabs: EditorTab[]): Record<string, EditorFile> {
+ const used = new Set(tabs.map((tab) => tab.fileKey));
+ const next: Record<string, EditorFile> = {};
+ for (const [key, file] of Object.entries(files)) if (used.has(key)) next[key] = file;
+ return next;
+}
+
+/** The tab to show once `key` closes: the nearest survivor to its right, else to its left. */
+function successor(own: EditorTab[], key: string, closing: Set<string>): string | null {
+ const index = own.findIndex((tab) => tab.key === key);
+ const right = own.slice(index + 1).find((tab) => !closing.has(tab.key));
+ const left = own
+ .slice(0, Math.max(index, 0))
+ .reverse()
+ .find((tab) => !closing.has(tab.key));
+ return (right ?? left)?.key ?? null;
+}
+
+let revealNonce = 0;
+
+export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({
+ tabs: [],
+ active: {},
+ files: {},
+ visible: false,
+ quickOpen: false,
+ cursor: null,
+ reveal: null,
+ closed: [],
+
+ openFile: (workspaceId, path, options = {}) => {
+ const mode = options.mode ?? "edit";
+ const preview = options.preview ?? true;
+ const fileKey = fileKeyOf(workspaceId, path);
+ const key = tabKeyOf(mode, fileKey);
+ set((state) => {
+ let tabs = state.tabs;
+ const existing = tabs.find((tab) => tab.key === key);
+ if (existing) {
+ if (!preview && existing.preview) tabs = tabs.map((tab) => (tab.key === key ? { ...tab, preview: false } : tab));
+ } else {
+ const tab: EditorTab = { key, fileKey, workspaceId, path, mode, preview };
+ const replaced = tabs.find(
+ (entry) => entry.workspaceId === workspaceId && entry.preview && !state.files[entry.fileKey]?.dirty,
+ );
+ if (replaced) {
+ tabs = tabs.map((entry) => (entry.key === replaced.key ? tab : entry));
+ } else {
+ const activeKey = state.active[workspaceId];
+ const at = activeKey ? tabs.findIndex((entry) => entry.key === activeKey) : -1;
+ tabs = at < 0 ? [...tabs, tab] : [...tabs.slice(0, at + 1), tab, ...tabs.slice(at + 1)];
+ }
+ }
+ const files = state.files[fileKey] ? state.files : { ...state.files, [fileKey]: newFile(workspaceId, path) };
+ const reveal =
+ options.line != null ? { fileKey, line: options.line, column: options.column ?? 1, nonce: ++revealNonce } : state.reveal;
+ return {
+ tabs,
+ files: prune(files, tabs),
+ active: { ...state.active, [workspaceId]: key },
+ visible: true,
+ reveal,
+ };
+ });
+ },
+
+ closeTab: (key) => get().closeTabs([key]),
+
+ closeTabs: (keys) =>
+ set((state) => {
+ const closing = new Set(keys);
+ const gone = state.tabs.filter((tab) => closing.has(tab.key));
+ if (gone.length === 0) return {};
+ const tabs = state.tabs.filter((tab) => !closing.has(tab.key));
+ const active = { ...state.active };
+ for (const workspaceId of new Set(gone.map((tab) => tab.workspaceId))) {
+ const current = active[workspaceId];
+ if (!current || !closing.has(current)) continue;
+ active[workspaceId] = successor(state.tabs.filter((tab) => tab.workspaceId === workspaceId), current, closing);
+ }
+ const closed = [...state.closed, ...gone.map(({ workspaceId, path, mode }) => ({ workspaceId, path, mode }))];
+ return { tabs, active, files: prune(state.files, tabs), closed: closed.slice(-MAX_CLOSED) };
+ }),
+
+ activate: (key) =>
+ set((state) => {
+ const tab = state.tabs.find((entry) => entry.key === key);
+ return tab ? { active: { ...state.active, [tab.workspaceId]: key }, visible: true } : {};
+ }),
+
+ pinTab: (key) =>
+ set((state) => ({ tabs: state.tabs.map((tab) => (tab.key === key && tab.preview ? { ...tab, preview: false } : tab)) })),
+
+ cycle: (workspaceId, step) =>
+ set((state) => {
+ const own = state.tabs.filter((tab) => tab.workspaceId === workspaceId);
+ if (own.length === 0) return {};
+ const index = own.findIndex((tab) => tab.key === state.active[workspaceId]);
+ const next = own[(index + step + own.length) % own.length];
+ return { active: { ...state.active, [workspaceId]: next.key } };
+ }),
+
+ reopenClosed: (workspaceId) => {
+ const closed = [...get().closed];
+ for (let index = closed.length - 1; index >= 0; index -= 1) {
+ const entry = closed[index];
+ if (entry.workspaceId !== workspaceId) continue;
+ closed.splice(index, 1);
+ set({ closed });
+ get().openFile(entry.workspaceId, entry.path, { mode: entry.mode, preview: false });
+ return;
+ }
+ },
+
+ patchFile: (fileKey, patch) =>
+ set((state) => {
+ const current = state.files[fileKey];
+ if (!current) return {};
+ const file = { ...current, ...patch };
+ // An edit keeps a preview tab, the way typing in it would.
+ const tabs =
+ patch.dirty && !current.dirty
+ ? state.tabs.map((tab) => (tab.fileKey === fileKey && tab.preview ? { ...tab, preview: false } : tab))
+ : state.tabs;
+ return { files: { ...state.files, [fileKey]: file }, tabs };
+ }),
+
+ setVisible: (visible) => set({ visible }),
+ setQuickOpen: (quickOpen) => set({ quickOpen }),
+ setCursor: (cursor) => set({ cursor }),
+
+ renamePath: (workspaceId, from, to) =>
+ set((state) => {
+ const moved = (path: string) => (isUnder(path, from) ? to + path.slice(from.length) : path);
+ const tabs = state.tabs.map((tab) => {
+ if (tab.workspaceId !== workspaceId || !isUnder(tab.path, from)) return tab;
+ const path = moved(tab.path);
+ const fileKey = fileKeyOf(workspaceId, path);
+ return { ...tab, path, fileKey, key: tabKeyOf(tab.mode, fileKey) };
+ });
+ const files: Record<string, EditorFile> = {};
+ for (const [key, file] of Object.entries(state.files)) {
+ if (file.workspaceId !== workspaceId || !isUnder(file.path, from)) files[key] = file;
+ else {
+ const path = moved(file.path);
+ files[fileKeyOf(workspaceId, path)] = { ...file, path };
+ }
+ }
+ const activeKey = state.active[workspaceId];
+ const activeTab = activeKey ? state.tabs.findIndex((tab) => tab.key === activeKey) : -1;
+ return {
+ tabs,
+ files,
+ active: { ...state.active, [workspaceId]: activeTab >= 0 ? tabs[activeTab].key : (activeKey ?? null) },
+ };
+ }),
+
+ markDeleted: (workspaceId, path) =>
+ set((state) => {
+ const files = { ...state.files };
+ for (const [key, file] of Object.entries(files)) {
+ if (file.workspaceId === workspaceId && isUnder(file.path, path)) files[key] = { ...file, deleted: true, version: null };
+ }
+ return { files };
+ }),
+}));
+
+/** The tabs of one workspace, in order. */
+export function tabsOf(state: Pick<CodeEditorState, "tabs">, workspaceId: string | null): EditorTab[] {
+ return workspaceId ? state.tabs.filter((tab) => tab.workspaceId === workspaceId) : [];
+}
+
+// An unsaved buffer holds off the automatic reload a new frontend build
+// triggers (lib/bundleWatch), so a rebuild never throws away typed code.
+useCodeEditorStore.subscribe((state) => {
+ setReloadHold(
+ "code-editor",
+ Object.values(state.files).some((file) => file.dirty),
+ );
+});
diff --git a/jarvis/ui/web/frontend/src/store/ideExplorer.ts b/jarvis/ui/web/frontend/src/store/ideExplorer.ts
index 4be85c9f49..636e4222f5 100644
--- a/jarvis/ui/web/frontend/src/store/ideExplorer.ts
+++ b/jarvis/ui/web/frontend/src/store/ideExplorer.ts
@@ -1,52 +1,140 @@
import { useEffect } from "react";
import { create } from "zustand";
+import { fetchFileVersion } from "@/components/agentic/editor/editorApi";
+import { openTerminalTarget } from "@/lib/agenticIdeApi";
import { OPEN_PATH_EVENT } from "@/lib/terminalLinks";
+import { useCodeEditorStore } from "@/store/codeEditor";
+import { useEventStore } from "@/store/events";
import { useIdeChatStore } from "@/store/ideChat";
import { useIdeSidePanelStore } from "@/store/ideSidePanel";
/**
- * The Changes and Folder tabs' state: which file each of them has open.
+ * The side panel's Changes and Folder tabs.
*
- * Kept outside the component because a file can be opened from elsewhere: a
- * Ctrl+click on a path a coding agent printed in its terminal lands here (see
- * `OPEN_PATH_EVENT`), opens the side panel on the Folder tab, and shows that
- * file's diff. Each tab keeps its own open file, so opening one in Changes
- * does not cover the tree in Folder.
+ * Files open in the code editor (store/codeEditor). This store only carries a
+ * "reveal" request: show one path in the Folder tab's tree, expanding the
+ * folders above it — the editor's "Reveal in Explorer", and a Ctrl+click on a
+ * folder a coding agent printed in its terminal.
*/
export type ExplorerView = "files" | "changes";
export interface OpenedFile {
workspaceId: string;
- /** Workspace-relative, or an absolute path inside the workspace as printed. */
+ /** Workspace-relative POSIX path. */
path: string;
}
+export interface RevealRequest extends OpenedFile {
+ nonce: number;
+}
+
interface IdeExplorerState {
- opened: Record<ExplorerView, OpenedFile | null>;
- open: (view: ExplorerView, file: OpenedFile) => void;
- close: (view: ExplorerView) => void;
+ revealed: RevealRequest | null;
+ reveal: (file: OpenedFile) => void;
}
+let nonce = 0;
+
export const useIdeExplorerStore = create<IdeExplorerState>((set) => ({
- opened: { files: null, changes: null },
- open: (view, file) => set((state) => ({ opened: { ...state.opened, [view]: file } })),
- close: (view) => set((state) => ({ opened: { ...state.opened, [view]: null } })),
+ revealed: null,
+ reveal: (file) => set({ revealed: { ...file, nonce: ++nonce } }),
}));
+/** Show a path in the Folder tab, bringing the side panel up if needed. */
+export function revealInExplorer(file: OpenedFile): void {
+ useIdeExplorerStore.getState().reveal(file);
+ useIdeSidePanelStore.getState().openTab("files");
+}
+
export interface OpenPathDetail {
workspaceId: string;
path: string;
}
-/** Open a file in the side panel's Folder tab, bringing the panel up if needed. */
-export function openInExplorer(file: OpenedFile): void {
- useIdeExplorerStore.getState().open("files", file);
- useIdeSidePanelStore.getState().openTab("files");
+export interface PrintedPath {
+ /** Workspace-relative POSIX path; null when it points outside the workspace. */
+ path: string | null;
+ line?: number;
+ column?: number;
+}
+
+const LOCATION = /(?:#L(\d+)(?::(\d+))?|:(\d+)(?::(\d+))?|\((\d+)(?:,(\d+))?\))$/i;
+
+/**
+ * A path as a coding agent printed it (`src/app.ts:42:7`, an absolute path,
+ * a `file:` URI) turned into a workspace-relative path and a line to jump to.
+ */
+export function parsePrintedPath(workspaceRoot: string, printed: string): PrintedPath {
+ let value = printed.trim().replace(/^["'`]|["'`]$/g, "");
+ let line: number | undefined;
+ let column: number | undefined;
+ const location = LOCATION.exec(value);
+ if (location) {
+ const [, l1, c1, l2, c2, l3, c3] = location;
+ line = Number(l1 ?? l2 ?? l3);
+ const col = c1 ?? c2 ?? c3;
+ column = col ? Number(col) : undefined;
+ value = value.slice(0, location.index);
+ }
+ if (/^file:/i.test(value)) {
+ try {
+ value = decodeURIComponent(new URL(value).pathname).replace(/^\/([a-z]:)/i, "$1");
+ } catch {
+ return { path: null };
+ }
+ }
+ const slashes = (text: string) => text.replace(/\\/g, "/");
+ let path = slashes(value);
+ const root = slashes(workspaceRoot).replace(/\/+$/, "");
+ const absolute = path.startsWith("/") || /^[a-z]:\//i.test(path);
+ if (absolute) {
+ // Windows paths compare case-insensitively; POSIX paths exactly.
+ const windows = /^[a-z]:\//i.test(root);
+ const head = windows ? path.slice(0, root.length + 1).toLowerCase() : path.slice(0, root.length + 1);
+ const want = windows ? `${root.toLowerCase()}/` : `${root}/`;
+ if (head !== want) return { path: null };
+ path = path.slice(root.length + 1);
+ }
+ path = path.replace(/^(\.\/)+/, "").replace(/\/+$/, "");
+ if (!path || path.split("/").includes("..")) return { path: null };
+ return { path, line, column };
+}
+
+/**
+ * Open what a terminal path points at: a file in the editor (at its line), a
+ * folder in the Folder tab, anything outside the workspace with the system app.
+ */
+export async function openPrintedPath(workspaceId: string, workspaceRoot: string, printed: string): Promise<void> {
+ const parsed = parsePrintedPath(workspaceRoot, printed);
+ const external = () =>
+ openTerminalTarget(workspaceId, printed).catch((error: unknown) =>
+ useEventStore.getState().pushToast("error", (error as Error).message),
+ );
+ if (parsed.path === null) {
+ await external();
+ return;
+ }
+ let version: string | null;
+ try {
+ version = await fetchFileVersion(workspaceId, parsed.path);
+ } catch {
+ await external();
+ return;
+ }
+ if (version === null) {
+ revealInExplorer({ workspaceId, path: parsed.path });
+ return;
+ }
+ useCodeEditorStore.getState().openFile(workspaceId, parsed.path, {
+ preview: false,
+ line: parsed.line,
+ column: parsed.column,
+ });
}
/**
- * Route terminal path clicks into the Folder tab while the Agentic IDE is mounted.
+ * Route terminal path clicks into the editor while the Agentic IDE is mounted.
*
* Only for the workspace on screen: a path from another workspace's pane has
* no tree here to show it in, so it keeps the old behaviour.
@@ -55,10 +143,10 @@ export function useExplorerPathRouting(): void {
useEffect(() => {
const onOpen = (event: Event) => {
const detail = (event as CustomEvent<OpenPathDetail>).detail;
- if (!detail?.workspaceId || !detail.path) return;
- if (useIdeChatStore.getState().workspace?.id !== detail.workspaceId) return;
+ const workspace = useIdeChatStore.getState().workspace;
+ if (!detail?.workspaceId || !detail.path || workspace?.id !== detail.workspaceId) return;
event.preventDefault();
- openInExplorer({ workspaceId: detail.workspaceId, path: detail.path });
+ void openPrintedPath(detail.workspaceId, workspace.path, detail.path);
};
window.addEventListener(OPEN_PATH_EVENT, onOpen);
return () => window.removeEventListener(OPEN_PATH_EVENT, onOpen);
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
index 99629db6d3..77385f44e3 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
@@ -29,6 +29,8 @@ import { useIdeProjectsStore } from "@/store/ideProjects";
import { useIdeSkillsStore } from "@/store/ideSkills";
import { useIdeThreadsStore } from "@/store/ideThreads";
import { ThreadView } from "@/components/agentic/threads/ThreadView";
+import { CodeEditorStage } from "@/components/agentic/editor/CodeEditorStage";
+import { useCodeEditorStore } from "@/store/codeEditor";
import { openProject } from "@/lib/chatLibraryApi";
import {
activateWorkspace, addTerminal, closeTerminal, closeWorkspace, fetchIdeAgents, fetchIdeProjects, fetchIdeState, renameWorkspace,
@@ -82,6 +84,10 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
// Grid of terminals, or one thread at a time (see store/ideThreads).
const layout = useIdeThreadsStore((state) => state.layout);
const threads = layout === "threads";
+ // The code editor lies over the grid or the thread; both stay mounted underneath.
+ const ideWorkspace = useIdeChatStore((state) => state.workspace);
+ const stagedPane = useIdeChatStore((state) => state.stagedPane);
+ const editorShown = useCodeEditorStore((state) => state.visible && state.tabs.some((tab) => tab.workspaceId === ideWorkspace?.id));
const [state, setState] = useState<IdeState | null>(null);
const [projects, setProjects] = useState<IdeProject[]>([]);
const [agents, setAgents] = useState<AgentStatus[]>([]);
@@ -565,11 +571,12 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
<main className="min-h-0 flex-1">
<IdeSidePanelFrame markInUse={paneStyle === "minimal"} appearance={appearance ?? undefined} onScreen={onScreen}>
- {threads && <ThreadView onScreen={onScreen} />}
+ <div className="relative h-full min-h-0">
+ {threads && <ThreadView onScreen={onScreen && !editorShown} />}
{/* The grid stays mounted behind the threads: its terminals keep running
and come back exactly as they were when the layout switches back. */}
<div hidden={threads} className="h-full min-h-0">
- {session ? <RetainedWorkspaceGrid session={session} onScreen={onScreen && !threads} workspaceIds={state.workspaces?.map((workspace) => workspace.id)} onChanged={(next) => setState((current) => current?.session?.id === next.id ? { ...current, session: next } : current)}
+ {session ? <RetainedWorkspaceGrid session={session} onScreen={onScreen && !threads && !editorShown} workspaceIds={state.workspaces?.map((workspace) => workspace.id)} onChanged={(next) => setState((current) => current?.session?.id === next.id ? { ...current, session: next } : current)}
onAdd={openAgentPicker} onClose={closeAgent} onSelect={setSelected} selected={selected} fontSize={fontSize} appearance={appearance} disabled={busy}
onMutationStart={beginGridMutation} onMutationEnd={endGridMutation} paneStyle={paneStyle} workspaces={state.workspaces ?? []} />
: <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">
@@ -579,6 +586,8 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
<button type="button" onClick={() => setProjectDialog(true)} className="mt-2 rounded-md border border-border px-3 py-1.5 text-sm hover:bg-accent">Connect folder</button>
</div>}
</div>
+ <CodeEditorStage workspaceId={ideWorkspace?.id ?? null} workspacePath={ideWorkspace?.path ?? ""} stagedPane={stagedPane} />
+ </div>
</IdeSidePanelFrame>
</main>