mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-06 21:11:50 +08:00
- Support pool auto-rotation mode alongside inherit/direct/node/custom proxy routes across gateway and MITM proxy
- Add GET /api/proxy/routes/{scope}/{owner_id}, task create/DTO proxy_route, and schedule proxy persistence + propagation
- Add list_proxy_pool and set_task_proxy chat agent tools and @task mention search/context injection
- Wire shared proxy/pool selectors into tasks, schedules, chat sandbox popover, and container routes UI
504 lines
20 KiB
TypeScript
504 lines
20 KiB
TypeScript
"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 { ContainerProxyControlSection } from "@/components/proxy-route-selector";
|
|
|
|
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,
|
|
sandboxScope,
|
|
sandboxOwnerId,
|
|
running: chatRunning,
|
|
}: {
|
|
conversationId: number;
|
|
sandboxScope?: string;
|
|
sandboxOwnerId?: string;
|
|
running: boolean;
|
|
}) {
|
|
const { isEn } = useLiveTranslation();
|
|
const L = (zh: string, en: string) => (isEn ? en : zh);
|
|
|
|
const scope = sandboxScope === "task" ? "task" : "session";
|
|
const ownerID = sandboxOwnerId ?? `conv-${conversationId}`;
|
|
const taskBound = scope === "task";
|
|
const boxZh = taskBound ? "任务沙箱" : "会话沙箱";
|
|
const boxEn = taskBound ? "Task sandbox" : "Session sandbox";
|
|
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 reqSeqRef = React.useRef(0);
|
|
|
|
const fetchInfo = React.useCallback(
|
|
async (withStats: boolean, silent = false) => {
|
|
const seq = ++reqSeqRef.current;
|
|
if (!silent) setLoading(true);
|
|
try {
|
|
const res = await api.sandboxContainer(scope, ownerID, withStats);
|
|
if (seq === reqSeqRef.current) {
|
|
setInfo(res);
|
|
}
|
|
} catch {
|
|
// Ignore transient poll errors; popover refresh button lets user retry.
|
|
} finally {
|
|
if (seq === reqSeqRef.current && !silent) {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
},
|
|
[scope, ownerID],
|
|
);
|
|
|
|
React.useEffect(() => {
|
|
reqSeqRef.current += 1;
|
|
setInfo(null);
|
|
void fetchInfo(false);
|
|
}, [fetchInfo]);
|
|
|
|
React.useEffect(() => {
|
|
if (!open) return;
|
|
void fetchInfo(true);
|
|
}, [open, fetchInfo]);
|
|
|
|
// Refresh container status whenever a chat turn starts or completes (tool calls
|
|
// lazily create/start the container mid-turn).
|
|
const prevRunningRef = React.useRef(chatRunning);
|
|
React.useEffect(() => {
|
|
if (prevRunningRef.current !== chatRunning) {
|
|
void fetchInfo(open, true);
|
|
}
|
|
prevRunningRef.current = chatRunning;
|
|
}, [chatRunning, open, fetchInfo]);
|
|
|
|
// Poll while a chat turn is running (every 2s until the container reports running,
|
|
// then every 5s) or while the popover is open so live status never stays stale.
|
|
const infoState = info?.state;
|
|
React.useEffect(() => {
|
|
if (infoState === "local") return;
|
|
if (!chatRunning && !open) return;
|
|
const intervalMs = chatRunning && infoState !== "running" ? 2000 : 5000;
|
|
const timer = window.setInterval(() => {
|
|
if (document.visibilityState === "visible") {
|
|
void fetchInfo(open, true);
|
|
}
|
|
}, intervalMs);
|
|
return () => window.clearInterval(timer);
|
|
}, [chatRunning, open, infoState, fetchInfo]);
|
|
|
|
React.useEffect(() => {
|
|
if (infoState === "local") return;
|
|
const onVisibility = () => {
|
|
if (document.visibilityState === "visible") {
|
|
void fetchInfo(open, true);
|
|
}
|
|
};
|
|
document.addEventListener("visibilitychange", onVisibility);
|
|
return () => document.removeEventListener("visibilitychange", onVisibility);
|
|
}, [open, infoState, 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 === "created") stateLabel = L("沙箱启动中", "Sandbox Starting");
|
|
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 === "created") dotClass = "bg-amber-500";
|
|
else if (info.state === "error") dotClass = "bg-red-500";
|
|
|
|
const handleStart = async () => {
|
|
setBusy("start");
|
|
try {
|
|
const res = await api.startSandboxContainer(scope, ownerID);
|
|
reqSeqRef.current += 1;
|
|
setInfo(res);
|
|
toast.success(L(`${boxZh}容器已启动`, `${boxEn} 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(scope, ownerID);
|
|
reqSeqRef.current += 1;
|
|
setInfo(res);
|
|
toast.success(L(`${boxZh}容器已停止(内存已释放)`, `${boxEn} 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(scope, ownerID, { clear_workspace: wipe });
|
|
reqSeqRef.current += 1;
|
|
setInfo(res);
|
|
toast.success(
|
|
wipe
|
|
? L(`${boxZh}已重建并清空工作区`, `${boxEn} recreated with clean workspace`)
|
|
: L(`${boxZh}已重建(工作区文件已保留)`, `${boxEn} 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(scope, ownerID);
|
|
await fetchInfo(false);
|
|
toast.success(L(`${boxZh}容器已删除(工作区文件已保留)`, `${boxEn} 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-96 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(taskBound ? "任务沙箱" : "对话隔离沙箱", taskBound ? "Task Sandbox" : "Chat Sandbox")}
|
|
</span>
|
|
<Badge variant={running ? "default" : "secondary"}>{info.state}</Badge>
|
|
</PopoverTitle>
|
|
<PopoverDescription className="text-xs">
|
|
{taskBound
|
|
? L(
|
|
"本对话调用命令、脚本或浏览器时,实际跑在关联任务的沙箱容器里,不会另开一个对话容器。",
|
|
"Commands, scripts, and browser tools in this chat run in the linked task sandbox, not a separate chat container.",
|
|
)
|
|
: 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(taskBound ? "任务" : "会话", taskBound ? "Task" : "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>
|
|
|
|
<ContainerProxyControlSection scope={scope} ownerId={ownerID} open={open} />
|
|
|
|
<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 items-center justify-between gap-2 border-t pt-2">
|
|
{taskBound ? (
|
|
<Link
|
|
href={`/function/tasks/detail?id=${encodeURIComponent(ownerID)}`}
|
|
className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
|
|
>
|
|
{L("查看关联任务", "Open task")}
|
|
<ExternalLinkIcon className="size-3" />
|
|
</Link>
|
|
) : (
|
|
<span />
|
|
)}
|
|
<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(
|
|
taskBound ? "重建任务沙箱容器" : "重建对话沙箱容器",
|
|
taskBound ? "Recreate Task Sandbox" : "Recreate Chat Sandbox",
|
|
)}
|
|
</AlertDialogTitle>
|
|
<AlertDialogDescription>
|
|
{taskBound
|
|
? L(
|
|
"确定销毁关联任务的沙箱容器,并按最新镜像与资源配额重新创建吗?这会影响该任务,不会另开对话容器。",
|
|
"Replace the linked task's sandbox container with a fresh one? This affects that task.",
|
|
)
|
|
: 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">
|
|
{taskBound
|
|
? L(
|
|
"默认保留任务工作区;勾选后会清空该任务 /workspace 下的文件,包括已有截图和脚本。",
|
|
"Task files are kept by default. Check to wipe this task's /workspace, including screenshots and scripts.",
|
|
)
|
|
: 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(
|
|
taskBound ? "删除任务沙箱容器" : "删除对话沙箱容器",
|
|
taskBound ? "Delete Task Sandbox" : "Delete Chat Sandbox",
|
|
)}
|
|
</AlertDialogTitle>
|
|
<AlertDialogDescription>
|
|
{taskBound
|
|
? L(
|
|
"确定删除关联任务的沙箱容器吗?任务工作区文件会保留,下次执行命令时会重新创建。",
|
|
"Remove the linked task's sandbox container? Task workspace files will be preserved.",
|
|
)
|
|
: 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>
|
|
</>
|
|
);
|
|
}
|