mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-06 21:11:50 +08:00
feat(sandbox): isolate worker/chat execution in Docker containers with lifecycle UI
- Add Docker sandbox manager, non-root sandbox image, compose isolation, and host firewall script (#217) - Route Bash, custom commands/scripts, stdio MCP, chat sessions, MainAgent chat, and task-scoped reporter screenshots into sandbox containers with per-task browser concurrency gate - Enforce proxy SSRF guard against loopback, metadata, internal services, and admin port - Add dedicated /system/sandbox management page, /chat session sandbox control, and task detail sandbox popover with progressive stats loading
This commit is contained in:
1 parent
6bbeac588d
commit
9c43e694a3
44 files changed
+7086
-91
No files matched your search
@@ -0,0 +1,411 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import {
|
||||
BoxIcon,
|
||||
ExternalLinkIcon,
|
||||
PlayIcon,
|
||||
RefreshCwIcon,
|
||||
RotateCcwIcon,
|
||||
SquareIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverDescription,
|
||||
PopoverHeader,
|
||||
PopoverTitle,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import type { SandboxContainerInfo } from "@/lib/types";
|
||||
|
||||
function fmtBytes(n?: number): string {
|
||||
if (!n || n <= 0) return "0 B";
|
||||
if (n >= 1 << 30) return `${(n / (1 << 30)).toFixed(2)} GiB`;
|
||||
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MiB`;
|
||||
if (n >= 1 << 10) return `${(n / (1 << 10)).toFixed(1)} KiB`;
|
||||
return `${n} B`;
|
||||
}
|
||||
|
||||
function fmtUptime(startedAt?: string): string {
|
||||
if (!startedAt) return "-";
|
||||
const ts = Date.parse(startedAt);
|
||||
if (Number.isNaN(ts)) return "-";
|
||||
const sec = Math.max(0, Math.floor((Date.now() - ts) / 1000));
|
||||
if (sec < 60) return `${sec}s`;
|
||||
const min = Math.floor(sec / 60);
|
||||
if (min < 60) return `${min}m ${sec % 60}s`;
|
||||
const hr = Math.floor(min / 60);
|
||||
if (hr < 24) return `${hr}h ${min % 60}m`;
|
||||
return `${Math.floor(hr / 24)}d ${hr % 24}h`;
|
||||
}
|
||||
|
||||
export function SessionSandboxControl({
|
||||
conversationId,
|
||||
running: chatRunning,
|
||||
}: {
|
||||
conversationId: number;
|
||||
running: boolean;
|
||||
}) {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const ownerID = `conv-${conversationId}`;
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [info, setInfo] = React.useState<SandboxContainerInfo | null>(null);
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
const [busy, setBusy] = React.useState<"" | "start" | "stop" | "recreate" | "remove">("");
|
||||
const [recreateOpen, setRecreateOpen] = React.useState(false);
|
||||
const [clearWorkspace, setClearWorkspace] = React.useState(false);
|
||||
const [removeOpen, setRemoveOpen] = React.useState(false);
|
||||
|
||||
const fetchInfo = React.useCallback(
|
||||
async (withStats: boolean) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.sandboxContainer("session", ownerID, withStats);
|
||||
setInfo(res);
|
||||
} catch {
|
||||
// Ignore transient poll errors; popover refresh button lets user retry.
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[ownerID],
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
setInfo(null);
|
||||
void fetchInfo(false);
|
||||
}, [fetchInfo]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
void fetchInfo(true);
|
||||
}, [open, fetchInfo]);
|
||||
|
||||
// Refresh container status when a chat turn completes (a tool call may have started it).
|
||||
const prevRunningRef = React.useRef(chatRunning);
|
||||
React.useEffect(() => {
|
||||
if (prevRunningRef.current && !chatRunning) {
|
||||
void fetchInfo(open);
|
||||
}
|
||||
prevRunningRef.current = chatRunning;
|
||||
}, [chatRunning, open, fetchInfo]);
|
||||
|
||||
// Hide completely when running in local (non-Docker) mode.
|
||||
if (!info || info.state === "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const running = info.state === "running";
|
||||
const exists = info.state !== "missing";
|
||||
|
||||
let stateLabel = info.state;
|
||||
if (info.state === "running") stateLabel = L("沙箱运行中", "Sandbox Running");
|
||||
else if (info.state === "exited") stateLabel = L("沙箱已停止", "Sandbox Stopped");
|
||||
else if (info.state === "missing") stateLabel = L("沙箱未创建", "Sandbox Standby");
|
||||
else if (info.state === "error") stateLabel = L("沙箱异常", "Sandbox Error");
|
||||
|
||||
let dotClass = "bg-muted-foreground/50";
|
||||
if (running) dotClass = "bg-emerald-500";
|
||||
else if (info.state === "error") dotClass = "bg-red-500";
|
||||
|
||||
const handleStart = async () => {
|
||||
setBusy("start");
|
||||
try {
|
||||
const res = await api.startSandboxContainer("session", ownerID);
|
||||
setInfo(res);
|
||||
toast.success(L("会话沙箱容器已启动", "Session sandbox container started"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleStop = async () => {
|
||||
setBusy("stop");
|
||||
try {
|
||||
const res = await api.stopSandboxContainer("session", ownerID);
|
||||
setInfo(res);
|
||||
toast.success(L("会话沙箱容器已停止(内存已释放)", "Session sandbox container stopped"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy("");
|
||||
}
|
||||
};
|
||||
|
||||
const executeRecreate = async () => {
|
||||
const wipe = clearWorkspace;
|
||||
setRecreateOpen(false);
|
||||
setClearWorkspace(false);
|
||||
setBusy("recreate");
|
||||
try {
|
||||
const res = await api.recreateSandboxContainer("session", ownerID, { clear_workspace: wipe });
|
||||
setInfo(res);
|
||||
toast.success(
|
||||
wipe
|
||||
? L("会话沙箱已重建并清空工作区", "Session sandbox recreated with clean workspace")
|
||||
: L("会话沙箱已重建(工作区文件已保留)", "Session sandbox recreated"),
|
||||
);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy("");
|
||||
}
|
||||
};
|
||||
|
||||
const executeRemove = async () => {
|
||||
setRemoveOpen(false);
|
||||
setBusy("remove");
|
||||
try {
|
||||
await api.removeSandboxContainer("session", ownerID);
|
||||
await fetchInfo(false);
|
||||
toast.success(L("会话沙箱容器已删除(工作区文件已保留)", "Session sandbox container removed"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy("");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button size="sm" variant="outline" className="h-7 gap-1.5 px-2 text-xs">
|
||||
<BoxIcon className="size-3.5" />
|
||||
<span className={`size-1.5 rounded-full ${dotClass}`} />
|
||||
<span className="hidden sm:inline">{stateLabel}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" className="w-80 space-y-3 text-xs">
|
||||
<PopoverHeader>
|
||||
<PopoverTitle className="flex items-center justify-between text-sm">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<BoxIcon className="size-4" />
|
||||
{L("对话隔离沙箱", "Chat Sandbox")}
|
||||
</span>
|
||||
<Badge variant={running ? "default" : "secondary"}>{info.state}</Badge>
|
||||
</PopoverTitle>
|
||||
<PopoverDescription className="text-xs">
|
||||
{L(
|
||||
"本对话调用命令、脚本或浏览器时将在此独立非 root 容器内执行(按需自动创建,空闲自动停机)。",
|
||||
"Commands, scripts, and browser tools in this chat run inside this isolated non-root container (created on demand).",
|
||||
)}
|
||||
</PopoverDescription>
|
||||
</PopoverHeader>
|
||||
|
||||
<div className="space-y-1.5 rounded-md border bg-muted/40 p-2.5 font-mono text-[11px]">
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("会话", "Session")}</span>
|
||||
<span className="truncate">{ownerID}</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("容器", "Container")}</span>
|
||||
<span className="truncate">{info.short_id || "-"}</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("镜像", "Image")}</span>
|
||||
<span className="truncate" title={info.image}>
|
||||
{info.image}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("网络", "Network")}</span>
|
||||
<span className="truncate">{info.network || "-"}</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("活跃执行", "Active runs")}</span>
|
||||
<span>{info.active_runs}</span>
|
||||
</div>
|
||||
{running ? (
|
||||
<>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("运行时长", "Uptime")}</span>
|
||||
<span>{fmtUptime(info.started_at)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">CPU</span>
|
||||
<span>{(info.cpu_percent ?? 0).toFixed(1)}%</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("内存", "Memory")}</span>
|
||||
<span>
|
||||
{fmtBytes(info.mem_usage_bytes)}
|
||||
{info.mem_limit_bytes ? ` / ${fmtBytes(info.mem_limit_bytes)}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
{info.pids_current != null ? (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">PIDs</span>
|
||||
<span>{info.pids_current}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{info.error ? <p className="break-all text-destructive">{info.error}</p> : null}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{!running ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
className="h-7 flex-1 gap-1 text-xs"
|
||||
disabled={busy !== ""}
|
||||
onClick={() => void handleStart()}
|
||||
>
|
||||
<PlayIcon className="size-3.5" />
|
||||
{busy === "start" ? L("启动中…", "Starting…") : L("启动", "Start")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 flex-1 gap-1 text-xs"
|
||||
disabled={busy !== ""}
|
||||
onClick={() => void handleStop()}
|
||||
>
|
||||
<SquareIcon className="size-3.5" />
|
||||
{busy === "stop" ? L("停止中…", "Stopping…") : L("停止", "Stop")}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 gap-1 text-xs"
|
||||
disabled={busy !== ""}
|
||||
onClick={() => {
|
||||
setClearWorkspace(false);
|
||||
setRecreateOpen(true);
|
||||
}}
|
||||
>
|
||||
<RotateCcwIcon className="size-3.5" />
|
||||
{busy === "recreate" ? L("重建中…", "Recreating…") : L("重建", "Recreate")}
|
||||
</Button>
|
||||
{exists ? (
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="h-7 w-7 text-destructive hover:text-destructive"
|
||||
disabled={busy !== ""}
|
||||
onClick={() => setRemoveOpen(true)}
|
||||
title={L("删除容器", "Delete container")}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="h-7 w-7"
|
||||
disabled={loading}
|
||||
onClick={() => void fetchInfo(true)}
|
||||
title={L("刷新", "Refresh")}
|
||||
>
|
||||
<RefreshCwIcon className={`size-3.5 ${loading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end border-t pt-2">
|
||||
<Link
|
||||
href="/system/sandbox"
|
||||
className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{L("前往沙箱容器管理", "All Sandbox Containers")}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</Link>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<AlertDialog open={recreateOpen} onOpenChange={setRecreateOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{L("重建对话沙箱容器", "Recreate Chat Sandbox")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{L(
|
||||
"确定销毁当前对话的旧容器并按最新镜像与资源配额重新创建启动吗?",
|
||||
"Replace this chat's sandbox container with a fresh one using the latest image and limits?",
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="flex items-start gap-2.5 rounded-md border bg-muted/30 p-3 text-xs">
|
||||
<Checkbox
|
||||
id="chat-sandbox-recreate-wipe"
|
||||
checked={clearWorkspace}
|
||||
onCheckedChange={(v) => setClearWorkspace(Boolean(v))}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<Label htmlFor="chat-sandbox-recreate-wipe" className="block cursor-pointer space-y-0.5 font-normal">
|
||||
<div className="font-medium text-foreground">
|
||||
{L("同时清空工作区文件 (/workspace)", "Also clear workspace files (/workspace)")}
|
||||
</div>
|
||||
<div className="text-muted-foreground">
|
||||
{L(
|
||||
"默认保留本对话上传与生成的文件;勾选后将清空 /workspace 下所有文件。",
|
||||
"Session files are preserved by default. Check to wipe /workspace.",
|
||||
)}
|
||||
</div>
|
||||
</Label>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => void executeRecreate()}>
|
||||
{clearWorkspace ? L("清空并重建", "Wipe & Recreate") : L("确认重建", "Recreate")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<AlertDialog open={removeOpen} onOpenChange={setRemoveOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{L("删除对话沙箱容器", "Delete Chat Sandbox")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{L(
|
||||
"确定删除该对话的沙箱容器吗?宿主机工作区文件会保留,后续调用工具时将自动重新创建。",
|
||||
"Remove this chat's sandbox container? Host workspace files will be preserved.",
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() => void executeRemove()}
|
||||
>
|
||||
{L("确认删除", "Delete")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -64,6 +64,7 @@ import { isBtwCommand } from "@/lib/side-questions";
|
||||
import type { Activity, Agent, ChatAttachment, Conversation, LLMProfile } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { SessionSandboxControl } from "./_components/session-sandbox-control";
|
||||
// fmtBytes renders a human file size for attachment chips (mirrors transcript.tsx).
|
||||
function fmtBytes(n: number): string {
|
||||
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MB`;
|
||||
@@ -824,6 +825,7 @@ function ChatView({
|
||||
)}
|
||||
{running && <LiveBadge />}
|
||||
<SideQuestionButton side={side} />
|
||||
<SessionSandboxControl conversationId={conv.id} running={running} />
|
||||
<div className="text-muted-foreground ml-auto flex min-w-0 max-w-full items-center justify-end gap-x-3 gap-y-1 text-xs max-sm:w-full max-sm:flex-wrap">
|
||||
{tokenTotal.turns > 0 && (
|
||||
<span title={translate("overview.roundsHint")} className="tabular-nums">
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import {
|
||||
BoxIcon,
|
||||
ExternalLinkIcon,
|
||||
PlayIcon,
|
||||
RefreshCwIcon,
|
||||
RotateCcwIcon,
|
||||
SquareIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverDescription,
|
||||
PopoverHeader,
|
||||
PopoverTitle,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import type { SandboxContainerInfo, Task } from "@/lib/types";
|
||||
|
||||
function fmtBytes(n?: number): string {
|
||||
if (!n || n <= 0) return "0 B";
|
||||
if (n >= 1 << 30) return `${(n / (1 << 30)).toFixed(2)} GiB`;
|
||||
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MiB`;
|
||||
if (n >= 1 << 10) return `${(n / (1 << 10)).toFixed(1)} KiB`;
|
||||
return `${n} B`;
|
||||
}
|
||||
|
||||
function fmtUptime(startedAt?: string): string {
|
||||
if (!startedAt) return "-";
|
||||
const ts = Date.parse(startedAt);
|
||||
if (Number.isNaN(ts)) return "-";
|
||||
const sec = Math.max(0, Math.floor((Date.now() - ts) / 1000));
|
||||
if (sec < 60) return `${sec}s`;
|
||||
const min = Math.floor(sec / 60);
|
||||
if (min < 60) return `${min}m ${sec % 60}s`;
|
||||
const hr = Math.floor(min / 60);
|
||||
if (hr < 24) return `${hr}h ${min % 60}m`;
|
||||
return `${Math.floor(hr / 24)}d ${hr % 24}h`;
|
||||
}
|
||||
|
||||
export function TaskSandboxControl({ task, onTaskUpdated }: { task: Task; onTaskUpdated: () => void }) {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [info, setInfo] = React.useState<SandboxContainerInfo | null>(null);
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
const [busy, setBusy] = React.useState<"" | "start" | "stop" | "recreate" | "remove">("");
|
||||
const [recreateOpen, setRecreateOpen] = React.useState(false);
|
||||
const [clearWorkspace, setClearWorkspace] = React.useState(false);
|
||||
const [removeOpen, setRemoveOpen] = React.useState(false);
|
||||
|
||||
const fetchInfo = React.useCallback(
|
||||
async (withStats: boolean) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.taskSandbox(task.id, withStats);
|
||||
setInfo(res);
|
||||
} catch {
|
||||
// Ignore transient poll errors; detail popover lets user retry.
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[task.id],
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
void fetchInfo(false);
|
||||
}, [fetchInfo]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
void fetchInfo(true);
|
||||
}, [open, fetchInfo]);
|
||||
|
||||
// Hide completely when running in local (non-Docker) mode.
|
||||
if (!info || info.state === "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const running = info.state === "running";
|
||||
const exists = info.state !== "missing";
|
||||
const taskRunning = task.status === "running" && !task.paused;
|
||||
|
||||
const stateLabel = (() => {
|
||||
switch (info.state) {
|
||||
case "running":
|
||||
return L("沙箱运行中", "Sandbox Running");
|
||||
case "exited":
|
||||
return L("沙箱已停止", "Sandbox Stopped");
|
||||
case "missing":
|
||||
return L("沙箱未创建", "Sandbox Not Created");
|
||||
case "error":
|
||||
return L("沙箱异常", "Sandbox Error");
|
||||
default:
|
||||
return info.state;
|
||||
}
|
||||
})();
|
||||
|
||||
const handleStart = async () => {
|
||||
setBusy("start");
|
||||
try {
|
||||
const res = await api.startTaskSandbox(task.id);
|
||||
setInfo(res);
|
||||
toast.success(L("沙箱容器已启动", "Sandbox container started"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleStop = async () => {
|
||||
if (taskRunning) {
|
||||
const ok = window.confirm(
|
||||
L(
|
||||
"当前任务仍在运行,停止容器会同时暂停该任务。确定继续吗?",
|
||||
"This task is running. Stopping its container will pause the task. Continue?",
|
||||
),
|
||||
);
|
||||
if (!ok) return;
|
||||
}
|
||||
setBusy("stop");
|
||||
try {
|
||||
const res = await api.stopTaskSandbox(task.id, taskRunning);
|
||||
setInfo(res);
|
||||
toast.success(L("沙箱容器已停止(内存已释放)", "Sandbox container stopped"));
|
||||
if (taskRunning) onTaskUpdated();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy("");
|
||||
}
|
||||
};
|
||||
|
||||
const executeRecreate = async () => {
|
||||
const wipe = clearWorkspace;
|
||||
setRecreateOpen(false);
|
||||
setClearWorkspace(false);
|
||||
setBusy("recreate");
|
||||
try {
|
||||
const res = await api.recreateTaskSandbox(task.id, {
|
||||
pause_task: taskRunning,
|
||||
clear_workspace: wipe,
|
||||
});
|
||||
setInfo(res);
|
||||
toast.success(
|
||||
wipe
|
||||
? L("沙箱容器已重建并清空工作区", "Sandbox recreated with clean workspace")
|
||||
: L("沙箱容器已重建(工作区文件已保留)", "Sandbox container recreated"),
|
||||
);
|
||||
if (taskRunning) onTaskUpdated();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy("");
|
||||
}
|
||||
};
|
||||
|
||||
const executeRemove = async () => {
|
||||
setRemoveOpen(false);
|
||||
setBusy("remove");
|
||||
try {
|
||||
await api.removeSandboxContainer("task", task.id);
|
||||
await fetchInfo(false);
|
||||
toast.success(L("沙箱容器已删除(工作区文件已保留)", "Sandbox container removed"));
|
||||
if (taskRunning) onTaskUpdated();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy("");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button size="sm" variant="outline" className="h-7 gap-1.5 px-2 text-xs">
|
||||
<BoxIcon className="size-3.5" />
|
||||
<span
|
||||
className={`size-1.5 rounded-full ${
|
||||
running ? "bg-emerald-500" : info.state === "error" ? "bg-red-500" : "bg-muted-foreground/50"
|
||||
}`}
|
||||
/>
|
||||
<span className="hidden sm:inline">{stateLabel}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" className="w-80 space-y-3 text-xs">
|
||||
<PopoverHeader>
|
||||
<PopoverTitle className="flex items-center justify-between text-sm">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<BoxIcon className="size-4" />
|
||||
{L("任务隔离沙箱", "Task Sandbox")}
|
||||
</span>
|
||||
<Badge variant={running ? "default" : "secondary"}>{info.state}</Badge>
|
||||
</PopoverTitle>
|
||||
<PopoverDescription className="text-xs">
|
||||
{L(
|
||||
"该任务的所有命令、脚本与浏览器均在此隔离容器内运行。",
|
||||
"All commands, scripts, and browser actions for this task run inside this isolated container.",
|
||||
)}
|
||||
</PopoverDescription>
|
||||
</PopoverHeader>
|
||||
|
||||
<div className="space-y-1.5 rounded-md border bg-muted/40 p-2.5 font-mono text-[11px]">
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("容器", "Container")}</span>
|
||||
<span className="truncate">{info.short_id || "-"}</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("镜像", "Image")}</span>
|
||||
<span className="truncate" title={info.image}>
|
||||
{info.image}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("网络", "Network")}</span>
|
||||
<span className="truncate">{info.network || "-"}</span>
|
||||
</div>
|
||||
{info.runtime ? (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("运行时", "Runtime")}</span>
|
||||
<span>{info.runtime}</span>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("活跃执行", "Active runs")}</span>
|
||||
<span>{info.active_runs}</span>
|
||||
</div>
|
||||
{running ? (
|
||||
<>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("运行时长", "Uptime")}</span>
|
||||
<span>{fmtUptime(info.started_at)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">CPU</span>
|
||||
<span>{(info.cpu_percent ?? 0).toFixed(1)}%</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("内存", "Memory")}</span>
|
||||
<span>
|
||||
{fmtBytes(info.mem_usage_bytes)}
|
||||
{info.mem_limit_bytes ? ` / ${fmtBytes(info.mem_limit_bytes)}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
{info.pids_current != null ? (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">PIDs</span>
|
||||
<span>{info.pids_current}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{info.error ? <p className="text-destructive break-all">{info.error}</p> : null}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{!running ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
className="h-7 flex-1 gap-1 text-xs"
|
||||
disabled={busy !== ""}
|
||||
onClick={() => void handleStart()}
|
||||
>
|
||||
<PlayIcon className="size-3.5" />
|
||||
{busy === "start" ? L("启动中…", "Starting…") : L("启动", "Start")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 flex-1 gap-1 text-xs"
|
||||
disabled={busy !== ""}
|
||||
onClick={() => void handleStop()}
|
||||
>
|
||||
<SquareIcon className="size-3.5" />
|
||||
{busy === "stop" ? L("停止中…", "Stopping…") : L("停止", "Stop")}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 gap-1 text-xs"
|
||||
disabled={busy !== ""}
|
||||
onClick={() => {
|
||||
setClearWorkspace(false);
|
||||
setRecreateOpen(true);
|
||||
}}
|
||||
>
|
||||
<RotateCcwIcon className="size-3.5" />
|
||||
{busy === "recreate" ? L("重建中…", "Recreating…") : L("重建", "Recreate")}
|
||||
</Button>
|
||||
{exists ? (
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="h-7 w-7 text-destructive hover:text-destructive"
|
||||
disabled={busy !== ""}
|
||||
onClick={() => setRemoveOpen(true)}
|
||||
title={L("删除容器", "Delete container")}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="h-7 w-7"
|
||||
disabled={loading}
|
||||
onClick={() => void fetchInfo(true)}
|
||||
title={L("刷新", "Refresh")}
|
||||
>
|
||||
<RefreshCwIcon className={`size-3.5 ${loading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end border-t pt-2">
|
||||
<Link
|
||||
href="/system/sandbox"
|
||||
className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{L("前往沙箱容器管理", "All Sandbox Containers")}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</Link>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<AlertDialog open={recreateOpen} onOpenChange={setRecreateOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{L("重建任务沙箱容器", "Recreate Task Sandbox")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{taskRunning
|
||||
? L(
|
||||
"重建容器会暂停当前任务并销毁旧容器,按最新镜像与资源配额重新创建启动。",
|
||||
"Recreating will pause the running task, destroy the old container, and start a fresh one with the latest image and limits.",
|
||||
)
|
||||
: L(
|
||||
"确定销毁旧容器并按最新镜像与资源配额重新创建启动吗?",
|
||||
"Replace this sandbox container with a fresh one using the latest image and limits?",
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="flex items-start gap-2.5 rounded-md border bg-muted/30 p-3 text-xs">
|
||||
<Checkbox
|
||||
id="task-sandbox-recreate-wipe"
|
||||
checked={clearWorkspace}
|
||||
onCheckedChange={(v) => setClearWorkspace(Boolean(v))}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<Label htmlFor="task-sandbox-recreate-wipe" className="block cursor-pointer space-y-0.5 font-normal">
|
||||
<div className="font-medium text-foreground">
|
||||
{L("同时清空工作区文件 (/workspace)", "Also clear workspace files (/workspace)")}
|
||||
</div>
|
||||
<div className="text-muted-foreground">
|
||||
{L(
|
||||
"默认保留任务工作区文件;勾选后将清空 /workspace 下所有产物与脚本。",
|
||||
"Workspace files are preserved by default. Check to wipe /workspace.",
|
||||
)}
|
||||
</div>
|
||||
</Label>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => void executeRecreate()}>
|
||||
{clearWorkspace ? L("清空并重建", "Wipe & Recreate") : L("确认重建", "Recreate")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<AlertDialog open={removeOpen} onOpenChange={setRemoveOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{L("删除任务沙箱容器", "Delete Task Sandbox")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{taskRunning
|
||||
? L(
|
||||
"任务仍在运行,删除容器会同时暂停任务并移除容器(工作区文件保留,下次执行自动重建)。",
|
||||
"This task is running. Removing the container will pause the task (workspace files are preserved).",
|
||||
)
|
||||
: L(
|
||||
"确定删除该任务的沙箱容器吗?宿主机工作区文件会保留,后续执行将按需重新创建。",
|
||||
"Remove this task's sandbox container? Host workspace files will be preserved.",
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() => void executeRemove()}
|
||||
>
|
||||
{L("确认删除", "Delete")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -55,6 +55,7 @@ import { OverviewTab } from "./_tabs/overview-tab";
|
||||
import { ReportTab } from "./_tabs/report-tab";
|
||||
import { RetestsTab } from "./_tabs/retests-tab";
|
||||
import { SessionsTab } from "./_tabs/sessions-tab";
|
||||
import { TaskSandboxControl } from "./_components/task-sandbox-control";
|
||||
|
||||
const TABS = (ui: UITranslate) => [
|
||||
{ value: "sessions", label: ui("screen.a63280253f17d4") },
|
||||
@@ -498,6 +499,7 @@ function TaskDetailInner() {
|
||||
</code>
|
||||
<Separator orientation="vertical" className="mx-1 hidden h-4 sm:block" />
|
||||
<TaskLLMControl task={task} profiles={profiles} onUpdated={load} />
|
||||
<TaskSandboxControl task={task} onTaskUpdated={load} />
|
||||
<StatusBadge
|
||||
stopReason={task.stop_reason}
|
||||
domain={terminal ? "task" : "engine"}
|
||||
|
||||
@@ -0,0 +1,947 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import {
|
||||
ActivityIcon,
|
||||
BoxIcon,
|
||||
CpuIcon,
|
||||
ExternalLinkIcon,
|
||||
HardDriveIcon,
|
||||
PlayIcon,
|
||||
RefreshCwIcon,
|
||||
RotateCcwIcon,
|
||||
SearchIcon,
|
||||
Settings2Icon,
|
||||
SquareIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import type { SandboxContainerInfo, SandboxGlobalStatus } from "@/lib/types";
|
||||
|
||||
function fmtBytes(n?: number): string {
|
||||
if (!n || n <= 0) return "0 B";
|
||||
if (n >= 1 << 30) return `${(n / (1 << 30)).toFixed(2)} GiB`;
|
||||
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MiB`;
|
||||
if (n >= 1 << 10) return `${(n / (1 << 10)).toFixed(1)} KiB`;
|
||||
return `${n} B`;
|
||||
}
|
||||
|
||||
function ownerHref(c: SandboxContainerInfo): string | null {
|
||||
if (c.scope === "task" && c.owner_id) {
|
||||
return `/function/tasks/detail?id=${encodeURIComponent(c.owner_id)}`;
|
||||
}
|
||||
if (c.scope === "session" && c.owner_id) {
|
||||
const num = c.owner_id.startsWith("conv-") ? c.owner_id.slice(5) : c.owner_id;
|
||||
return num ? `/chat?c=${encodeURIComponent(num)}` : "/chat";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function fmtCreatedAt(iso?: string): string {
|
||||
if (!iso) return "-";
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return iso;
|
||||
return d.toLocaleString(undefined, {
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
export default function SandboxPage() {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const [status, setStatus] = React.useState<SandboxGlobalStatus | null>(null);
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
const [autoRefresh, setAutoRefresh] = React.useState(true);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [pruning, setPruning] = React.useState(false);
|
||||
const [busyKey, setBusyKey] = React.useState<string>("");
|
||||
|
||||
// Filters
|
||||
const [scopeFilter, setScopeFilter] = React.useState<"all" | "task" | "session">("all");
|
||||
const [stateFilter, setStateFilter] = React.useState<"all" | "running" | "stopped">("all");
|
||||
const [query, setQuery] = React.useState("");
|
||||
|
||||
// Config form state
|
||||
const [image, setImage] = React.useState("");
|
||||
const [memoryMB, setMemoryMB] = React.useState("2048");
|
||||
const [cpus, setCpus] = React.useState("2");
|
||||
const [pidsLimit, setPidsLimit] = React.useState("256");
|
||||
const [shmSizeMB, setShmSizeMB] = React.useState("512");
|
||||
const [runtime, setRuntime] = React.useState("");
|
||||
const [autoStop, setAutoStop] = React.useState(true);
|
||||
const [idleMin, setIdleMin] = React.useState("20");
|
||||
const formDirtyRef = React.useRef(false);
|
||||
|
||||
// Dialog states
|
||||
const [recreateTarget, setRecreateTarget] = React.useState<SandboxContainerInfo | null>(null);
|
||||
const [recreateClearWorkspace, setRecreateClearWorkspace] = React.useState(false);
|
||||
const [removeTarget, setRemoveTarget] = React.useState<SandboxContainerInfo | null>(null);
|
||||
const [stopTarget, setStopTarget] = React.useState<SandboxContainerInfo | null>(null);
|
||||
|
||||
const applyStatus = React.useCallback((s: SandboxGlobalStatus, forceForm = false) => {
|
||||
setStatus(s);
|
||||
if (forceForm || !formDirtyRef.current) {
|
||||
setImage(s.image || "");
|
||||
setMemoryMB(String(s.memory_mb || 2048));
|
||||
setCpus(String(s.cpus || 2));
|
||||
setPidsLimit(String(s.pids_limit || 256));
|
||||
setShmSizeMB(String(s.shm_size_mb || 512));
|
||||
setRuntime(s.runtime || "");
|
||||
setAutoStop(s.auto_stop_on_complete !== false);
|
||||
setIdleMin(String(s.session_idle_minutes || 20));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadSeqRef = React.useRef(0);
|
||||
|
||||
const load = React.useCallback(
|
||||
async (silent = false, forceForm = false, progressive = false) => {
|
||||
const seq = ++loadSeqRef.current;
|
||||
if (!silent) setLoading(true);
|
||||
try {
|
||||
// Fast path: fetch container list + cached stats immediately (~10ms) so
|
||||
// opening the page never blocks on Docker's ~1s live CPU sampling.
|
||||
const fast = await api.sandboxStatus(!progressive);
|
||||
if (seq !== loadSeqRef.current) return;
|
||||
applyStatus(fast, forceForm);
|
||||
if (!silent) setLoading(false);
|
||||
|
||||
if (progressive && fast.enabled && fast.containers.some((c) => c.state === "running")) {
|
||||
void api
|
||||
.sandboxStatus(true)
|
||||
.then((fresh) => {
|
||||
if (seq === loadSeqRef.current) {
|
||||
applyStatus(fresh, false);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// ignore transient background stats hydration errors
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (seq === loadSeqRef.current && !silent) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
} finally {
|
||||
if (seq === loadSeqRef.current && !silent) setLoading(false);
|
||||
}
|
||||
},
|
||||
[applyStatus],
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
void load(false, true, true);
|
||||
}, [load]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!autoRefresh) return;
|
||||
const timer = window.setInterval(() => {
|
||||
if (document.visibilityState === "visible") {
|
||||
void load(true, false, false);
|
||||
}
|
||||
}, 8000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [autoRefresh, load]);
|
||||
|
||||
const containers = status?.containers ?? [];
|
||||
const runningContainers = containers.filter((c) => c.state === "running");
|
||||
const stoppedContainers = containers.filter((c) => c.state !== "running");
|
||||
const totalMemUsage = runningContainers.reduce((acc, c) => acc + (c.mem_usage_bytes ?? 0), 0);
|
||||
const totalCpu = runningContainers.reduce((acc, c) => acc + (c.cpu_percent ?? 0), 0);
|
||||
const totalActiveRuns = containers.reduce((acc, c) => acc + (c.active_runs ?? 0), 0);
|
||||
|
||||
const filtered = React.useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return containers.filter((c) => {
|
||||
if (scopeFilter !== "all" && c.scope !== scopeFilter) return false;
|
||||
if (stateFilter === "running" && c.state !== "running") return false;
|
||||
if (stateFilter === "stopped" && c.state === "running") return false;
|
||||
if (q) {
|
||||
const hay =
|
||||
`${c.scope}:${c.owner_id} ${c.owner_title ?? ""} ${c.name} ${c.short_id ?? ""} ${c.image}`.toLowerCase();
|
||||
if (!hay.includes(q)) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}, [containers, scopeFilter, stateFilter, query]);
|
||||
|
||||
const containerKey = (c: SandboxContainerInfo) => `${c.scope}:${c.owner_id}`;
|
||||
|
||||
const handleStart = async (c: SandboxContainerInfo) => {
|
||||
const key = containerKey(c);
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await api.startSandboxContainer(c.scope, c.owner_id);
|
||||
toast.success(L(`容器 ${key} 已启动`, `Container ${key} started`));
|
||||
await load(true);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey("");
|
||||
}
|
||||
};
|
||||
|
||||
const executeStop = async (c: SandboxContainerInfo) => {
|
||||
const key = containerKey(c);
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await api.stopSandboxContainer(c.scope, c.owner_id);
|
||||
toast.success(L(`容器 ${key} 已停止(内存已释放)`, `Container ${key} stopped`));
|
||||
await load(true);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleStopClick = (c: SandboxContainerInfo) => {
|
||||
if (c.task_running) {
|
||||
setStopTarget(c);
|
||||
} else {
|
||||
void executeStop(c);
|
||||
}
|
||||
};
|
||||
|
||||
const executeRecreate = async () => {
|
||||
if (!recreateTarget) return;
|
||||
const c = recreateTarget;
|
||||
const clearWs = recreateClearWorkspace;
|
||||
setRecreateTarget(null);
|
||||
setRecreateClearWorkspace(false);
|
||||
const key = containerKey(c);
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await api.recreateSandboxContainer(c.scope, c.owner_id, {
|
||||
pause_task: Boolean(c.task_running),
|
||||
clear_workspace: clearWs,
|
||||
});
|
||||
toast.success(
|
||||
clearWs
|
||||
? L(`容器 ${key} 已重建并清空工作区`, `Container ${key} recreated with clean workspace`)
|
||||
: L(`容器 ${key} 已重建(工作区文件已保留)`, `Container ${key} recreated`),
|
||||
);
|
||||
await load(true);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey("");
|
||||
}
|
||||
};
|
||||
|
||||
const executeRemove = async () => {
|
||||
if (!removeTarget) return;
|
||||
const c = removeTarget;
|
||||
setRemoveTarget(null);
|
||||
const key = containerKey(c);
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await api.removeSandboxContainer(c.scope, c.owner_id);
|
||||
toast.success(L(`容器 ${key} 已删除`, `Container ${key} removed`));
|
||||
await load(true);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey("");
|
||||
}
|
||||
};
|
||||
|
||||
const handlePrune = async () => {
|
||||
setPruning(true);
|
||||
try {
|
||||
const r = await api.pruneSandboxContainers();
|
||||
toast.success(L(`已清理 ${r.removed} 个已停止的沙箱容器`, `Removed ${r.removed} stopped sandbox container(s)`));
|
||||
await load(true);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setPruning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveSettings = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const updated = await api.updateSandboxSettings({
|
||||
image: image.trim(),
|
||||
memory_mb: Number(memoryMB) || 2048,
|
||||
cpus: Number(cpus) || 2,
|
||||
pids_limit: Number(pidsLimit) || 256,
|
||||
shm_size_mb: Number(shmSizeMB) || 512,
|
||||
runtime: runtime.trim(),
|
||||
auto_stop_on_complete: autoStop,
|
||||
session_idle_minutes: Number(idleMin) || 20,
|
||||
});
|
||||
formDirtyRef.current = false;
|
||||
applyStatus(updated, true);
|
||||
toast.success(L("沙箱配置已保存(新创建或重建的容器生效)", "Sandbox settings saved"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const scopeBadge = (scope: string) => {
|
||||
if (scope === "task") return <Badge variant="outline">{L("任务", "Task")}</Badge>;
|
||||
if (scope === "session") return <Badge variant="secondary">{L("对话", "Chat")}</Badge>;
|
||||
return <Badge variant="secondary">{scope}</Badge>;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-w-0 w-full flex-1 flex-col gap-4 md:gap-6">
|
||||
{/* Header */}
|
||||
<div className="flex min-w-0 flex-wrap items-start justify-between gap-3">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h1 className="flex items-center gap-2 font-semibold text-xl tracking-tight">
|
||||
<BoxIcon className="size-5" />
|
||||
{L("沙箱容器", "Sandbox Containers")}
|
||||
</h1>
|
||||
{status ? (
|
||||
<Badge variant={status.enabled ? (status.available ? "default" : "destructive") : "secondary"}>
|
||||
{status.enabled
|
||||
? status.available
|
||||
? `Docker · ${status.runtime || "runc"}`
|
||||
: L("Docker 不可用", "Docker Unavailable")
|
||||
: L("本地模式", "Local Mode")}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">{L("加载中…", "Loading…")}</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{!status
|
||||
? L("正在读取沙箱运行状态与托管容器…", "Loading sandbox status and managed containers…")
|
||||
: status.enabled
|
||||
? L(
|
||||
`统一管理所有任务与对话的隔离容器生命周期与资源占用(隔离网络:${status.network},已禁用容器间互通)。`,
|
||||
`Manage lifecycle and resource usage for isolated task and chat containers (network: ${status.network}, ICC disabled).`,
|
||||
)
|
||||
: L(
|
||||
"当前为本地执行模式。部署时配置 ARTEX_SANDBOX_MODE=docker 即可启用任务与对话级容器隔离。",
|
||||
"Running in local execution mode. Set ARTEX_SANDBOX_MODE=docker to enable container isolation.",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{status?.enabled ? (
|
||||
<>
|
||||
<div className="flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs">
|
||||
<Switch id="sandbox-auto-refresh" checked={autoRefresh} onCheckedChange={setAutoRefresh} />
|
||||
<Label
|
||||
htmlFor="sandbox-auto-refresh"
|
||||
className="cursor-pointer font-normal text-muted-foreground text-xs"
|
||||
>
|
||||
{L("自动刷新", "Auto-refresh")}
|
||||
</Label>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={pruning || stoppedContainers.length === 0}
|
||||
onClick={() => void handlePrune()}
|
||||
>
|
||||
<Trash2Icon className="mr-1.5 size-3.5" />
|
||||
{pruning
|
||||
? L("清理中…", "Pruning…")
|
||||
: L(`清理已停止 (${stoppedContainers.length})`, `Prune Stopped (${stoppedContainers.length})`)}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
<Button size="sm" variant="outline" disabled={loading} onClick={() => void load(false, false, true)}>
|
||||
<RefreshCwIcon className={`mr-1.5 size-3.5 ${loading ? "animate-spin" : ""}`} />
|
||||
{L("刷新", "Refresh")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{status?.error ? (
|
||||
<div className="rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">
|
||||
{status.error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Summary KPI cards */}
|
||||
{status?.enabled ? (
|
||||
<div className="grid min-w-0 grid-cols-2 gap-3 lg:grid-cols-4">
|
||||
<Card className="min-w-0">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription className="flex items-center gap-1.5 text-xs">
|
||||
<ActivityIcon className="size-3.5 shrink-0 text-emerald-500" />
|
||||
<span className="truncate">{L("运行中容器", "Running Containers")}</span>
|
||||
</CardDescription>
|
||||
<CardTitle className="text-2xl tabular-nums">
|
||||
{runningContainers.length}
|
||||
<span className="ml-1.5 font-normal text-muted-foreground text-sm">/ {containers.length}</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
<Card className="min-w-0">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription className="flex items-center gap-1.5 text-xs">
|
||||
<SquareIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="truncate">{L("已停止(内存已释放)", "Stopped (Memory Freed)")}</span>
|
||||
</CardDescription>
|
||||
<CardTitle className="text-2xl tabular-nums">{stoppedContainers.length}</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
<Card className="min-w-0">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription className="flex items-center gap-1.5 text-xs">
|
||||
<HardDriveIcon className="size-3.5 shrink-0 text-blue-500" />
|
||||
<span className="truncate">{L("运行容器总内存", "Active Memory Usage")}</span>
|
||||
</CardDescription>
|
||||
<CardTitle className="text-2xl tabular-nums">{fmtBytes(totalMemUsage)}</CardTitle>
|
||||
<div className="truncate text-[11px] text-muted-foreground">
|
||||
{L(`单容器上限 ${status.memory_mb} MiB`, `Cap ${status.memory_mb} MiB / container`)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
<Card className="min-w-0">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription className="flex items-center gap-1.5 text-xs">
|
||||
<CpuIcon className="size-3.5 shrink-0 text-amber-500" />
|
||||
<span className="truncate">{L("总 CPU / 活跃执行", "Total CPU / Active Runs")}</span>
|
||||
</CardDescription>
|
||||
<CardTitle className="text-2xl tabular-nums">{totalCpu.toFixed(1)}%</CardTitle>
|
||||
<div className="truncate text-[11px] text-muted-foreground">
|
||||
{L(`活跃执行 ${totalActiveRuns}`, `${totalActiveRuns} active run(s)`)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{status?.enabled ? (
|
||||
<Tabs defaultValue="containers" className="min-w-0 w-full space-y-4">
|
||||
<TabsList>
|
||||
<TabsTrigger value="containers" className="gap-1.5">
|
||||
<BoxIcon className="size-3.5" />
|
||||
{L(`托管容器 (${containers.length})`, `Containers (${containers.length})`)}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="settings" className="gap-1.5">
|
||||
<Settings2Icon className="size-3.5" />
|
||||
{L("全局配额与策略", "Limits & Policy")}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Tab 1: Container Lifecycle Management */}
|
||||
<TabsContent value="containers" className="min-w-0 space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="relative min-w-[220px] flex-1">
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={L(
|
||||
"搜索任务名、归属 ID、容器 ID 或镜像…",
|
||||
"Search task title, owner ID, container ID, or image…",
|
||||
)}
|
||||
className="h-8 pl-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<Select value={scopeFilter} onValueChange={(v) => setScopeFilter(v as "all" | "task" | "session")}>
|
||||
<SelectTrigger className="h-8 w-32 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{L("全部类型", "All Scopes")}</SelectItem>
|
||||
<SelectItem value="task">{L("仅任务容器", "Tasks Only")}</SelectItem>
|
||||
<SelectItem value="session">{L("仅对话容器", "Chats Only")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={stateFilter} onValueChange={(v) => setStateFilter(v as "all" | "running" | "stopped")}>
|
||||
<SelectTrigger className="h-8 w-32 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{L("全部状态", "All States")}</SelectItem>
|
||||
<SelectItem value="running">{L("运行中", "Running")}</SelectItem>
|
||||
<SelectItem value="stopped">{L("已停止", "Stopped")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 w-full overflow-x-auto rounded-lg border bg-card">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{L("归属与容器", "Owner & Container")}</TableHead>
|
||||
<TableHead>{L("状态与时长", "State & Uptime")}</TableHead>
|
||||
<TableHead className="min-w-[160px]">{L("实时资源", "Resources")}</TableHead>
|
||||
<TableHead>{L("镜像与创建时间", "Image & Created")}</TableHead>
|
||||
<TableHead className="text-right">{L("生命周期操作", "Lifecycle")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{filtered.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="py-10 text-center text-sm text-muted-foreground">
|
||||
{containers.length === 0
|
||||
? L(
|
||||
"暂无沙箱容器(任务或对话执行命令/脚本/浏览器时会自动按需创建)",
|
||||
"No sandbox containers yet (created on demand when tasks or chats execute tools)",
|
||||
)
|
||||
: L("没有符合当前筛选条件的容器", "No containers match the current filter")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
filtered.map((c) => {
|
||||
const running = c.state === "running";
|
||||
const key = containerKey(c);
|
||||
const isBusy = busyKey === key;
|
||||
const href = ownerHref(c);
|
||||
const memLimit = c.mem_limit_bytes || (status.memory_mb ? status.memory_mb * 1024 * 1024 : 0);
|
||||
const memPct =
|
||||
running && memLimit > 0
|
||||
? Math.min(100, Math.round(((c.mem_usage_bytes ?? 0) / memLimit) * 100))
|
||||
: 0;
|
||||
return (
|
||||
<TableRow key={c.container_id || c.name}>
|
||||
<TableCell>
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{scopeBadge(c.scope)}
|
||||
{href ? (
|
||||
<Link
|
||||
href={href}
|
||||
className="inline-flex items-center gap-1 font-mono text-xs font-medium hover:underline"
|
||||
>
|
||||
{c.scope === "task" ? `#${c.owner_id}` : c.owner_id}
|
||||
<ExternalLinkIcon className="size-3 text-muted-foreground" />
|
||||
</Link>
|
||||
) : (
|
||||
<span className="font-mono text-xs font-medium">{c.owner_id}</span>
|
||||
)}
|
||||
{c.task_running ? (
|
||||
<Badge variant="default" className="h-4 px-1.5 text-[10px]">
|
||||
{L("任务运行中", "Task Active")}
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
{c.owner_title ? (
|
||||
<div
|
||||
className="max-w-[200px] truncate text-xs text-muted-foreground"
|
||||
title={c.owner_title}
|
||||
>
|
||||
{c.owner_title}
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
className="max-w-[200px] truncate font-mono text-[11px] text-muted-foreground"
|
||||
title={c.name}
|
||||
>
|
||||
{c.short_id || "-"} · {c.name}
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
|
||||
<TableCell>
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span
|
||||
className={`size-2 rounded-full ${
|
||||
running
|
||||
? "bg-emerald-500"
|
||||
: c.state === "error"
|
||||
? "bg-red-500"
|
||||
: "bg-muted-foreground/50"
|
||||
}`}
|
||||
/>
|
||||
<Badge variant={running ? "default" : "secondary"} className="text-[11px]">
|
||||
{running ? L("运行中", "running") : c.state}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-[11px] text-muted-foreground">{c.status_text || c.state}</div>
|
||||
<div className="font-mono text-[11px] text-muted-foreground">
|
||||
{L("活跃执行", "active")}={c.active_runs}
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
|
||||
<TableCell>
|
||||
{running ? (
|
||||
<div className="space-y-1.5 font-mono text-[11px]">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-muted-foreground">CPU</span>
|
||||
<span>{(c.cpu_percent ?? 0).toFixed(1)}%</span>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-muted-foreground">MEM</span>
|
||||
<span>
|
||||
{fmtBytes(c.mem_usage_bytes)} / {fmtBytes(memLimit)}
|
||||
</span>
|
||||
</div>
|
||||
<Progress value={memPct} className="h-1.5" />
|
||||
</div>
|
||||
{c.pids_current != null ? (
|
||||
<div className="flex items-center justify-between gap-2 text-muted-foreground">
|
||||
<span>PIDs</span>
|
||||
<span>
|
||||
{c.pids_current} / {status.pids_limit}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{L("已释放(容器未运行)", "Freed (stopped)")}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
|
||||
<TableCell>
|
||||
<div className="space-y-1 font-mono text-[11px]">
|
||||
<div className="max-w-[180px] truncate" title={c.image}>
|
||||
{c.image}
|
||||
</div>
|
||||
<div className="text-muted-foreground">{fmtCreatedAt(c.created_at)}</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="text-right">
|
||||
<div className="flex flex-wrap items-center justify-end gap-1.5">
|
||||
{!running ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
className="h-7 gap-1 px-2.5 text-xs"
|
||||
disabled={isBusy}
|
||||
onClick={() => void handleStart(c)}
|
||||
>
|
||||
<PlayIcon className="size-3" />
|
||||
{L("启动", "Start")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 gap-1 px-2.5 text-xs"
|
||||
disabled={isBusy}
|
||||
onClick={() => handleStopClick(c)}
|
||||
>
|
||||
<SquareIcon className="size-3" />
|
||||
{L("停止", "Stop")}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 gap-1 px-2.5 text-xs"
|
||||
disabled={isBusy}
|
||||
onClick={() => {
|
||||
setRecreateClearWorkspace(false);
|
||||
setRecreateTarget(c);
|
||||
}}
|
||||
>
|
||||
<RotateCcwIcon className="size-3" />
|
||||
{L("重建", "Recreate")}
|
||||
</Button>
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="h-7 w-7 text-destructive hover:text-destructive"
|
||||
disabled={isBusy}
|
||||
onClick={() => setRemoveTarget(c)}
|
||||
title={L("删除容器", "Delete container")}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
{/* Tab 2: Global Sandbox Settings */}
|
||||
<TabsContent value="settings">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">
|
||||
{L("默认镜像、资源配额与自动停机策略", "Default Image, Limits & Auto-Stop Policy")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{L(
|
||||
"保存后会持久化到数据库,并对新创建或手动「重建」的容器生效。",
|
||||
"Persisted to the database and applied to newly created or recreated containers.",
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{L("沙箱工具镜像", "Sandbox Image")}</Label>
|
||||
<Input
|
||||
value={image}
|
||||
onChange={(e) => {
|
||||
formDirtyRef.current = true;
|
||||
setImage(e.target.value);
|
||||
}}
|
||||
placeholder="ruoji6/artex-sandbox:latest"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{L("单容器内存上限 (MiB)", "Memory Limit (MiB)")}</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={256}
|
||||
value={memoryMB}
|
||||
onChange={(e) => {
|
||||
formDirtyRef.current = true;
|
||||
setMemoryMB(e.target.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{L("单容器 CPU 核数", "CPU Cores")}</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.5"
|
||||
min={0.25}
|
||||
value={cpus}
|
||||
onChange={(e) => {
|
||||
formDirtyRef.current = true;
|
||||
setCpus(e.target.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{L("进程数上限 (PIDs)", "PIDs Limit")}</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={32}
|
||||
value={pidsLimit}
|
||||
onChange={(e) => {
|
||||
formDirtyRef.current = true;
|
||||
setPidsLimit(e.target.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{L("共享内存 /dev/shm (MiB)", "Shared Memory (MiB)")}</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={64}
|
||||
value={shmSizeMB}
|
||||
onChange={(e) => {
|
||||
formDirtyRef.current = true;
|
||||
setShmSizeMB(e.target.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">
|
||||
{L("容器运行时(留空默认 runc / 可填 runsc)", "Runtime (blank=runc, or runsc)")}
|
||||
</Label>
|
||||
<Input
|
||||
value={runtime}
|
||||
onChange={(e) => {
|
||||
formDirtyRef.current = true;
|
||||
setRuntime(e.target.value);
|
||||
}}
|
||||
placeholder="runc / runsc"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 rounded-md border bg-muted/30 px-3 py-2.5">
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
checked={autoStop}
|
||||
onCheckedChange={(v) => {
|
||||
formDirtyRef.current = true;
|
||||
setAutoStop(v);
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<div className="text-xs font-medium">
|
||||
{L("任务结束或暂停后自动停止容器", "Auto-stop container on task finish or pause")}
|
||||
</div>
|
||||
<div className="text-[11px] text-muted-foreground">
|
||||
{L(
|
||||
"释放内存与 CPU,工作区文件保留,恢复任务时自动秒级重启。",
|
||||
"Frees RAM and CPU while keeping workspace files for fast resume.",
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="text-xs text-muted-foreground">
|
||||
{L("对话空闲停机(分钟)", "Chat idle stop (min)")}
|
||||
</Label>
|
||||
<Input
|
||||
className="h-8 w-20"
|
||||
type="number"
|
||||
min={1}
|
||||
value={idleMin}
|
||||
onChange={(e) => {
|
||||
formDirtyRef.current = true;
|
||||
setIdleMin(e.target.value);
|
||||
}}
|
||||
/>
|
||||
<Button size="sm" disabled={saving} onClick={() => void handleSaveSettings()}>
|
||||
{saving ? L("保存中…", "Saving…") : L("保存配置", "Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
) : null}
|
||||
|
||||
{/* Stop Running Task Container Dialog */}
|
||||
<AlertDialog open={Boolean(stopTarget)} onOpenChange={(o) => !o && setStopTarget(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{L("确认停止正在运行任务的沙箱容器?", "Stop container for a running task?")}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{stopTarget
|
||||
? L(
|
||||
`任务 #${stopTarget.owner_id} 当前正在运行,停止容器 ${stopTarget.short_id || stopTarget.name} 会同时暂停该任务。工作区文件会保留。`,
|
||||
`Task #${stopTarget.owner_id} is currently running. Stopping container ${stopTarget.short_id || stopTarget.name} will pause the task. Workspace files will be kept.`,
|
||||
)
|
||||
: null}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => {
|
||||
if (stopTarget) {
|
||||
const target = stopTarget;
|
||||
setStopTarget(null);
|
||||
void executeStop(target);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{L("暂停任务并停止容器", "Pause Task & Stop")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Recreate Container Dialog */}
|
||||
<AlertDialog open={Boolean(recreateTarget)} onOpenChange={(o) => !o && setRecreateTarget(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{L("重建沙箱容器", "Recreate Sandbox Container")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{recreateTarget
|
||||
? recreateTarget.task_running
|
||||
? L(
|
||||
`将暂停任务 #${recreateTarget.owner_id},销毁旧容器并按最新镜像和配额重新创建。`,
|
||||
`This will pause task #${recreateTarget.owner_id}, destroy the old container, and create a fresh one with the latest image and limits.`,
|
||||
)
|
||||
: L(
|
||||
`将销毁容器 ${recreateTarget.scope}:${recreateTarget.owner_id} 并按最新镜像和配额重新创建启动。`,
|
||||
`This will destroy container ${recreateTarget.scope}:${recreateTarget.owner_id} and start a fresh one with the latest image and limits.`,
|
||||
)
|
||||
: null}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="flex items-start gap-2.5 rounded-md border bg-muted/30 p-3 text-xs">
|
||||
<Checkbox
|
||||
id="sandbox-recreate-wipe"
|
||||
checked={recreateClearWorkspace}
|
||||
onCheckedChange={(v) => setRecreateClearWorkspace(Boolean(v))}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<Label htmlFor="sandbox-recreate-wipe" className="block cursor-pointer space-y-0.5 font-normal">
|
||||
<div className="font-medium text-foreground">
|
||||
{L("同时清空工作区文件 (/workspace)", "Also clear workspace files (/workspace)")}
|
||||
</div>
|
||||
<div className="text-muted-foreground">
|
||||
{L(
|
||||
"默认保留工作区脚本、截图和附件;如怀疑环境被污染可勾选彻底清空。",
|
||||
"Workspace files are kept by default. Check this to wipe all files inside /workspace.",
|
||||
)}
|
||||
</div>
|
||||
</Label>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => void executeRecreate()}>
|
||||
{recreateClearWorkspace ? L("清空并重建", "Wipe & Recreate") : L("确认重建", "Recreate")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Delete Container Dialog */}
|
||||
<AlertDialog open={Boolean(removeTarget)} onOpenChange={(o) => !o && setRemoveTarget(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{L("删除沙箱容器", "Delete Sandbox Container")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{removeTarget
|
||||
? removeTarget.task_running
|
||||
? L(
|
||||
`任务 #${removeTarget.owner_id} 正在运行,删除容器会同时暂停该任务并销毁容器层(宿主机工作区目录保留,下次执行时将自动新建容器)。`,
|
||||
`Task #${removeTarget.owner_id} is running. Deleting will pause the task and remove the container (host workspace files are preserved).`,
|
||||
)
|
||||
: L(
|
||||
`确定彻底删除容器 ${removeTarget.scope}:${removeTarget.owner_id}(${removeTarget.short_id || removeTarget.name})吗?宿主机工作区文件会保留,后续执行将按需重新创建。`,
|
||||
`Remove container ${removeTarget.scope}:${removeTarget.owner_id} (${removeTarget.short_id || removeTarget.name})? Host workspace files are preserved.`,
|
||||
)
|
||||
: null}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() => void executeRemove()}
|
||||
>
|
||||
{L("确认删除", "Delete")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import {
|
||||
BoxIcon,
|
||||
ExternalLinkIcon,
|
||||
PlayIcon,
|
||||
RefreshCwIcon,
|
||||
RotateCcwIcon,
|
||||
SquareIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import type { SandboxContainerInfo, SandboxGlobalStatus } from "@/lib/types";
|
||||
|
||||
function fmtBytes(n?: number): string {
|
||||
if (!n || n <= 0) return "0 B";
|
||||
if (n >= 1 << 30) return `${(n / (1 << 30)).toFixed(2)} GiB`;
|
||||
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MiB`;
|
||||
if (n >= 1 << 10) return `${(n / (1 << 10)).toFixed(1)} KiB`;
|
||||
return `${n} B`;
|
||||
}
|
||||
|
||||
function ownerHref(c: SandboxContainerInfo): string | null {
|
||||
if (c.scope === "task" && c.owner_id) {
|
||||
return `/function/tasks/detail?id=${encodeURIComponent(c.owner_id)}`;
|
||||
}
|
||||
if (c.scope === "session" && c.owner_id) {
|
||||
const num = c.owner_id.startsWith("conv-") ? c.owner_id.slice(5) : c.owner_id;
|
||||
return num ? `/chat?c=${encodeURIComponent(num)}` : "/chat";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function SandboxCard() {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const [status, setStatus] = React.useState<SandboxGlobalStatus | null>(null);
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [pruning, setPruning] = React.useState(false);
|
||||
const [busyKey, setBusyKey] = React.useState("");
|
||||
|
||||
const [image, setImage] = React.useState("");
|
||||
const [memoryMB, setMemoryMB] = React.useState("2048");
|
||||
const [cpus, setCpus] = React.useState("2");
|
||||
const [pidsLimit, setPidsLimit] = React.useState("256");
|
||||
const [shmSizeMB, setShmSizeMB] = React.useState("512");
|
||||
const [runtime, setRuntime] = React.useState("");
|
||||
const [autoStop, setAutoStop] = React.useState(true);
|
||||
const [idleMin, setIdleMin] = React.useState("20");
|
||||
|
||||
const applyStatus = React.useCallback((s: SandboxGlobalStatus) => {
|
||||
setStatus(s);
|
||||
setImage(s.image || "");
|
||||
setMemoryMB(String(s.memory_mb || 2048));
|
||||
setCpus(String(s.cpus || 2));
|
||||
setPidsLimit(String(s.pids_limit || 256));
|
||||
setShmSizeMB(String(s.shm_size_mb || 512));
|
||||
setRuntime(s.runtime || "");
|
||||
setAutoStop(s.auto_stop_on_complete !== false);
|
||||
setIdleMin(String(s.session_idle_minutes || 20));
|
||||
}, []);
|
||||
|
||||
const load = React.useCallback(
|
||||
async (progressive = false) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const s = await api.sandboxStatus(!progressive);
|
||||
applyStatus(s);
|
||||
if (progressive && s.enabled && s.containers.some((c) => c.state === "running")) {
|
||||
void api
|
||||
.sandboxStatus(true)
|
||||
.then(applyStatus)
|
||||
.catch(() => {
|
||||
// ignore transient background stats hydration errors
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// keep silent on initial load failure in mock/offline environments
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[applyStatus],
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
void load(true);
|
||||
}, [load]);
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const updated = await api.updateSandboxSettings({
|
||||
image: image.trim(),
|
||||
memory_mb: Number(memoryMB) || 2048,
|
||||
cpus: Number(cpus) || 2,
|
||||
pids_limit: Number(pidsLimit) || 256,
|
||||
shm_size_mb: Number(shmSizeMB) || 512,
|
||||
runtime: runtime.trim(),
|
||||
auto_stop_on_complete: autoStop,
|
||||
session_idle_minutes: Number(idleMin) || 20,
|
||||
});
|
||||
applyStatus(updated);
|
||||
toast.success(L("沙箱配置已保存(新创建或重建的容器生效)", "Sandbox settings saved"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePrune = async () => {
|
||||
setPruning(true);
|
||||
try {
|
||||
const r = await api.pruneSandboxContainers();
|
||||
toast.success(L(`已清理 ${r.removed} 个已停止的沙箱容器`, `Removed ${r.removed} stopped sandbox container(s)`));
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setPruning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStartOne = async (scope: string, ownerID: string) => {
|
||||
const key = `${scope}:${ownerID}`;
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await api.startSandboxContainer(scope, ownerID);
|
||||
toast.success(L("容器已启动", "Container started"));
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleStopOne = async (scope: string, ownerID: string) => {
|
||||
const key = `${scope}:${ownerID}`;
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await api.stopSandboxContainer(scope, ownerID);
|
||||
toast.success(L("容器已停止", "Container stopped"));
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleRecreateOne = async (c: SandboxContainerInfo) => {
|
||||
const key = `${c.scope}:${c.owner_id}`;
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await api.recreateSandboxContainer(c.scope, c.owner_id, { pause_task: Boolean(c.task_running) });
|
||||
toast.success(L("容器已重建(工作区文件已保留)", "Container recreated"));
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveOne = async (scope: string, ownerID: string) => {
|
||||
const key = `${scope}:${ownerID}`;
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await api.removeSandboxContainer(scope, ownerID);
|
||||
toast.success(L("容器已移除", "Container removed"));
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey("");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<BoxIcon className="size-4" />
|
||||
{L("沙箱容器隔离", "Sandbox Container Isolation")}
|
||||
<Badge variant={status?.enabled ? "default" : "secondary"}>
|
||||
{status?.enabled ? "Docker" : L("本地模式", "Local")}
|
||||
</Badge>
|
||||
</CardTitle>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button size="sm" variant="outline" asChild>
|
||||
<Link href="/system/sandbox" className="gap-1">
|
||||
{L("容器管理页", "Manage Containers")}
|
||||
<ExternalLinkIcon className="size-3.5" />
|
||||
</Link>
|
||||
</Button>
|
||||
{status?.enabled ? (
|
||||
<Button size="sm" variant="outline" disabled={pruning} onClick={() => void handlePrune()}>
|
||||
<Trash2Icon className="mr-1 size-3.5" />
|
||||
{L("清理闲置容器", "Prune Stopped")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
disabled={loading}
|
||||
onClick={() => void load()}
|
||||
title={L("刷新", "Refresh")}
|
||||
>
|
||||
<RefreshCwIcon className={`size-4 ${loading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<CardDescription>
|
||||
{status?.enabled
|
||||
? L(
|
||||
`已启用 Docker 容器隔离(网络:${status.network},关闭容器间互通)。每个任务和对话在独立非 root 容器内执行命令、脚本与浏览器。`,
|
||||
`Docker sandbox isolation is active (network: ${status.network}, ICC disabled). Tasks and chat sessions execute tools in isolated non-root containers.`,
|
||||
)
|
||||
: L(
|
||||
"当前为本地执行模式。部署时设置 ARTEX_SANDBOX_MODE=docker 即可启用任务级容器隔离。",
|
||||
"Running in local mode. Set ARTEX_SANDBOX_MODE=docker on deployment to enable per-task container isolation.",
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4">
|
||||
{status?.error ? (
|
||||
<div className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">
|
||||
{status.error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{status?.enabled ? (
|
||||
<>
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{L("沙箱工具镜像", "Sandbox Image")}</Label>
|
||||
<Input
|
||||
value={image}
|
||||
onChange={(e) => setImage(e.target.value)}
|
||||
placeholder="ruoji6/artex-sandbox:latest"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{L("单容器内存上限 (MiB)", "Memory Limit (MiB)")}</Label>
|
||||
<Input type="number" min={256} value={memoryMB} onChange={(e) => setMemoryMB(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{L("单容器 CPU 核数", "CPU Cores")}</Label>
|
||||
<Input type="number" step="0.5" min={0.25} value={cpus} onChange={(e) => setCpus(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{L("进程数上限 (PIDs)", "PIDs Limit")}</Label>
|
||||
<Input type="number" min={32} value={pidsLimit} onChange={(e) => setPidsLimit(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{L("共享内存 /dev/shm (MiB)", "Shared Memory (MiB)")}</Label>
|
||||
<Input type="number" min={64} value={shmSizeMB} onChange={(e) => setShmSizeMB(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">
|
||||
{L("容器运行时(留空默认 runc / 可填 runsc)", "Runtime (blank=runc, or runsc)")}
|
||||
</Label>
|
||||
<Input value={runtime} onChange={(e) => setRuntime(e.target.value)} placeholder="runc / runsc" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 rounded-md border bg-muted/30 px-3 py-2.5">
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch checked={autoStop} onCheckedChange={setAutoStop} />
|
||||
<div>
|
||||
<div className="text-xs font-medium">
|
||||
{L("任务结束或暂停后自动停止容器", "Auto-stop container on task finish or pause")}
|
||||
</div>
|
||||
<div className="text-[11px] text-muted-foreground">
|
||||
{L(
|
||||
"释放内存与 CPU,工作区文件保留,恢复任务时自动秒级重启。",
|
||||
"Frees RAM and CPU while keeping workspace files for fast resume.",
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="text-xs text-muted-foreground">
|
||||
{L("对话空闲停机(分钟)", "Chat idle stop (min)")}
|
||||
</Label>
|
||||
<Input
|
||||
className="h-8 w-20"
|
||||
type="number"
|
||||
min={1}
|
||||
value={idleMin}
|
||||
onChange={(e) => setIdleMin(e.target.value)}
|
||||
/>
|
||||
<Button size="sm" disabled={saving} onClick={() => void handleSave()}>
|
||||
{saving ? L("保存中…", "Saving…") : L("保存配置", "Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground">
|
||||
{L(`当前托管容器 (${status.containers.length})`, `Managed Containers (${status.containers.length})`)}
|
||||
</div>
|
||||
{status.containers.length === 0 ? (
|
||||
<div className="rounded-md border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
|
||||
{L(
|
||||
"暂无沙箱容器(任务或对话执行工具时将自动按需创建)",
|
||||
"No sandbox containers yet (created on demand when tasks or chats run tools)",
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y rounded-md border">
|
||||
{status.containers.map((c) => {
|
||||
const key = `${c.scope}:${c.owner_id}`;
|
||||
const isBusy = busyKey === key;
|
||||
const href = ownerHref(c);
|
||||
return (
|
||||
<div
|
||||
key={c.container_id || c.name}
|
||||
className="flex flex-wrap items-center justify-between gap-2 px-3 py-2 text-xs"
|
||||
>
|
||||
<div className="min-w-0 flex-1 space-y-0.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={c.state === "running" ? "default" : "secondary"}>{c.state}</Badge>
|
||||
{href ? (
|
||||
<Link
|
||||
href={href}
|
||||
className="inline-flex items-center gap-1 font-mono font-medium hover:underline"
|
||||
>
|
||||
{c.scope}:{c.owner_id}
|
||||
<ExternalLinkIcon className="size-3 text-muted-foreground" />
|
||||
</Link>
|
||||
) : (
|
||||
<span className="font-mono font-medium">
|
||||
{c.scope}:{c.owner_id}
|
||||
</span>
|
||||
)}
|
||||
<span className="font-mono text-[11px] text-muted-foreground">{c.short_id}</span>
|
||||
</div>
|
||||
<div className="truncate font-mono text-[11px] text-muted-foreground">
|
||||
{c.image} · {c.status_text || c.state}
|
||||
{c.state === "running"
|
||||
? ` · CPU ${(c.cpu_percent ?? 0).toFixed(1)}% · MEM ${fmtBytes(c.mem_usage_bytes)}`
|
||||
: ""}
|
||||
{` · active=${c.active_runs}`}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{c.state === "running" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 gap-1 text-xs"
|
||||
disabled={isBusy}
|
||||
onClick={() => void handleStopOne(c.scope, c.owner_id)}
|
||||
>
|
||||
<SquareIcon className="size-3" />
|
||||
{L("停止", "Stop")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
className="h-7 gap-1 text-xs"
|
||||
disabled={isBusy}
|
||||
onClick={() => void handleStartOne(c.scope, c.owner_id)}
|
||||
>
|
||||
<PlayIcon className="size-3" />
|
||||
{L("启动", "Start")}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 gap-1 text-xs"
|
||||
disabled={isBusy}
|
||||
onClick={() => void handleRecreateOne(c)}
|
||||
>
|
||||
<RotateCcwIcon className="size-3" />
|
||||
{L("重建", "Recreate")}
|
||||
</Button>
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="h-7 w-7 text-destructive"
|
||||
disabled={isBusy}
|
||||
onClick={() => void handleRemoveOne(c.scope, c.owner_id)}
|
||||
title={L("删除容器", "Remove container")}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -33,8 +33,8 @@ import { useEgressIp } from "../../_components/egress-ip-banner";
|
||||
import { BackupCard } from "./_components/backup-card";
|
||||
import { BasicAuthCard } from "./_components/basic-auth-card";
|
||||
import { McpServerCard } from "./_components/mcp-server-card";
|
||||
import { SandboxCard } from "./_components/sandbox-card";
|
||||
import { UpdateCard } from "./_components/update-card";
|
||||
|
||||
export default function SystemSettingsPage() {
|
||||
const { t, liveT, i18n } = useLiveTranslation();
|
||||
const [credentialAgent, setCredentialAgent] = React.useState(false);
|
||||
@@ -770,7 +770,7 @@ export default function SystemSettingsPage() {
|
||||
{isSettingVisible("system", "settings.keywords.backup") ? <BackupCard /> : null}
|
||||
{isSettingVisible("system", "settings.keywords.basicAuth") ? <BasicAuthCard /> : null}
|
||||
{isSettingVisible("system", "settings.keywords.mcpServer") ? <McpServerCard /> : null}
|
||||
|
||||
{isSettingVisible("system", "settings.keywords.sandbox") ? <SandboxCard /> : null}
|
||||
<Card
|
||||
className={`${isSettingVisible("traffic", "settings.keywords.trafficCapture") ? "" : "hidden"} mb-4 break-inside-avoid md:mb-6`}
|
||||
>
|
||||
|
||||
@@ -62,6 +62,7 @@ export const messages = {
|
||||
"nav.intercept": ["拦截规则", "Interception rules"],
|
||||
"nav.asset-intercept": ["资产拦截", "Asset interception"],
|
||||
"nav.approvals": ["审批记录", "Approval history"],
|
||||
"nav.sandbox": ["沙箱容器", "Sandbox"],
|
||||
"nav.logs": ["日志", "Logs"],
|
||||
"nav.settings": ["系统配置", "Settings"],
|
||||
"search.placeholder": ["搜索页面与功能…", "Search pages and features…"],
|
||||
|
||||
@@ -164,6 +164,10 @@ export const settingsMessages = {
|
||||
"MCP 服务端 访问令牌 token 智能体 编排 外部 bot 审计 白名单 来源 IP",
|
||||
"mcp server access token agent orchestration external bot audit allowlist whitelist source ip",
|
||||
],
|
||||
"settings.keywords.sandbox": [
|
||||
"沙箱 容器 隔离 docker 镜像 内存 cpu 进程 生命周期 停机 清理",
|
||||
"sandbox container isolation docker image memory cpu pids lifecycle stop prune",
|
||||
],
|
||||
"settings.trafficCapture": ["流量捕获", "Traffic capture"],
|
||||
"settings.trafficCaptureHelp": [
|
||||
"开启后,所有 Agent 的 HTTP 流量经记录代理全量落库,并向 Agent 注入 traffic_search / traffic_get 工具与代理配置(提示词含代理说明)。",
|
||||
|
||||
@@ -118,6 +118,9 @@ import type {
|
||||
TrafficResp,
|
||||
UpdateCheck,
|
||||
UpdateSettings,
|
||||
SandboxContainerInfo,
|
||||
SandboxGlobalStatus,
|
||||
SandboxRuntimeOverrides,
|
||||
UsageStats,
|
||||
WorkspaceFile,
|
||||
WorkspaceListing,
|
||||
@@ -1813,4 +1816,37 @@ export const api = {
|
||||
// 202 即返回,实际下载在后台跑,进度走 /api/update/stream。
|
||||
applyUpdate: () => post<{ ok: boolean; target: string }>(`/update/apply`),
|
||||
rollbackUpdate: () => post<{ ok: boolean }>(`/update/rollback`),
|
||||
|
||||
// ---- Sandbox container isolation ----
|
||||
sandboxStatus: (withStats = false) =>
|
||||
get<SandboxGlobalStatus>(`/sandbox/status${withStats ? "?stats=1" : ""}`),
|
||||
updateSandboxSettings: (ov: SandboxRuntimeOverrides) => put<SandboxGlobalStatus>("/sandbox/settings", ov),
|
||||
pruneSandboxContainers: () => post<{ removed: number }>("/sandbox/prune"),
|
||||
sandboxContainer: (scope: string, ownerID: string, withStats = true) =>
|
||||
get<SandboxContainerInfo>(
|
||||
`/sandbox/containers/${encodeURIComponent(scope)}/${encodeURIComponent(ownerID)}${withStats ? "" : "?stats=0"}`,
|
||||
),
|
||||
startSandboxContainer: (scope: string, ownerID: string) =>
|
||||
post<SandboxContainerInfo>(`/sandbox/containers/${encodeURIComponent(scope)}/${encodeURIComponent(ownerID)}/start`),
|
||||
stopSandboxContainer: (scope: string, ownerID: string) =>
|
||||
post<SandboxContainerInfo>(`/sandbox/containers/${encodeURIComponent(scope)}/${encodeURIComponent(ownerID)}/stop`),
|
||||
recreateSandboxContainer: (
|
||||
scope: string,
|
||||
ownerID: string,
|
||||
opts?: { pause_task?: boolean; clear_workspace?: boolean },
|
||||
) =>
|
||||
post<SandboxContainerInfo>(
|
||||
`/sandbox/containers/${encodeURIComponent(scope)}/${encodeURIComponent(ownerID)}/recreate`,
|
||||
opts ?? {},
|
||||
),
|
||||
removeSandboxContainer: (scope: string, ownerID: string) =>
|
||||
del<{ removed: string }>(`/sandbox/containers/${encodeURIComponent(scope)}/${encodeURIComponent(ownerID)}`),
|
||||
taskSandbox: (taskID: string, withStats = true) =>
|
||||
get<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox${withStats ? "" : "?stats=0"}`),
|
||||
startTaskSandbox: (taskID: string) =>
|
||||
post<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox/start`),
|
||||
stopTaskSandbox: (taskID: string, pauseTask = false) =>
|
||||
post<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox/stop`, { pause_task: pauseTask }),
|
||||
recreateTaskSandbox: (taskID: string, opts?: { pause_task?: boolean; clear_workspace?: boolean }) =>
|
||||
post<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox/recreate`, opts ?? {}),
|
||||
};
|
||||
@@ -2004,3 +2004,56 @@ export interface TaskFileListing {
|
||||
truncated: boolean;
|
||||
missing: boolean;
|
||||
}
|
||||
|
||||
// ---- Sandbox Container Isolation ----
|
||||
export interface SandboxContainerInfo {
|
||||
scope: "task" | "session" | "ephemeral" | string;
|
||||
owner_id: string;
|
||||
owner_title?: string;
|
||||
task_running?: boolean;
|
||||
name: string;
|
||||
container_id?: string;
|
||||
short_id?: string;
|
||||
image: string;
|
||||
state: "running" | "exited" | "created" | "missing" | "local" | "error" | string;
|
||||
status_text?: string;
|
||||
created_at?: string;
|
||||
started_at?: string;
|
||||
active_runs: number;
|
||||
cpu_percent?: number;
|
||||
mem_usage_bytes?: number;
|
||||
mem_limit_bytes?: number;
|
||||
pids_current?: number;
|
||||
work_dir_container: string;
|
||||
network?: string;
|
||||
runtime?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface SandboxGlobalStatus {
|
||||
mode: "local" | "docker" | string;
|
||||
enabled: boolean;
|
||||
available: boolean;
|
||||
error?: string;
|
||||
image: string;
|
||||
network: string;
|
||||
runtime: string;
|
||||
memory_mb: number;
|
||||
cpus: number;
|
||||
pids_limit: number;
|
||||
shm_size_mb: number;
|
||||
auto_stop_on_complete: boolean;
|
||||
session_idle_minutes: number;
|
||||
containers: SandboxContainerInfo[];
|
||||
}
|
||||
|
||||
export interface SandboxRuntimeOverrides {
|
||||
image?: string;
|
||||
memory_mb?: number;
|
||||
cpus?: number;
|
||||
pids_limit?: number;
|
||||
shm_size_mb?: number;
|
||||
runtime?: string;
|
||||
auto_stop_on_complete?: boolean;
|
||||
session_idle_minutes?: number;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
Ban,
|
||||
BellRing,
|
||||
Bot,
|
||||
Box,
|
||||
Brain,
|
||||
Bug,
|
||||
CalendarClock,
|
||||
@@ -95,6 +96,7 @@ export const sidebarItems: NavGroup[] = [
|
||||
{ id: "intercept", title: "拦截规则", url: "/system/intercept", icon: ShieldAlert },
|
||||
{ id: "asset-intercept", title: "资产拦截", url: "/system/intercept/assets", icon: Ban },
|
||||
{ id: "approvals", title: "审批记录", url: "/system/intercept/approvals", icon: ClipboardList },
|
||||
{ id: "sandbox", title: "沙箱容器", url: "/system/sandbox", icon: Box },
|
||||
{ id: "logs", title: "日志", url: "/system/logs", icon: ScrollText },
|
||||
{ id: "settings", title: "系统配置", url: "/system/settings", icon: Settings2 },
|
||||
],
|
||||
|
||||
Reference in new issue
Block a user