Users, file manager, image generation, budgets and agent workflow
- User management: local accounts (Argon2) and OpenID Connect, admin/user roles, per-user folders plus admin-shared folders, read-only session sharing, event filtering per user - File manager with CodeMirror editor and git client (status, diff, stage, commit, branches, fetch/pull/push, log, clone/init) - Image generation via fal.ai: generate_image tool and image page - Budgets: monthly limits per provider, provider balances/costs (OpenRouter, Anthropic admin cost report, fal.ai), price discovery - Subagents on other models, background tasks, concurrency limits per host/model/subagent - MCP tools loaded on demand (mcp_search/mcp_call), read-only hints - Permission mode "auto", safe read-only commands always allowed - Persistent message queue with attachments, deletable - Live reasoning incl. <think> tags, activity animations, CSS themes, mobile layout, statistics per user, upload size handling - Docker: named volume for state, localhost-bound port Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f3a2fe3816
commit
49262c612c
70 files changed
+8495
-714
No files matched your search
@@ -0,0 +1,442 @@
|
||||
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { del, get, post, put } from "../api";
|
||||
import { useFetch } from "../hooks";
|
||||
import { fmtCompact, fmtDate, useT } from "../i18n";
|
||||
import { Spinner } from "./Activity";
|
||||
import { Diff } from "./Diff";
|
||||
import { Markdown } from "./Markdown";
|
||||
import { GitPanel, type GitStatus } from "./GitPanel";
|
||||
|
||||
const CodeEditor = lazy(() => import("./CodeEditor").then((m) => ({ default: m.CodeEditor })));
|
||||
|
||||
interface Entry {
|
||||
name: string;
|
||||
path: string;
|
||||
is_dir: boolean;
|
||||
size: number;
|
||||
mtime?: number;
|
||||
}
|
||||
|
||||
interface Listing {
|
||||
path: string;
|
||||
parent: string | null;
|
||||
entries: Entry[];
|
||||
repo: string | null;
|
||||
}
|
||||
|
||||
interface OpenFile {
|
||||
path: string;
|
||||
content: string;
|
||||
saved: string;
|
||||
mtime?: number;
|
||||
binary: boolean;
|
||||
tooLarge?: boolean;
|
||||
}
|
||||
|
||||
/** What the right pane shows. */
|
||||
type Pane = { kind: "file"; file: OpenFile } | { kind: "diff"; title: string; diff: string } | { kind: "none" };
|
||||
|
||||
const IMAGE = /\.(png|jpe?g|gif|webp)$/i;
|
||||
const rawUrl = (p: string, download = false) => `/api/files/raw?path=${encodeURIComponent(p)}${download ? "&download=true" : ""}`;
|
||||
const baseName = (p: string) => p.split("/").filter(Boolean).pop() ?? p;
|
||||
const dirName = (p: string) => p.replace(/\/[^/]+\/?$/, "") || "/";
|
||||
|
||||
function icon(e: Entry) {
|
||||
if (e.is_dir) return "📁";
|
||||
if (IMAGE.test(e.name)) return "🖼";
|
||||
if (/\.(md|txt)$/i.test(e.name)) return "📝";
|
||||
return "📄";
|
||||
}
|
||||
|
||||
export function Files({ onMenu }: { onMenu: () => void }) {
|
||||
const t = useT();
|
||||
const roots = useFetch<{ path: string; name: string }[]>("/fs/roots").data ?? [];
|
||||
const [dir, setDir] = useState<string>(() => localStorage.getItem("codecraft.filesDir") ?? "");
|
||||
const [listing, setListing] = useState<Listing>();
|
||||
const [hidden, setHidden] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
const [pane, setPane] = useState<Pane>({ kind: "none" });
|
||||
const [tab, setTab] = useState<"files" | "git">("files");
|
||||
const [git, setGit] = useState<GitStatus>();
|
||||
const [search, setSearch] = useState("");
|
||||
const [hits, setHits] = useState<{ path: string; is_dir: boolean }[]>();
|
||||
const [preview, setPreview] = useState(false);
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const [mobileEditor, setMobileEditor] = useState(false);
|
||||
const uploadRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = useCallback(
|
||||
async (path: string) => {
|
||||
try {
|
||||
const l = await get<Listing>(`/files/list?path=${encodeURIComponent(path)}&hidden=${hidden}`);
|
||||
setListing(l);
|
||||
setDir(l.path);
|
||||
localStorage.setItem("codecraft.filesDir", l.path);
|
||||
setError(undefined);
|
||||
} catch (e: any) {
|
||||
setError(e.message);
|
||||
if (roots[0] && path !== roots[0].path) void load(roots[0].path);
|
||||
}
|
||||
},
|
||||
[hidden, roots],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (roots.length) void load(dir || roots[0].path);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [roots.length, hidden]);
|
||||
|
||||
const refreshGit = useCallback(async () => {
|
||||
if (!listing?.repo) return setGit(undefined);
|
||||
try {
|
||||
setGit(await post<GitStatus>("/git", { path: listing.repo, action: "status" }));
|
||||
} catch {
|
||||
setGit(undefined);
|
||||
}
|
||||
}, [listing?.repo]);
|
||||
useEffect(() => void refreshGit(), [refreshGit]);
|
||||
|
||||
// Git state per file name in the current directory.
|
||||
const gitMarks = useMemo(() => {
|
||||
const m = new Map<string, string>();
|
||||
if (!git || !listing) return m;
|
||||
for (const f of git.files) {
|
||||
const abs = `${git.repo}/${f.path}`;
|
||||
const code = f.index === "?" ? "U" : (f.index.trim() || f.worktree.trim());
|
||||
// Mark the file itself and every parent folder inside the listing.
|
||||
if (dirName(abs) === listing.path) m.set(abs, code);
|
||||
for (const e of listing.entries) if (e.is_dir && abs.startsWith(e.path + "/")) m.set(e.path, "•");
|
||||
}
|
||||
return m;
|
||||
}, [git, listing]);
|
||||
|
||||
const dirty = pane.kind === "file" && pane.file.content !== pane.file.saved;
|
||||
|
||||
const confirmDiscard = () => !dirty || confirm(t("files.discardChanges"));
|
||||
|
||||
const openFile = async (path: string) => {
|
||||
if (!confirmDiscard()) return;
|
||||
try {
|
||||
const r = await get<{ content?: string; binary: boolean; mtime?: number; too_large?: boolean }>(`/files/read?path=${encodeURIComponent(path)}`);
|
||||
setPane({ kind: "file", file: { path, content: r.content ?? "", saved: r.content ?? "", mtime: r.mtime, binary: r.binary, tooLarge: r.too_large } });
|
||||
setPreview(/\.md$/i.test(path));
|
||||
setMobileEditor(true);
|
||||
} catch (e: any) {
|
||||
alert(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
const save = useCallback(
|
||||
async (force = false) => {
|
||||
if (pane.kind !== "file") return;
|
||||
const f = pane.file;
|
||||
try {
|
||||
const r = await put<{ mtime: number }>("/files/write", { path: f.path, content: f.content, expected_mtime: f.mtime, force });
|
||||
setPane({ kind: "file", file: { ...f, saved: f.content, mtime: r.mtime } });
|
||||
void refreshGit();
|
||||
} catch (e: any) {
|
||||
if (e.status === 409 && confirm(t("files.conflict"))) return save(true);
|
||||
alert(e.message);
|
||||
}
|
||||
},
|
||||
[pane, refreshGit, t],
|
||||
);
|
||||
|
||||
const act = async (fn: () => Promise<unknown>) => {
|
||||
try {
|
||||
await fn();
|
||||
if (listing) await load(listing.path);
|
||||
void refreshGit();
|
||||
} catch (e: any) {
|
||||
alert(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
const newEntry = (isDir: boolean) => {
|
||||
const name = prompt(isDir ? t("files.newFolderName") : t("files.newFileName"));
|
||||
if (!name || !listing) return;
|
||||
const path = `${listing.path}/${name}`;
|
||||
void act(async () => {
|
||||
await post("/files/create", { path, dir: isDir });
|
||||
if (!isDir) await openFile(path);
|
||||
});
|
||||
};
|
||||
|
||||
const rename = (e: Entry) => {
|
||||
const name = prompt(t("files.renameTo"), e.name);
|
||||
if (name && name !== e.name) void act(() => post("/files/move", { from: e.path, to: `${dirName(e.path)}/${name}` }));
|
||||
};
|
||||
|
||||
const duplicate = (e: Entry) => {
|
||||
const name = prompt(t("files.copyTo"), `${e.name.replace(/(\.[^.]*)?$/, " copy$1")}`);
|
||||
if (name) void act(() => post("/files/move", { from: e.path, to: `${dirName(e.path)}/${name}`, copy: true }));
|
||||
};
|
||||
|
||||
const remove = (e: Entry) => {
|
||||
if (confirm(t(e.is_dir ? "files.deleteFolderConfirm" : "files.deleteConfirm", { name: e.name }))) {
|
||||
void act(() => del(`/files/delete?path=${encodeURIComponent(e.path)}`));
|
||||
if (pane.kind === "file" && pane.file.path.startsWith(e.path)) setPane({ kind: "none" });
|
||||
}
|
||||
};
|
||||
|
||||
const upload = async (files: FileList | File[]) => {
|
||||
if (!listing) return;
|
||||
for (const f of [...files]) {
|
||||
const res = await fetch(`/api/files/upload?path=${encodeURIComponent(`${listing.path}/${f.name}`)}`, { method: "PUT", body: f, credentials: "same-origin" });
|
||||
if (!res.ok) alert(`${f.name}: HTTP ${res.status}${res.status === 413 ? " – too large for the reverse proxy" : ""}`);
|
||||
}
|
||||
await load(listing.path);
|
||||
void refreshGit();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!search.trim() || !listing) return setHits(undefined);
|
||||
const h = setTimeout(() => {
|
||||
get<{ path: string; is_dir: boolean }[]>(`/files/search?path=${encodeURIComponent(listing.path)}&q=${encodeURIComponent(search)}`).then(setHits).catch(() => setHits([]));
|
||||
}, 250);
|
||||
return () => clearTimeout(h);
|
||||
}, [search, listing]);
|
||||
|
||||
// Warn before leaving with unsaved changes.
|
||||
useEffect(() => {
|
||||
const h = (e: BeforeUnloadEvent) => dirty && e.preventDefault();
|
||||
window.addEventListener("beforeunload", h);
|
||||
return () => window.removeEventListener("beforeunload", h);
|
||||
}, [dirty]);
|
||||
|
||||
const root = roots.find((r) => listing?.path.startsWith(r.path));
|
||||
const crumbs = listing && root ? [root.path, ...listing.path.slice(root.path.length).split("/").filter(Boolean)] : [];
|
||||
|
||||
const list = (
|
||||
<div
|
||||
className={`files-list ${dragOver ? "drag" : ""}`}
|
||||
onDragOver={(e) => (e.preventDefault(), setDragOver(true))}
|
||||
onDragLeave={() => setDragOver(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setDragOver(false);
|
||||
void upload(e.dataTransfer.files);
|
||||
}}
|
||||
>
|
||||
<div className="files-toolbar">
|
||||
{roots.length > 1 && (
|
||||
<select value={root?.path ?? ""} onChange={(e) => confirmDiscard() && load(e.target.value)} aria-label={t("images.folder")}>
|
||||
{roots.map((r) => (
|
||||
<option key={r.path} value={r.path}>
|
||||
{r.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<input className="files-search" placeholder={t("files.search")} value={search} onChange={(e) => setSearch(e.target.value)} />
|
||||
<button className="small" title={t("files.newFile")} onClick={() => newEntry(false)}>
|
||||
+ 📄
|
||||
</button>
|
||||
<button className="small" title={t("files.newFolder")} onClick={() => newEntry(true)}>
|
||||
+ 📁
|
||||
</button>
|
||||
<button className="small" title={t("files.upload")} onClick={() => uploadRef.current?.click()}>
|
||||
⤒
|
||||
</button>
|
||||
<input ref={uploadRef} type="file" multiple hidden onChange={(e) => e.target.files && upload(e.target.files)} />
|
||||
<button className={`small ${hidden ? "active" : ""}`} title={t("files.showHidden")} onClick={() => setHidden(!hidden)}>
|
||||
.*
|
||||
</button>
|
||||
</div>
|
||||
<div className="crumbs">
|
||||
{crumbs.map((c, i) => {
|
||||
const path = i === 0 ? c : `${crumbs[0]}/${crumbs.slice(1, i + 1).join("/")}`;
|
||||
return (
|
||||
<span key={path}>
|
||||
{i > 0 && " / "}
|
||||
<a href="#" onClick={(e) => (e.preventDefault(), load(path))}>
|
||||
{i === 0 ? root?.name : c}
|
||||
</a>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{error && <div className="notice err">{error}</div>}
|
||||
<div className="entries" role="list">
|
||||
{hits ? (
|
||||
hits.length === 0 ? (
|
||||
<div className="empty">{t("files.noHits")}</div>
|
||||
) : (
|
||||
hits.map((h) => (
|
||||
<button key={h.path} className="entry" onClick={() => (h.is_dir ? load(h.path) : openFile(h.path))}>
|
||||
<span>{h.is_dir ? "📁" : "📄"}</span>
|
||||
<span className="name">{h.path.slice((listing?.path.length ?? 0) + 1)}</span>
|
||||
</button>
|
||||
))
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
{listing?.parent && (
|
||||
<button className="entry" onClick={() => load(listing.parent!)}>
|
||||
<span>↰</span>
|
||||
<span className="name">..</span>
|
||||
</button>
|
||||
)}
|
||||
{listing?.entries.map((e) => {
|
||||
const mark = gitMarks.get(e.path);
|
||||
const active = pane.kind === "file" && pane.file.path === e.path;
|
||||
return (
|
||||
<div key={e.path} className={`entry ${active ? "active" : ""}`} role="listitem">
|
||||
<button className="entry-main" onClick={() => (e.is_dir ? load(e.path) : openFile(e.path))}>
|
||||
<span>{icon(e)}</span>
|
||||
<span className="name">{e.name}</span>
|
||||
{mark && <span className={`git-mark m-${mark === "•" ? "dot" : mark}`}>{mark}</span>}
|
||||
{!e.is_dir && <span className="size">{fmtCompact(e.size)}B</span>}
|
||||
</button>
|
||||
<details className="entry-menu">
|
||||
<summary aria-label={t("files.actions")}>⋯</summary>
|
||||
<div className="menu">
|
||||
<button onClick={() => rename(e)}>{t("files.rename")}</button>
|
||||
<button onClick={() => duplicate(e)}>{t("files.duplicate")}</button>
|
||||
{!e.is_dir && (
|
||||
<a className="button" href={rawUrl(e.path, true)}>
|
||||
{t("files.download")}
|
||||
</a>
|
||||
)}
|
||||
<button className="danger" onClick={() => remove(e)}>
|
||||
{t("common.delete")}
|
||||
</button>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{listing?.entries.length === 0 && <div className="empty">{t("files.emptyFolder")}</div>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="drop-hint">{t("files.dropHint")}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const right = (() => {
|
||||
if (pane.kind === "diff") {
|
||||
return (
|
||||
<div className="editor-pane">
|
||||
<div className="editor-bar">
|
||||
<button className="ghost small mobile-only" onClick={() => setMobileEditor(false)}>
|
||||
←
|
||||
</button>
|
||||
<b className="grow">{pane.title}</b>
|
||||
</div>
|
||||
<div className="pane-scroll">{pane.diff ? <Diff diff={pane.diff} /> : <div className="empty">{t("git.noDiff")}</div>}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (pane.kind === "none") return <div className="editor-pane empty">{t("files.selectFile")}</div>;
|
||||
const f = pane.file;
|
||||
const isImage = IMAGE.test(f.path);
|
||||
const isMd = /\.md$/i.test(f.path);
|
||||
return (
|
||||
<div className="editor-pane">
|
||||
<div className="editor-bar">
|
||||
<button className="ghost small mobile-only" onClick={() => confirmDiscard() && setMobileEditor(false)}>
|
||||
←
|
||||
</button>
|
||||
<b className="grow" title={f.path}>
|
||||
{baseName(f.path)}
|
||||
{dirty && <span className="dirty"> ●</span>}
|
||||
</b>
|
||||
{isMd && (
|
||||
<button className="small" onClick={() => setPreview(!preview)}>
|
||||
{preview ? t("files.edit") : t("files.preview")}
|
||||
</button>
|
||||
)}
|
||||
<a className="button small" href={rawUrl(f.path, true)}>
|
||||
⤓
|
||||
</a>
|
||||
{!f.binary && (
|
||||
<button className="small primary" disabled={!dirty} onClick={() => save()}>
|
||||
{t("common.save")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{isImage ? (
|
||||
<div className="pane-scroll image-preview">
|
||||
<img src={rawUrl(f.path)} alt={baseName(f.path)} />
|
||||
</div>
|
||||
) : f.binary ? (
|
||||
<div className="empty">{f.tooLarge ? t("files.tooLarge") : t("files.binary")}</div>
|
||||
) : isMd && preview ? (
|
||||
<div className="pane-scroll" style={{ padding: 16 }}>
|
||||
<Markdown text={f.content} />
|
||||
</div>
|
||||
) : (
|
||||
<Suspense fallback={<div className="empty"><Spinner /></div>}>
|
||||
<CodeEditor
|
||||
key={f.path}
|
||||
value={f.content}
|
||||
filename={baseName(f.path)}
|
||||
onChange={(v) => setPane((p) => (p.kind === "file" ? { kind: "file", file: { ...p.file, content: v } } : p))}
|
||||
onSave={() => void save()}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})();
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="topbar">
|
||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||
☰
|
||||
</button>
|
||||
<div className="grow">
|
||||
<h1>{t("nav.files")}</h1>
|
||||
<div className="path">{listing?.path}</div>
|
||||
</div>
|
||||
{listing?.repo && (
|
||||
<div className="mode-tabs" role="tablist">
|
||||
<button className={tab === "files" ? "active" : ""} onClick={() => setTab("files")}>
|
||||
{t("files.tabFiles")}
|
||||
</button>
|
||||
<button className={tab === "git" ? "active" : ""} onClick={() => setTab("git")}>
|
||||
Git{git && git.files.length > 0 ? ` (${git.files.length})` : ""}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={`files-layout ${mobileEditor ? "show-editor" : ""}`}>
|
||||
<div className="files-side">
|
||||
{tab === "git" && listing?.repo ? (
|
||||
<GitPanel
|
||||
repo={listing.repo}
|
||||
status={git}
|
||||
refresh={refreshGit}
|
||||
showDiff={(title, diff) => (setPane({ kind: "diff", title, diff }), setMobileEditor(true))}
|
||||
openFile={openFile}
|
||||
/>
|
||||
) : (
|
||||
list
|
||||
)}
|
||||
{!listing?.repo && listing && (
|
||||
<div className="git-init">
|
||||
<button className="small" onClick={() => act(() => post("/git", { path: listing.path, action: "init" }))}>
|
||||
{t("git.init")}
|
||||
</button>
|
||||
<button
|
||||
className="small"
|
||||
onClick={() => {
|
||||
const url = prompt(t("git.cloneUrl"));
|
||||
if (!url) return;
|
||||
const name = prompt(t("git.cloneFolder"), baseName(url).replace(/\.git$/, ""));
|
||||
if (name) void act(() => post("/git", { path: `${listing.path}/${name}`, action: "clone", url }));
|
||||
}}
|
||||
>
|
||||
{t("git.clone")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="files-main">{right}</div>
|
||||
</div>
|
||||
{pane.kind === "file" && pane.file.mtime && <div className="files-status">{fmtDate(pane.file.mtime)}</div>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user