/** * ProjectSelectModal * * Shown when the user first enters Coding Mode (or clicks "Switch Project"). * Four tabs: * 1. Default Workspace – use the agent's default workspace_dir * 2. Clone Repository – git clone a public URL with SSE progress * 3. Open Local Path – enter an absolute path * 4. New Project – create an empty dir + git init */ import { useState, useRef, useEffect } from "react"; import { Modal, Tabs, Input, Button, Alert, List } from "antd"; import { ChevronRight, Eye, EyeOff, Folder, FolderOpen, FolderSymlink, GitBranch, HardDrive, Home, PlusCircle, RotateCcw, X, } from "lucide-react"; import { useTranslation } from "react-i18next"; import { projectDirectoryApi, type BrowseDirsResponse, type ProjectListItem, } from "../../api/modules/projectDirectory"; import { useProjectDir } from "../../stores/projectDirectoryStore"; import styles from "./index.module.less"; interface ProjectSelectModalProps { open: boolean; onClose: () => void; onConfirm: (path: string | null) => void; } // --------------------------------------------------------------------------- // Clone progress event // --------------------------------------------------------------------------- interface CloneEvent { type: "log" | "done" | "error"; line?: string; path?: string; name?: string; detail?: string; } // --------------------------------------------------------------------------- // Tab: Workspace // --------------------------------------------------------------------------- function WorkspaceTab({ workspaceDir, onSelect, }: { workspaceDir: string | null; onSelect: (path: null) => void; }) { const { t } = useTranslation(); return (
{workspaceDir && (
{t("codingMode.workingDir")}: {workspaceDir}
)}
); } // --------------------------------------------------------------------------- // Tab: Clone // --------------------------------------------------------------------------- function CloneTab({ onDone }: { onDone: (path: string) => void }) { const { t } = useTranslation(); const [url, setUrl] = useState(""); const [name, setName] = useState(""); const [cloning, setCloning] = useState(false); const [logs, setLogs] = useState([]); const [error, setError] = useState(null); const logEndRef = useRef(null); const handleClone = async () => { if (!url.trim()) return; setCloning(true); setLogs([]); setError(null); try { const res = await projectDirectoryApi.cloneStream( url.trim(), name.trim() || undefined, ); const reader = res.body?.getReader(); if (!reader) throw new Error("No response body"); const decoder = new TextDecoder(); let buf = ""; while (true) { const { done, value } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }); const parts = buf.split("\n\n"); buf = parts.pop() ?? ""; for (const part of parts) { const line = part.startsWith("data: ") ? part.slice(6) : part; if (!line.trim()) continue; try { const evt: CloneEvent = JSON.parse(line); if (evt.type === "log" && evt.line) { setLogs((prev) => { const next = [...prev, evt.line!]; setTimeout(() => logEndRef.current?.scrollIntoView(), 0); return next; }); } else if (evt.type === "done" && evt.path) { setCloning(false); onDone(evt.path); return; } else if (evt.type === "error") { setError(evt.detail ?? "Unknown error"); setCloning(false); return; } } catch { // ignore non-JSON lines } } } } catch (err) { setError(err instanceof Error ? err.message : String(err)); setCloning(false); } }; return (
setUrl(e.target.value)} disabled={cloning} className={styles.input} /> setName(e.target.value)} disabled={cloning} className={styles.input} /> {error && ( )} {logs.length > 0 && (
{logs.map((l, i) => ( // eslint-disable-next-line react/no-array-index-key
{l}
))}
)}
); } // --------------------------------------------------------------------------- // Helpers for LocalPathTab: read a dropped directory recursively, skipping // common large / generated directories so we don't upload gigabytes. // --------------------------------------------------------------------------- const SKIP_SEGMENTS = new Set([ "node_modules", ".git", ".next", "dist", "build", "__pycache__", ".cache", ".venv", "venv", ".mypy_cache", ".tox", ]); function shouldSkipPath(path: string): boolean { return path.split("/").some((seg) => SKIP_SEGMENTS.has(seg)); } async function readDirFiltered( entry: FileSystemDirectoryEntry, ): Promise> { const result: Array<{ path: string; file: File }> = []; const reader = entry.createReader(); const readBatch = (): Promise => new Promise((resolve, reject) => reader.readEntries(resolve, reject)); let batch: FileSystemEntry[]; do { batch = await readBatch(); for (const item of batch) { if (shouldSkipPath(item.fullPath)) continue; if (item.isFile) { const file = await new Promise((resolve, reject) => (item as FileSystemFileEntry).file(resolve, reject), ); result.push({ path: item.fullPath.replace(/^\//, ""), file }); } else if (item.isDirectory) { const sub = await readDirFiltered(item as FileSystemDirectoryEntry); result.push(...sub); } } } while (batch.length > 0); return result; } type FolderSelection = { name: string; entries: Array<{ path: string; file: File }>; }; // --------------------------------------------------------------------------- // Tab: Open Local Path // --------------------------------------------------------------------------- function LocalPathTab({ onSelect }: { onSelect: (path: string) => void }) { const { t } = useTranslation(); const [localSel, setLocalSel] = useState(null); const [dragOver, setDragOver] = useState(false); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const dirInputRef = useRef(null); useEffect(() => { const prevent = (e: DragEvent) => e.preventDefault(); const clear = () => setDragOver(false); document.addEventListener("dragover", prevent); document.addEventListener("drop", prevent); window.addEventListener("dragend", clear); window.addEventListener("drop", clear); return () => { document.removeEventListener("dragover", prevent); document.removeEventListener("drop", prevent); window.removeEventListener("dragend", clear); window.removeEventListener("drop", clear); }; }, []); // System folder picker — same hidden input pattern as plugin install modal const handleDirPicked = (e: React.ChangeEvent) => { const files = Array.from(e.target.files ?? []).filter( (f) => !shouldSkipPath(f.webkitRelativePath), ); if (files.length === 0) return; const folderName = files[0].webkitRelativePath.split("/")[0]; setLocalSel({ name: folderName, entries: files.map((f) => ({ path: f.webkitRelativePath, file: f })), }); e.target.value = ""; }; const handleDragOver = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setDragOver(true); }; const handleDragLeave = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setDragOver(false); }; const handleDrop = async (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setDragOver(false); const items = Array.from(e.dataTransfer.items); if (items.length === 0) return; const entry = items[0].webkitGetAsEntry(); if (!entry?.isDirectory) return; try { const entries = await readDirFiltered(entry as FileSystemDirectoryEntry); setLocalSel({ name: entry.name, entries }); } catch { setError(t("codingMode.dropFailed")); } }; const handleImport = async () => { if (!localSel) return; setLoading(true); setError(null); try { const { default: JSZip } = await import("jszip"); const zip = new JSZip(); for (const { path, file } of localSel.entries) { zip.file(path, file); } const blob = await zip.generateAsync({ type: "blob" }); const zipFile = new File([blob], `${localSel.name}.zip`, { type: "application/zip", }); const res = await projectDirectoryApi.uploadZip(zipFile, localSel.name); onSelect(res.path); } catch (err: unknown) { setError(err instanceof Error ? err.message : "Import failed"); } finally { setLoading(false); } }; return (
{localSel ? ( <>
{localSel.name}
{error && ( )} ) : (
void handleDrop(e)} onClick={() => dirInputRef.current?.click()} role="button" tabIndex={0} onKeyDown={(e) => e.key === "Enter" && dirInputRef.current?.click()} > {t("codingMode.dropPrimary")} {t("codingMode.dropSecondary")}
)}
); } // --------------------------------------------------------------------------- // Tab: Open Existing Directory (server-side file browser, no copy) // --------------------------------------------------------------------------- function OpenDirTab({ onSelect }: { onSelect: (path: string) => void }) { const { t } = useTranslation(); const [browsePath, setBrowsePath] = useState("~"); const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [showHidden, setShowHidden] = useState(false); const listRef = useRef(null); const navSeq = useRef(0); const navigate = (path: string) => { const seq = ++navSeq.current; setBrowsePath(path); setLoading(true); setError(null); projectDirectoryApi .browseDirs(path, showHidden) .then((res) => { if (seq !== navSeq.current) return; setData(res); listRef.current?.scrollTo(0, 0); }) .catch((err: unknown) => { if (seq !== navSeq.current) return; setError(err instanceof Error ? err.message : String(err)); }) .finally(() => { if (seq === navSeq.current) setLoading(false); }); }; useEffect(() => { navigate("~"); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // Re-fetch current directory when the hidden-folders toggle changes. // navSeq already discards stale responses, so unconditional re-fetch is safe. useEffect(() => { navigate(browsePath); // eslint-disable-next-line react-hooks/exhaustive-deps }, [showHidden]); const breadcrumbParts = data?.current.split("/").filter(Boolean) ?? []; return (
{/* Quick-access shortcuts */}
{/* Breadcrumb */} {data && (
navigate("/")} role="button" tabIndex={0} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); navigate("/"); } }} > / {breadcrumbParts.map((seg, i) => { const segPath = "/" + breadcrumbParts.slice(0, i + 1).join("/"); const isLast = i === breadcrumbParts.length - 1; return ( !isLast && navigate(segPath)} role={isLast ? undefined : "button"} tabIndex={isLast ? undefined : 0} onKeyDown={(e) => { if (!isLast && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); navigate(segPath); } }} > {seg} ); })}
)} {/* Directory listing */}
{loading && (
{t("codingMode.openDirLoading")}
)} {error && ( )} {!loading && !error && data && ( <> {data.parent && (
navigate(data.parent!)} role="button" tabIndex={0} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); navigate(data.parent!); } }} > ..
)} {data.dirs.length === 0 && !data.parent && (
{t("codingMode.openDirEmpty")}
)} {data.dirs.map((dir) => (
navigate(dir.path)} role="button" tabIndex={0} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); navigate(dir.path); } }} > {dir.name}
))} )}
{/* Confirm button */} {data && !loading && data.selectable !== false && ( )}
); } // --------------------------------------------------------------------------- // Tab: New Project // --------------------------------------------------------------------------- function NewProjectTab({ onDone }: { onDone: (path: string) => void }) { const { t } = useTranslation(); const [name, setName] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const handleCreate = async () => { if (!name.trim()) return; setLoading(true); setError(null); try { const res = await projectDirectoryApi.create(name.trim()); onDone(res.path); } catch (err: unknown) { const detail = err instanceof Error ? err.message : "Failed to create project"; setError(detail); } finally { setLoading(false); } }; return (
setName(e.target.value)} className={styles.input} /> {error && ( )}
); } // --------------------------------------------------------------------------- // Recent Projects list (shown below tabs) // --------------------------------------------------------------------------- function RecentProjects({ projects, onSelect, }: { projects: ProjectListItem[]; onSelect: (path: string) => void; }) { if (projects.length === 0) return null; return (
Recent
( onSelect(item.path)} > {item.name} {item.path} )} />
); } // --------------------------------------------------------------------------- // Main Modal // --------------------------------------------------------------------------- export default function ProjectSelectModal({ open, onClose, onConfirm, }: ProjectSelectModalProps) { const { t } = useTranslation(); const { setProjectDir } = useProjectDir(); const [projects, setProjects] = useState([]); const [activeTab, setActiveTab] = useState("workspace"); // The agent's default workspace directory (fetched from backend) const [workspaceDir, setWorkspaceDir] = useState(null); const handleOpen = () => { projectDirectoryApi .list() .then(setProjects) .catch(() => undefined); // GET returns workspace_dir field alongside the active project projectDirectoryApi .get() .then((info) => { if (info.workspace_dir) setWorkspaceDir(info.workspace_dir); }) .catch(() => undefined); }; const handleConfirm = async (path: string | null) => { if (path !== undefined) { // For workspace default (path === null), explicitly reset on backend too if (path === null) { try { await projectDirectoryApi.set(null); } catch { // ignore – best effort } } setProjectDir(path); onConfirm(path); } }; const handlePathSelected = async (path: string) => { try { await projectDirectoryApi.set(path); } catch { // best effort } setProjectDir(path); onConfirm(path); }; const handleCloneDone = async (path: string) => { // After clone, the server already set the active project; update store. setProjectDir(path); onConfirm(path); }; const handleLocalDone = (path: string) => { setProjectDir(path); onConfirm(path); }; const handleNewDone = (path: string) => { setProjectDir(path); onConfirm(path); }; const tabItems = [ { key: "workspace", label: ( {t("codingMode.tabWorkspace")} ), children: ( void handleConfirm(null)} /> ), }, { key: "clone", label: ( {t("codingMode.tabClone")} ), children: void handleCloneDone(p)} />, }, { key: "opendir", label: ( {t("codingMode.tabOpenDir")} ), children: void handlePathSelected(p)} />, }, { key: "local", label: ( {t("codingMode.tabLocal")} ), children: , }, { key: "new", label: ( {t("codingMode.tabNew")} ), children: , }, ]; return ( isOpen && handleOpen()} className={styles.modal} >

{t("codingMode.selectProjectDesc")}

void handlePathSelected(p)} />
); }