This commit is contained in:
pphua committed 2026-08-24 14:14:15 +08:00
1 parent e67ff26e90
commit 58f23a2773
61 files changed
+11611 -443

No files matched your search

@@ -1,7 +1,7 @@
"use client";
import * as React from "react";
import { CheckIcon, ClipboardListIcon, RefreshCwIcon, ShieldAlertIcon, XIcon } from "lucide-react";
import { BotIcon, CheckIcon, ClipboardListIcon, RefreshCwIcon, ShieldAlertIcon, XIcon } from "lucide-react";
import { toast } from "sonner";
import { api } from "@/lib/api";
import type { InterceptApprovalRow } from "@/lib/types";
@@ -40,6 +40,33 @@ function SourceCell({ row }: { row: InterceptApprovalRow }) {
return <span className="text-muted-foreground">—</span>;
}
// MatchCell shows the matched rule name, or a "模型判定" badge when the decision
// came from the LLM fallback judge (rule_id null). The reason (rule message or
// model rationale, minus the [模型] prefix) is shown beneath.
function MatchCell({ row }: { row: InterceptApprovalRow }) {
const isModel = !row.rule_id;
const reason = row.reason?.replace(/^\[模型\]\s*/, "").trim();
return (
<div className="space-y-0.5">
{row.rule_name ? (
<span className="text-sm">{row.rule_name}</span>
) : isModel ? (
<Badge variant="outline" className="gap-1 border-violet-400 text-violet-600">
<BotIcon className="h-3 w-3" />
模型判定
</Badge>
) : (
<span className="text-muted-foreground">—</span>
)}
{reason && (
<p className="line-clamp-1 text-[11px] text-muted-foreground" title={reason}>
{reason}
</p>
)}
</div>
);
}
function StatusBadge({ status }: { status: string }) {
if (status === "pending") return <Badge variant="outline" className="border-amber-400 text-amber-600">待审批</Badge>;
if (status === "allowed") return <Badge variant="outline" className="border-emerald-500 text-emerald-600">已允许</Badge>;
@@ -155,11 +182,7 @@ export default function ApprovalsPage() {
<code className="rounded bg-muted px-1.5 py-0.5 text-xs font-mono">{row.tool_name}</code>
</TableCell>
<TableCell><SourceCell row={row} /></TableCell>
<TableCell>
{row.rule_name
? <span className="text-sm">{row.rule_name}</span>
: <span className="text-muted-foreground">—</span>}
</TableCell>
<TableCell><MatchCell row={row} /></TableCell>
<TableCell className="w-48 max-w-[12rem]"><InputPreview input={row.tool_input} /></TableCell>
<TableCell className="whitespace-nowrap text-xs text-muted-foreground">{fmtTime(row.created_at)}</TableCell>
<TableCell className="text-right">
@@ -221,11 +244,7 @@ export default function ApprovalsPage() {
<code className="rounded bg-muted px-1.5 py-0.5 text-xs font-mono">{row.tool_name}</code>
</TableCell>
<TableCell><SourceCell row={row} /></TableCell>
<TableCell>
{row.rule_name
? <span className="text-sm">{row.rule_name}</span>
: <span className="text-muted-foreground">—</span>}
</TableCell>
<TableCell><MatchCell row={row} /></TableCell>
<TableCell className="w-48 max-w-[12rem]"><InputPreview input={row.tool_input} /></TableCell>
<TableCell><StatusBadge status={row.status} /></TableCell>
<TableCell className="whitespace-nowrap text-xs text-muted-foreground">{fmtTime(row.created_at)}</TableCell>
+284 -27
View File
@@ -3,6 +3,7 @@
import * as React from "react";
import { toast } from "sonner";
import {
BotIcon,
ListFilterIcon,
PencilIcon,
PlusIcon,
@@ -48,8 +49,9 @@ import {
TableRow,
} from "@/components/ui/table";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { api } from "@/lib/api";
import type { InterceptRule, InterceptAction, Tool } from "@/lib/types";
import type { InterceptRule, InterceptAction, JudgeConfig, LLMProfile, Tool } from "@/lib/types";
// ---- tool scope ----
@@ -143,6 +145,203 @@ function Field({ label, children }: { label: string; children: React.ReactNode }
);
}
// ---- LLM fallback judge card ----
const FOLLOW_ACTIVE = "0"; // profile_id 0 = 跟随激活/默认配置
const defaultJudge = (): JudgeConfig => ({
enabled: false,
profile_id: 0,
prompt: "",
timeout_seconds: 15,
fail_action: "allow",
ask_timeout_seconds: 300,
ask_timeout_action: "deny",
});
function JudgeCard() {
const [cfg, setCfg] = React.useState<JudgeConfig>(defaultJudge());
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
const [loading, setLoading] = React.useState(true);
const [saving, setSaving] = React.useState(false);
const load = React.useCallback(async () => {
setLoading(true);
try {
const [j, ps] = await Promise.all([api.interceptGetJudgeConfig(), api.llmProfiles()]);
setCfg(j);
setProfiles(ps);
} catch (e) {
toast.error("加载模型兜底配置失败: " + (e as Error).message);
} finally {
setLoading(false);
}
}, []);
React.useEffect(() => {
load();
}, [load]);
function patch(p: Partial<JudgeConfig>) {
setCfg((c) => ({ ...c, ...p }));
}
async function save() {
setSaving(true);
try {
await api.interceptSetJudgeConfig(cfg);
toast.success("模型兜底配置已保存");
await load(); // 回读:提示词若清空则回填内置模板
} catch (e) {
toast.error("保存失败: " + (e as Error).message);
} finally {
setSaving(false);
}
}
async function restorePrompt() {
// 清空提示词并保存 → 服务端下次返回内置模板全文,回填到输入框。
setSaving(true);
try {
await api.interceptSetJudgeConfig({ ...cfg, prompt: "" });
const j = await api.interceptGetJudgeConfig();
setCfg(j);
toast.success("已恢复内置默认模板");
} catch (e) {
toast.error("恢复失败: " + (e as Error).message);
} finally {
setSaving(false);
}
}
return (
<div className="space-y-4">
{/* 启用开关 —— 独立高亮条 */}
<div
className={`flex items-center justify-between gap-3 rounded-lg border px-4 py-3 ${
cfg.enabled ? "border-violet-400/50 bg-violet-50/40 dark:bg-violet-950/20" : "bg-muted/40"
}`}
>
<div className="flex items-center gap-2.5">
<BotIcon className={`h-5 w-5 shrink-0 ${cfg.enabled ? "text-violet-600" : "text-muted-foreground"}`} />
<div>
<p className="text-sm font-semibold leading-tight">模型兜底审批</p>
<p className="text-xs text-muted-foreground mt-0.5">
在<span className="font-medium text-foreground">拦截范围</span>内、且<span className="font-medium text-foreground">没有任何拦截规则命中</span>的命令,才由模型做语义判断(放行 / 转人工 / 拦截)
</p>
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
<span className="text-xs text-muted-foreground">{cfg.enabled ? "已启用" : "未启用"}</span>
<Switch checked={cfg.enabled} disabled={loading} onCheckedChange={(v) => patch({ enabled: v })} />
</div>
</div>
{cfg.enabled && (
<div className="grid gap-4 lg:grid-cols-5">
{/* 左:提示词编辑器(直接展开,主区域) */}
<Card className="lg:col-span-3">
<CardContent className="flex h-full flex-col gap-2 p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">审批提示词</p>
<p className="text-xs text-muted-foreground">模型据此判定 ALLOW / ASK / DENY,可直接编辑</p>
</div>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={restorePrompt} disabled={saving}>
恢复默认模板
</Button>
</div>
<Textarea
className="min-h-[22rem] flex-1 resize-none font-mono text-xs leading-relaxed"
value={cfg.prompt}
onChange={(e) => patch({ prompt: e.target.value })}
placeholder="留空使用内置模板"
spellCheck={false}
/>
<p className="text-right text-[11px] text-muted-foreground">{cfg.prompt.length} 字</p>
</CardContent>
</Card>
{/* 右:判定参数(设置栏) */}
<Card className="lg:col-span-2">
<CardContent className="space-y-5 p-4">
<div className="space-y-4">
<p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">判定模型与策略</p>
<Field label="审批模型">
<Select value={String(cfg.profile_id || 0)} onValueChange={(v) => patch({ profile_id: Number(v) })}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={FOLLOW_ACTIVE}>跟随激活配置</SelectItem>
{profiles.map((p) => (
<SelectItem key={p.id} value={p.id}>
{p.name}({p.model})
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field label="模型判定超时(秒)">
<Input
type="number"
min={1}
value={cfg.timeout_seconds}
onChange={(e) => {
const n = parseInt(e.target.value, 10);
if (n > 0) patch({ timeout_seconds: n });
}}
/>
</Field>
<Field label="模型失败时(出错 / 超时 / 无法解析)">
<Select value={cfg.fail_action} onValueChange={(v) => patch({ fail_action: v as JudgeConfig["fail_action"] })}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="allow">放行</SelectItem>
<SelectItem value="ask">转人工审批</SelectItem>
<SelectItem value="deny">拦截</SelectItem>
</SelectContent>
</Select>
</Field>
</div>
<Separator />
<div className="space-y-4">
<p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">人工审批(模型判为「转人工」时)</p>
<Field label="审批等待超时(秒)">
<Input
type="number"
min={5}
value={cfg.ask_timeout_seconds}
onChange={(e) => {
const n = parseInt(e.target.value, 10);
if (n > 0) patch({ ask_timeout_seconds: n });
}}
/>
</Field>
<Field label="超时后默认动作">
<Select value={cfg.ask_timeout_action} onValueChange={(v) => patch({ ask_timeout_action: v as JudgeConfig["ask_timeout_action"] })}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="deny">拦截</SelectItem>
<SelectItem value="allow">放行</SelectItem>
</SelectContent>
</Select>
</Field>
</div>
</CardContent>
</Card>
</div>
)}
<div className="flex justify-end">
<Button size="sm" onClick={save} disabled={saving || loading}>
{saving ? "保存中…" : "保存配置"}
</Button>
</div>
</div>
);
}
// ---- page ----
export default function InterceptPage() {
@@ -161,9 +360,19 @@ export default function InterceptPage() {
const [enabledTools, setEnabledTools] = React.useState<Set<string>>(new Set());
const [scopeLoading, setScopeLoading] = React.useState(false);
const [scopeSaving, setScopeSaving] = React.useState(false);
const [scopeTools, setScopeTools] = React.useState<string[]>([]); // 页头信息条:当前进入拦截的工具
// ---- data ----
const loadScope = React.useCallback(async () => {
try {
const cfg = await api.interceptGetToolConfig();
setScopeTools(cfg.enabled_tools);
} catch {
// 信息条非关键,失败静默
}
}, []);
const load = React.useCallback(async () => {
try {
const r = await api.interceptRules();
@@ -175,7 +384,7 @@ export default function InterceptPage() {
}
}, []);
React.useEffect(() => { load(); }, [load]);
React.useEffect(() => { load(); loadScope(); }, [load, loadScope]);
React.useEffect(() => {
if (form.match_type !== "regex" || !form.pattern) { setRegexErr(""); setRegexWarn(false); return; }
@@ -285,6 +494,7 @@ export default function InterceptPage() {
try {
await api.interceptSetToolConfig([...enabledTools]);
toast.success("拦截范围已保存");
setScopeTools([...enabledTools]);
setScopeOpen(false);
} catch (e) {
toast.error("保存失败: " + (e as Error).message);
@@ -298,34 +508,74 @@ export default function InterceptPage() {
// ---- render ----
return (
<div className="flex flex-1 flex-col gap-6 p-6">
<div className="flex flex-1 flex-col gap-5 p-6">
{/* ---- header ---- */}
<div className="flex items-start justify-between">
<div className="flex items-center gap-2.5">
<ShieldAlertIcon className="h-5 w-5 mt-0.5 shrink-0" />
<div>
<h1 className="text-lg font-semibold leading-tight">拦截规则</h1>
<p className="text-sm text-muted-foreground mt-0.5">
工具执行前按优先级(数字越大越先)逐条匹配,首条命中的规则生效
</p>
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
<Button variant="outline" size="sm" onClick={openScope}>
<ListFilterIcon className="h-4 w-4" />
拦截范围
</Button>
<Button onClick={openNew} size="sm">
<PlusIcon className="h-4 w-4" />
新建规则
</Button>
<div className="flex items-center gap-2.5">
<ShieldAlertIcon className="h-5 w-5 shrink-0" />
<div>
<h1 className="text-lg font-semibold leading-tight">命令拦截</h1>
<p className="text-sm text-muted-foreground mt-0.5">
工具执行前先按拦截规则匹配;未命中的命令可交由模型兜底判定
</p>
</div>
</div>
{/* ---- rules table ---- */}
<Card>
<CardContent className="p-0">
{/* ---- 拦截范围信息条(规则匹配与模型兜底共用:不在范围内的工具两者都不介入)---- */}
<div
className={`flex items-center justify-between gap-3 rounded-lg border px-4 py-2.5 ${
scopeTools.length === 0
? "border-amber-400/60 bg-amber-50/50 dark:bg-amber-950/20"
: "bg-muted/40"
}`}
>
<div className="flex min-w-0 items-center gap-2 text-sm">
<ListFilterIcon className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="shrink-0 font-medium">拦截范围</span>
{scopeTools.length === 0 ? (
<span className="text-amber-700 dark:text-amber-500">
未启用任何工具 — 拦截规则与模型兜底均不会生效
</span>
) : (
<>
<Badge variant="secondary" className="shrink-0">{scopeTools.length} 个工具</Badge>
<span className="truncate text-muted-foreground" title={scopeTools.join("、")}>
{scopeTools.join("、")}
</span>
</>
)}
</div>
<Button
variant={scopeTools.length === 0 ? "default" : "outline"}
size="sm"
className="shrink-0"
onClick={openScope}
>
<ListFilterIcon className="h-4 w-4" />
调整范围
</Button>
</div>
<Tabs defaultValue="rules" className="flex-1">
<TabsList>
<TabsTrigger value="rules">拦截规则</TabsTrigger>
<TabsTrigger value="judge">模型配置</TabsTrigger>
</TabsList>
{/* ---- tab: 拦截规则 ---- */}
<TabsContent value="rules" className="mt-4 flex flex-col gap-4">
<div className="flex items-center justify-between gap-3">
<p className="text-xs text-muted-foreground">
按优先级(数字越大越先)逐条匹配,首条命中的规则生效
</p>
<Button onClick={openNew} size="sm" className="shrink-0">
<PlusIcon className="h-4 w-4" />
新建规则
</Button>
</div>
<Card>
<CardContent className="p-0">
{loading ? (
<p className="p-6 text-sm text-muted-foreground">加载中…</p>
) : rules.length === 0 ? (
@@ -404,8 +654,15 @@ export default function InterceptPage() {
</TableBody>
</Table>
)}
</CardContent>
</Card>
</CardContent>
</Card>
</TabsContent>
{/* ---- tab: 模型配置 ---- */}
<TabsContent value="judge" className="mt-4">
<JudgeCard />
</TabsContent>
</Tabs>
{/* ---- editor sheet ---- */}
<Sheet open={open} onOpenChange={setOpen}>
+298
View File
@@ -461,7 +461,305 @@ export default function LLMPage() {
}
}
<<<<<<< Updated upstream
async function activate(id: string) {
=======
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent
side="right"
className="flex flex-col gap-0 p-0 data-[side=right]:min-w-[420px] data-[side=right]:sm:max-w-xl"
// 表单填到一半时点外面不该丢内容(Esc / ✕ 仍可关闭)。
onInteractOutside={(e) => e.preventDefault()}
>
<SheetHeader className="px-4">
<SheetTitle className="flex items-center gap-2">
{isNew ? "新建模型配置" : `编辑:${profile?.name}`}
{profile?.is_default && (
<Badge variant="outline" className="border-amber-400/50 text-amber-500">
激活中
</Badge>
)}
</SheetTitle>
<SheetDescription>
{isNew
? "新建后不会自动激活,请在卡片上「设为激活」以启用。"
: "修改后点击保存;激活配置保存后对全部 Agent 立即生效。"}
</SheetDescription>
</SheetHeader>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="grid gap-2">
<Label htmlFor="p-name">名称</Label>
<Input
id="p-name"
placeholder="例如:OpenAI 生产"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label>格式</Label>
<Select value={format} onValueChange={(v) => setFormat(v as "anthropic" | "openai")}>
<SelectTrigger>
<SelectValue placeholder="选择格式" />
</SelectTrigger>
<SelectContent>
<SelectItem value="anthropic">Anthropic</SelectItem>
<SelectItem value="openai">OpenAI</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="p-model">模型</Label>
<div className="flex gap-2">
<Input
id="p-model"
className="font-mono"
placeholder="claude-opus-4-8"
value={model}
onChange={(e) => setModel(e.target.value)}
/>
{/* modal: 这个 Popover 的内容被 portal 到 <body>,在 Sheet 的滚动锁之外,
不加 modal 时列表能渲染却滚不动。modal 让它自己持有最上层滚动锁。 */}
<Popover open={modelsOpen} onOpenChange={setModelsOpen} modal>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="shrink-0"
disabled={loadingModels}
onClick={loadModels}
title="从 API 加载可用模型"
>
{loadingModels ? <Loader2Icon className="animate-spin" /> : <RefreshCwIcon />}
</Button>
</PopoverTrigger>
{models.length > 0 && (
<PopoverContent className="max-h-72 w-72 gap-0 overflow-y-auto overscroll-contain p-1" align="end">
{models.map((m) => (
<button
key={m}
type="button"
className="w-full shrink-0 rounded-md px-2 py-1.5 text-left font-mono text-xs hover:bg-accent hover:text-accent-foreground"
onClick={() => {
setModel(m);
setModelsOpen(false);
}}
>
{m}
</button>
))}
</PopoverContent>
)}
</Popover>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="p-base-url">Base URL(可选)</Label>
<Input
id="p-base-url"
className="font-mono"
placeholder="https://api.openai.com/v1"
value={baseUrl}
onChange={(e) => setBaseUrl(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="p-proxy">代理(可选)</Label>
<Input
id="p-proxy"
className="font-mono"
placeholder="socks5://user:[email protected]:1080 · http://127.0.0.1:8080"
value={proxy}
onChange={(e) => setProxy(e.target.value)}
/>
<p className="text-muted-foreground text-xs">
仅 LLM 出站请求走此代理,支持 http/https/socks5,可带账号密码(如 socks5://user:pass@host:port,密码含特殊字符需 URL 编码);留空表示不使用代理(直连)。
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="p-api-key">API Key</Label>
<Input
id="p-api-key"
type="password"
placeholder={keyHint ? `已设置(${keyHint}),留空保持不变` : "sk-…"}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
/>
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div className="grid gap-2">
<Label htmlFor="p-rps">每秒限速</Label>
<Input id="p-rps" type="number" min={0} value={rps} onChange={(e) => setRps(e.target.value)} />
</div>
<div className="grid gap-2">
<Label htmlFor="p-rpm">每分钟限速</Label>
<Input id="p-rpm" type="number" min={0} value={rpm} onChange={(e) => setRpm(e.target.value)} />
</div>
<div className="grid gap-2">
<Label htmlFor="p-cw">上下文窗口(K)</Label>
<Input
id="p-cw"
type="number"
min={0}
max={1000}
value={cw}
onChange={(e) => setCw(e.target.value)}
placeholder="200"
/>
</div>
</div>
<p className="-mt-2 text-muted-foreground text-xs">
限速 0 = 不限,全 Agent 共享。上下文窗口单位 K(千 token),0 = 默认 200K,上限 1000(即
1M);设太高会导致压缩不触发。
</p>
<div className="grid gap-3 rounded-lg border p-3">
<div className="flex items-center justify-between gap-4">
<div className="grid gap-0.5">
<Label htmlFor="p-priority" className="text-sm">
轮询优先级
</Label>
<p className="text-muted-foreground text-xs">
数字越大越先被选中;激活配置恒为第 1 顺位,与本值无关。相同优先级的配置会轮流打头,天然分摊额度。
</p>
</div>
<Input
id="p-priority"
type="number"
className="w-24 shrink-0"
value={priority}
onChange={(e) => setPriority(e.target.value)}
/>
</div>
<div className="flex items-center justify-between gap-4 border-t pt-3">
<div className="grid gap-0.5">
<Label className="text-sm">不参与轮询</Label>
<p className="text-muted-foreground text-xs">
开启后不会被当作故障转移目标(仍可被 Agent / 任务显式指定使用)。 适合「只给某个 Agent
专用、不希望别人失败时烧掉」的昂贵配置。
</p>
</div>
<Switch checked={poolExclude} onCheckedChange={setPoolExclude} aria-label="不参与轮询" />
</div>
</div>
<div className="grid gap-3 rounded-lg border p-3">
<div className="flex items-center justify-between gap-4">
<div className="grid gap-0.5">
<Label className="text-sm">思考开关 · thinking.type</Label>
<p className="text-muted-foreground text-xs">
控制是否发送 thinking 字段。不发送=不带该字段(兼容 MiniMax 等不支持
的模型);关闭=发 disabled;开启=发 enabled。与下面的强度互相独立。
</p>
</div>
<Select value={thinkingType} onValueChange={setThinkingType}>
<SelectTrigger className="w-32 shrink-0">
<SelectValue />
</SelectTrigger>
<SelectContent>
{THINKING_TYPES.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex items-center justify-between gap-4 border-t pt-3">
<div className="grid gap-0.5">
<Label className="text-sm">思考强度 · reasoning_effort</Label>
<p className="text-muted-foreground text-xs">
独立的强度档位(OpenAI reasoning_effort / Anthropic output_config.effort)。
有些接口没有 thinking 字段、只靠强度即可激活思考,故可单独设置、不发送思考开关。
</p>
</div>
<Select value={effort} onValueChange={setEffort}>
<SelectTrigger className="w-32 shrink-0">
<SelectValue />
</SelectTrigger>
<SelectContent>
{EFFORT_LEVELS.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
<div className="flex gap-2 border-t px-4 py-3">
<Button variant="outline" onClick={testConnection} disabled={testing}>
{testing ? <Loader2Icon className="animate-spin" /> : <PlugZapIcon />}
{testing ? "测试中…" : "测试连接"}
</Button>
<Button onClick={save} disabled={saving} className="flex-1">
{saving && <Loader2Icon className="animate-spin" />}
{!saving && (isNew ? <PlusIcon /> : <SaveIcon />)}
{isNew ? "新建" : "保存"}
</Button>
</div>
</SheetContent>
</Sheet>
);
}
// ─────────────────────────────────────────────────────────────────────────────
export default function LLMPage() {
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
const [pool, setPool] = React.useState<LLMPoolStatus | null>(null);
const [poolOpen, setPoolOpen] = React.useState(false);
// 抽屉的开关和内容分开存:关闭时 editing 保持不变,否则关闭动画期间标题会从
// 「编辑 X」闪成「新建」。editing = null 表示新建。
const [editOpen, setEditOpen] = React.useState(false);
const [editing, setEditing] = React.useState<LLMProfile | null>(null);
const openEditor = React.useCallback((p: LLMProfile | null) => {
setEditing(p);
setEditOpen(true);
}, []);
const loadPool = React.useCallback(async () => {
try {
setPool(await api.llmPool());
} catch {
/* ignore */
}
}, []);
const load = React.useCallback(async () => {
try {
setProfiles(await api.llmProfiles());
} catch {
/* ignore */
}
await loadPool();
}, [loadPool]);
React.useEffect(() => {
void load();
}, [load]);
// 卡片上的健康徽章按 profile id 取轮询状态。
const health = React.useMemo(() => {
const m = new Map<string, LLMPoolMember>();
for (const c of pool?.chain ?? []) m.set(c.profile_id, c);
return m;
}, [pool]);
async function activate(id: string, name: string) {
>>>>>>> Stashed changes
try {
await api.activateLLMProfile(id);
const p = profiles.find((x) => x.id === id);
+337 -225
View File
@@ -2,7 +2,7 @@
import * as React from "react";
import { CpuIcon, RadioTowerIcon, SearchIcon } from "lucide-react";
import { CpuIcon, KeyboardIcon, RadioTowerIcon, SearchIcon, ShieldAlertIcon } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
@@ -12,6 +12,7 @@ import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { api } from "@/lib/api";
import { CHAT_SEND_MODE_OPTIONS, type ChatSendMode, setChatSendMode, useChatSendMode } from "@/lib/chat-send-mode";
import type { Settings } from "@/lib/types";
export default function SystemSettingsPage() {
@@ -32,6 +33,11 @@ export default function SystemSettingsPage() {
const [pyInterp, setPyInterp] = React.useState("");
const [workers, setWorkers] = React.useState("3");
const [savingWorkers, setSavingWorkers] = React.useState(false);
// 操作约束注入范围(默认都开)。
const [injectPlanner, setInjectPlanner] = React.useState(true);
const [injectWorker, setInjectWorker] = React.useState(true);
// 纯前端偏好:不走 /api/settings,直接读写 localStorage。
const sendMode = useChatSendMode();
const apply = React.useCallback((s: Settings) => {
setTrafficCapture(!!s.traffic_capture);
@@ -42,6 +48,8 @@ export default function SystemSettingsPage() {
setProxyInput(s.web_search_proxy || "");
setPyInterp(s.python_interpreter || "");
setWorkers(String(s.workers ?? 3));
setInjectPlanner(s.constraints_inject_planner !== false);
setInjectWorker(s.constraints_inject_worker !== false);
}, []);
const saveWorkers = () => {
@@ -74,7 +82,11 @@ export default function SystemSettingsPage() {
};
const detectPython = () => {
setSaving(true);
api.detectPython().then((r) => setPyInterp(r.python_interpreter)).catch(() => undefined).finally(() => setSaving(false));
api
.detectPython()
.then((r) => setPyInterp(r.python_interpreter))
.catch(() => undefined)
.finally(() => setSaving(false));
};
React.useEffect(() => {
@@ -95,6 +107,22 @@ export default function SystemSettingsPage() {
.finally(() => setSaving(false));
};
const toggleInjectPlanner = (v: boolean) => {
setInjectPlanner(v); // optimistic
api
.setSettings({ constraints_inject_planner: v })
.then(apply)
.catch(() => setInjectPlanner(!v)); // revert on failure
};
const toggleInjectWorker = (v: boolean) => {
setInjectWorker(v); // optimistic
api
.setSettings({ constraints_inject_worker: v })
.then(apply)
.catch(() => setInjectWorker(!v)); // revert on failure
};
// Persist a web-search patch (enable and/or backend). Optimistic with refetch.
const saveWebSearch = (patch: Partial<Settings>) => {
setSaving(true);
@@ -181,249 +209,333 @@ export default function SystemSettingsPage() {
<p className="text-muted-foreground text-sm">全局运行时开关</p>
</div>
<Card className="max-w-2xl">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<RadioTowerIcon className="size-4" />
流量捕获
</CardTitle>
<CardDescription>
开启后,所有 Agent 的 HTTP 流量经记录代理全量落库,并向 Agent 注入 traffic_search / traffic_get
工具与代理配置(提示词含代理说明)。
<br />
关闭(默认)时不记录任何流量:Agent
<b>不会</b>拿到代理配置与流量工具,提示词也<b>不含</b>代理相关内容。切换后会即时重建 Agent 生效。
</CardDescription>
</CardHeader>
<CardContent className="flex items-center justify-between gap-4">
<Label htmlFor="traffic-capture" className="text-sm font-normal text-muted-foreground">
{trafficCapture ? "已开启 · 正在记录流量并注入代理" : "已关闭 · 不记录、不注入代理"}
</Label>
<Switch
id="traffic-capture"
checked={trafficCapture}
disabled={!loaded || saving}
onCheckedChange={toggleTraffic}
/>
</CardContent>
</Card>
<Card className="max-w-2xl">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<SearchIcon className="size-4" />
网络搜索
</CardTitle>
<CardDescription>
这是网络搜索的<b>总开关 + 来源配置</b>。开启后,才能在<b>每个 Agent 的配置</b>里单独选择是否启用
<b>web_search</b>(仅返回标题/链接/摘要,不抓取正文;抓取由 WebFetch 负责)。网络搜索<b>不走</b>记录代理,独立于流量捕获。
<br />
来源可选 <b>DuckDuckGo(ddgs)</b>(无需 Key)、<b>Brave(免费版)</b>(需填写 Brave API Key)或 <b>Tavily</b>(需填写 Tavily API Key)。总开关关闭时,各 Agent 的网络搜索开关不可用。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-4">
<Label htmlFor="web-search" className="text-sm font-normal text-muted-foreground">
{webSearch ? "总开关已开启 · 可在各 Agent 配置里单独启用" : "已关闭 · 各 Agent 无法启用网络搜索"}
{/* 多列而非 grid:网络搜索卡片比其余高数倍,且高度随所选后端变化(brave/tavily
的 key 输入是条件渲染)。grid 会按最高的一张撑满整行、在旁边留下大片空白,
多列则自动按内容高度平衡填充。卡片间距靠 mb 而非 gap——多列布局下
column-gap 只管列间距,行间距要由子元素自己给。 */}
<div className="columns-1 gap-4 md:gap-6 lg:columns-2">
<Card className="mb-4 break-inside-avoid md:mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<RadioTowerIcon className="size-4" />
流量捕获
</CardTitle>
<CardDescription>
开启后,所有 Agent 的 HTTP 流量经记录代理全量落库,并向 Agent 注入 traffic_search / traffic_get
工具与代理配置(提示词含代理说明)。
<br />
关闭(默认)时不记录任何流量:Agent
<b>不会</b>拿到代理配置与流量工具,提示词也<b>不含</b>代理相关内容。切换后会即时重建 Agent 生效。
</CardDescription>
</CardHeader>
<CardContent className="flex items-center justify-between gap-4">
<Label htmlFor="traffic-capture" className="text-sm font-normal text-muted-foreground">
{trafficCapture ? "已开启 · 正在记录流量并注入代理" : "已关闭 · 不记录、不注入代理"}
</Label>
<Switch
id="web-search"
checked={webSearch}
id="traffic-capture"
checked={trafficCapture}
disabled={!loaded || saving}
onCheckedChange={(v) => {
setWebSearch(v); // optimistic
saveWebSearch({ web_search_enabled: v });
}}
onCheckedChange={toggleTraffic}
/>
</div>
</CardContent>
</Card>
{webSearch && (
<Card className="mb-4 break-inside-avoid md:mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ShieldAlertIcon className="size-4" />
操作约束注入
</CardTitle>
<CardDescription>
开启后,把每个任务的<b>操作约束</b>(在任务总览「操作约束」里维护的 allow/deny 条目)拼进对应 Agent
的系统提示,用来框定探索边界(如「仅测当前端口」「禁止爆破」)。
<br />
可分别控制注入到 <b>规划者(planner)</b>与 <b>执行者(worker)</b>;默认都开。切换即时生效(下一轮读取),无需重建
Agent。关闭后该 Agent 不再看到约束。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-4">
<Label className="text-sm font-normal text-muted-foreground">搜索来源</Label>
<Select
value={backend}
<Label htmlFor="inject-planner" className="text-sm font-normal text-muted-foreground">
注入规划者(planner){injectPlanner ? " · 已开启" : " · 已关闭"}
</Label>
<Switch
id="inject-planner"
checked={injectPlanner}
disabled={!loaded}
onCheckedChange={toggleInjectPlanner}
/>
</div>
<div className="flex items-center justify-between gap-4">
<Label htmlFor="inject-worker" className="text-sm font-normal text-muted-foreground">
注入执行者(worker){injectWorker ? " · 已开启" : " · 已关闭"}
</Label>
<Switch
id="inject-worker"
checked={injectWorker}
disabled={!loaded}
onCheckedChange={toggleInjectWorker}
/>
</div>
</CardContent>
</Card>
<Card className="mb-4 break-inside-avoid md:mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<SearchIcon className="size-4" />
网络搜索
</CardTitle>
<CardDescription>
这是网络搜索的<b>总开关 + 来源配置</b>。开启后,才能在<b>每个 Agent 的配置</b>里单独选择是否启用
<b>web_search</b>(仅返回标题/链接/摘要,不抓取正文;抓取由 WebFetch 负责)。网络搜索<b>不走</b>
记录代理,独立于流量捕获。
<br />
来源可选 <b>DuckDuckGo(ddgs)</b>(无需 Key)、<b>Brave(免费版)</b>(需填写 Brave API Key)或{" "}
<b>Tavily</b>(需填写 Tavily API Key)。总开关关闭时,各 Agent 的网络搜索开关不可用。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-4">
<Label htmlFor="web-search" className="text-sm font-normal text-muted-foreground">
{webSearch ? "总开关已开启 · 可在各 Agent 配置里单独启用" : "已关闭 · 各 Agent 无法启用网络搜索"}
</Label>
<Switch
id="web-search"
checked={webSearch}
disabled={!loaded || saving}
onValueChange={(v) => {
setBackend(v); // optimistic
saveWebSearch({ web_search_backend: v });
onCheckedChange={(v) => {
setWebSearch(v); // optimistic
saveWebSearch({ web_search_enabled: v });
}}
>
<SelectTrigger className="w-48 shrink-0">
<SelectValue placeholder="选择来源" />
</SelectTrigger>
<SelectContent>
<SelectItem value="ddgs">DuckDuckGo(ddgs · 免费无 Key)</SelectItem>
<SelectItem value="brave-free">Brave(免费版 · 需 Key)</SelectItem>
<SelectItem value="tavily">Tavily(需 Key)</SelectItem>
</SelectContent>
</Select>
/>
</div>
)}
{webSearch && backend === "brave-free" && (
<div className="flex flex-col gap-2">
<Label htmlFor="brave-key" className="text-sm font-normal text-muted-foreground">
Brave Search API Key
{braveKeySet && <span className="ml-2 text-xs text-emerald-500">已配置</span>}
</Label>
<div className="flex items-center gap-2">
<Input
id="brave-key"
type="password"
autoComplete="off"
placeholder={braveKeySet ? "已配置(留空则不变)" : "输入 Brave API Key"}
value={braveKeyInput}
disabled={!loaded || savingKey}
onChange={(e) => setBraveKeyInput(e.target.value)}
/>
{webSearch && (
<div className="flex items-center justify-between gap-4">
<Label className="text-sm font-normal text-muted-foreground">搜索来源</Label>
<Select
value={backend}
disabled={!loaded || saving}
onValueChange={(v) => {
setBackend(v); // optimistic
saveWebSearch({ web_search_backend: v });
}}
>
<SelectTrigger className="w-48 shrink-0">
<SelectValue placeholder="选择来源" />
</SelectTrigger>
<SelectContent>
<SelectItem value="ddgs">DuckDuckGo(ddgs · 免费无 Key)</SelectItem>
<SelectItem value="brave-free">Brave(免费版 · 需 Key)</SelectItem>
<SelectItem value="tavily">Tavily(需 Key)</SelectItem>
</SelectContent>
</Select>
</div>
)}
{webSearch && backend === "brave-free" && (
<div className="flex flex-col gap-2">
<Label htmlFor="brave-key" className="text-sm font-normal text-muted-foreground">
Brave Search API Key
{braveKeySet && <span className="ml-2 text-xs text-emerald-500">已配置</span>}
</Label>
<div className="flex items-center gap-2">
<Input
id="brave-key"
type="password"
autoComplete="off"
placeholder={braveKeySet ? "已配置(留空则不变)" : "输入 Brave API Key"}
value={braveKeyInput}
disabled={!loaded || savingKey}
onChange={(e) => setBraveKeyInput(e.target.value)}
/>
<Button
type="button"
onClick={saveBraveKey}
disabled={!loaded || savingKey || braveKeyInput.trim() === ""}
>
保存
</Button>
</div>
{braveNeedsKey && (
<p className="text-xs text-amber-500">
已选择 Brave 但尚未配置 Key —— 在保存 Key 之前,搜索工具不会启用。
</p>
)}
<p className="text-muted-foreground text-xs">
免费版额度约 2,000 次/月。前往 https://brave.com/search/api/ 获取 Key。
</p>
</div>
)}
{webSearch && backend === "tavily" && (
<div className="flex flex-col gap-2">
<Label htmlFor="tavily-key" className="text-sm font-normal text-muted-foreground">
Tavily Search API Key
{tavilyKeySet && <span className="ml-2 text-xs text-emerald-500">已配置</span>}
</Label>
<div className="flex items-center gap-2">
<Input
id="tavily-key"
type="password"
autoComplete="off"
placeholder={tavilyKeySet ? "已配置(留空则不变)" : "输入 Tavily API Key(tvly-…)"}
value={tavilyKeyInput}
disabled={!loaded || savingTavilyKey}
onChange={(e) => setTavilyKeyInput(e.target.value)}
/>
<Button
type="button"
onClick={saveTavilyKey}
disabled={!loaded || savingTavilyKey || tavilyKeyInput.trim() === ""}
>
保存
</Button>
</div>
{webSearch && backend === "tavily" && !tavilyKeySet && (
<p className="text-xs text-amber-500">
已选择 Tavily 但尚未配置 Key —— 在保存 Key 之前,搜索工具不会启用。
</p>
)}
<p className="text-muted-foreground text-xs">前往 https://tavily.com 注册并获取 API Key。</p>
</div>
)}
{webSearch && (
<div className="flex flex-col gap-2">
<Label htmlFor="ws-proxy" className="text-sm font-normal text-muted-foreground">
出口代理(可选)
</Label>
<div className="flex items-center gap-2">
<Input
id="ws-proxy"
autoComplete="off"
placeholder="http://host:port 或 socks5://host:port(留空=直连)"
value={proxyInput}
disabled={!loaded || savingProxy}
onChange={(e) => setProxyInput(e.target.value)}
/>
<Button type="button" onClick={saveProxy} disabled={!loaded || savingProxy}>
保存
</Button>
</div>
<p className="text-muted-foreground text-xs">
独立出口代理,仅用于访问搜索端点(VPN/SOCKS 等)。与记录流量的 MITM 代理无关;网络不通时经此代理访问。
</p>
</div>
)}
{webSearch && (
<div className="flex items-center justify-between gap-4 border-t pt-4">
<p className="text-muted-foreground text-xs">
用当前配置(来源 + 代理 + Key)实际搜索一次「test」,验证是否可用。
</p>
<Button
type="button"
onClick={saveBraveKey}
disabled={!loaded || savingKey || braveKeyInput.trim() === ""}
variant="outline"
onClick={runTest}
disabled={!loaded || testing}
className="shrink-0"
>
保存
{testing ? "测试中…" : "测试搜索"}
</Button>
</div>
{braveNeedsKey && (
<p className="text-xs text-amber-500">
已选择 Brave 但尚未配置 Key —— 在保存 Key 之前,搜索工具不会启用。
</p>
)}
<p className="text-muted-foreground text-xs">
免费版额度约 2,000 次/月。前往 https://brave.com/search/api/ 获取 Key。
</p>
</div>
)}
)}
</CardContent>
</Card>
{webSearch && backend === "tavily" && (
<div className="flex flex-col gap-2">
<Label htmlFor="tavily-key" className="text-sm font-normal text-muted-foreground">
Tavily Search API Key
{tavilyKeySet && <span className="ml-2 text-xs text-emerald-500">已配置</span>}
</Label>
<div className="flex items-center gap-2">
<Input
id="tavily-key"
type="password"
autoComplete="off"
placeholder={tavilyKeySet ? "已配置(留空则不变)" : "输入 Tavily API Key(tvly-…)"}
value={tavilyKeyInput}
disabled={!loaded || savingTavilyKey}
onChange={(e) => setTavilyKeyInput(e.target.value)}
/>
<Button
type="button"
onClick={saveTavilyKey}
disabled={!loaded || savingTavilyKey || tavilyKeyInput.trim() === ""}
>
保存
</Button>
</div>
{webSearch && backend === "tavily" && !tavilyKeySet && (
<p className="text-xs text-amber-500">
已选择 Tavily 但尚未配置 Key —— 在保存 Key 之前,搜索工具不会启用。
</p>
)}
<p className="text-muted-foreground text-xs">
前往 https://tavily.com 注册并获取 API Key。
</p>
</div>
)}
{webSearch && (
<div className="flex flex-col gap-2">
<Label htmlFor="ws-proxy" className="text-sm font-normal text-muted-foreground">
出口代理(可选)
</Label>
<div className="flex items-center gap-2">
<Input
id="ws-proxy"
autoComplete="off"
placeholder="http://host:port 或 socks5://host:port(留空=直连)"
value={proxyInput}
disabled={!loaded || savingProxy}
onChange={(e) => setProxyInput(e.target.value)}
/>
<Button type="button" onClick={saveProxy} disabled={!loaded || savingProxy}>
保存
</Button>
</div>
<p className="text-muted-foreground text-xs">
独立出口代理,仅用于访问搜索端点(VPN/SOCKS 等)。与记录流量的 MITM 代理无关;网络不通时经此代理访问。
</p>
</div>
)}
{webSearch && (
<div className="flex items-center justify-between gap-4 border-t pt-4">
<p className="text-muted-foreground text-xs">
用当前配置(来源 + 代理 + Key)实际搜索一次「test」,验证是否可用。
</p>
<Button type="button" variant="outline" onClick={runTest} disabled={!loaded || testing} className="shrink-0">
{testing ? "测试中…" : "测试搜索"}
<Card className="mb-4 break-inside-avoid md:mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<RadioTowerIcon className="size-4" />
自定义脚本 · Python 解释器
</CardTitle>
<CardDescription>
自定义 <b>script</b> 类型工具用它跑 Python。开机会自动检测(python3 优先);此处可手填 venv /
特定版本的绝对路径,留空则运行时自动检测。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<Input
className="font-mono text-sm"
placeholder="/usr/bin/python3(留空=自动检测)"
value={pyInterp}
disabled={!loaded || saving}
onChange={(e) => setPyInterp(e.target.value)}
/>
<Button variant="outline" onClick={detectPython} disabled={!loaded || saving}>
重新检测
</Button>
<Button onClick={savePython} disabled={!loaded || saving}>
保存
</Button>
</div>
)}
</CardContent>
</Card>
</CardContent>
</Card>
<Card className="max-w-2xl">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<RadioTowerIcon className="size-4" />
自定义脚本 · Python 解释器
</CardTitle>
<CardDescription>
自定义 <b>script</b> 类型工具用它跑 Python。开机会自动检测(python3 优先);此处可手填 venv /
特定版本的绝对路径,留空则运行时自动检测。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<Input
className="font-mono text-sm"
placeholder="/usr/bin/python3(留空=自动检测)"
value={pyInterp}
disabled={!loaded || saving}
onChange={(e) => setPyInterp(e.target.value)}
/>
<Button variant="outline" onClick={detectPython} disabled={!loaded || saving}>
重新检测
</Button>
<Button onClick={savePython} disabled={!loaded || saving}>
保存
</Button>
</div>
</CardContent>
</Card>
<Card className="mb-4 break-inside-avoid md:mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<CpuIcon className="size-4" />
工作并发 · Work Agent 数
</CardTitle>
<CardDescription>
每个任务并发运行的工作 agent 数量(默认 3)。数值越大并发探测越多、消耗也越高。修改后
<b>对之后启动的任务生效</b>,正在运行的任务不受影响。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<Input
type="number"
min={1}
className="w-32 font-mono text-sm"
placeholder="3"
value={workers}
disabled={!loaded || savingWorkers}
onChange={(e) => setWorkers(e.target.value)}
/>
<Button onClick={saveWorkers} disabled={!loaded || savingWorkers}>
保存
</Button>
</div>
</CardContent>
</Card>
<Card className="max-w-2xl">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<CpuIcon className="size-4" />
工作并发 · Work Agent 数
</CardTitle>
<CardDescription>
每个任务并发运行的工作 agent 数量(默认 3)。数值越大并发探测越多、消耗也越高。修改后<b>对之后启动的任务生效</b>,正在运行的任务不受影响。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<Input
type="number"
min={1}
className="w-32 font-mono text-sm"
placeholder="3"
value={workers}
disabled={!loaded || savingWorkers}
onChange={(e) => setWorkers(e.target.value)}
/>
<Button onClick={saveWorkers} disabled={!loaded || savingWorkers}>
保存
</Button>
</div>
</CardContent>
</Card>
<Card className="mb-4 break-inside-avoid md:mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<KeyboardIcon className="size-4" />
会话输入框发送键位
</CardTitle>
<CardDescription>
对话页与任务详情的主 Agent 会话输入框共用此设置,选择后立即生效、无需保存。
<br />
该偏好<b>只存在本浏览器</b>,不随账号同步,换浏览器或清理站点数据后需重新设置。
</CardDescription>
</CardHeader>
<CardContent className="flex items-center justify-between gap-4">
<Label htmlFor="chat-send-mode" className="text-sm font-normal text-muted-foreground">
发送方式
</Label>
<Select value={sendMode} onValueChange={(v) => setChatSendMode(v as ChatSendMode)}>
<SelectTrigger id="chat-send-mode" className="w-72">
<SelectValue />
</SelectTrigger>
<SelectContent>
{CHAT_SEND_MODE_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</CardContent>
</Card>
</div>
</div>
);
}