agenthub/frontend/app/connect/page.tsx

570 lines
16 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"use client";
// 接入只有两类,向导也只有三步:选类型 → 选 Agent → 凭证。
//
// 类型只决定一件事:片段贴进哪一类 Agent(能装插件 / 配渠道的,还是只有一套 CLI、
// 旁边跑一个桥接进程的)。要填的东西两类一模一样 —— hub 的 IP+端口,加上 hub 签给
// 这台 Agent 的 ag_ 凭证。没有 hub id,也没有第二种令牌。
//
// 走到第 3 步就签:凭证和那段配置当场给出,可以重新签发。「完成」回到第 1 步。
// 下面「签发记录」是每一次签发的存档本身,一行一次:点开就是当时那把 token(明文)
// 和那段配置的原样。
import {
Bot,
Cable,
Check,
ChevronRight,
KeyRound,
ScrollText,
Server,
TerminalSquare,
} from "lucide-react";
import { useState } from "react";
import {
Badge,
CopyButton,
Dot,
Empty,
ErrorNote,
Field,
Input,
Panel,
PixelButton,
Select,
Spinner,
useToast,
} from "@/components/ui";
import { api } from "@/lib/api";
import { useAsync } from "@/lib/useAsync";
import type { DeployFile, DeployPlan, Issuance } from "@/lib/types";
/** 片段长什么样由 Agent 决定 —— 这是唯一还有区别的地方,凭证本身没有区别。 */
type AgentKind = "bridge" | "nanobot" | "dsh" | "claw";
type AccessType = "channel" | "bridge";
/** 一次签发的结果:凭证 + hub 渲染出来的那段配置。 */
interface Signed {
token: string;
plan: DeployPlan;
}
interface Target {
id: string;
label: string;
type: AccessType;
kind: AgentKind;
/** 建档写的 driver / connection_mode。 */
driver: string;
connectionMode: string;
/** 桥接类传给 bridge.py 的 --cli(适配器名)。 */
cli?: string;
icon: typeof Bot;
}
const TARGETS: Target[] = [
{
id: "dsh",
label: "DeepSeek Harness",
type: "channel",
kind: "dsh",
driver: "deepseek_harness",
connectionMode: "embedded",
icon: Server,
},
{
id: "nanobot",
label: "nanobot",
type: "channel",
kind: "nanobot",
driver: "nanobot",
connectionMode: "embedded",
icon: Bot,
},
{
id: "claw",
label: "OpenClaw",
type: "channel",
kind: "claw",
driver: "connector",
connectionMode: "connector",
icon: Cable,
},
{
id: "codex",
label: "codex",
type: "bridge",
kind: "bridge",
driver: "connector",
connectionMode: "connector",
cli: "codex",
icon: TerminalSquare,
},
{
id: "claude",
label: "claude",
type: "bridge",
kind: "bridge",
driver: "connector",
connectionMode: "connector",
cli: "claude",
icon: TerminalSquare,
},
{
id: "workbuddy",
label: "WorkBuddy",
type: "bridge",
kind: "bridge",
driver: "connector",
connectionMode: "connector",
cli: "workbuddy",
icon: Bot,
},
];
const TYPES: { id: AccessType; label: string; icon: typeof Bot }[] = [
{ id: "channel", label: "插件 / 渠道", icon: Cable },
{ id: "bridge", label: "桥接", icon: TerminalSquare },
];
const targetsIn = (type: AccessType) => TARGETS.filter((item) => item.type === type);
const KIND_LABEL: Record<AgentKind, string> = {
bridge: "桥接",
nanobot: "nanobot",
dsh: "DSH",
claw: "OpenClaw",
};
const asText = (exc: unknown) => (exc instanceof Error ? exc.message : String(exc));
/** 签发记录上的钟点:只在客户端拿到数据之后渲染,不必担心时区来回跳。 */
const clockOf = (iso: string) => {
const at = new Date(iso);
return Number.isNaN(at.getTime())
? "-"
: at.toLocaleString("zh-CN", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
};
function Code({ text }: { text: string }) {
return (
<div className="flex items-start gap-2">
<pre className="pixel-pre flex-1 whitespace-pre-wrap break-all">{text}</pre>
<CopyButton text={text} />
</div>
);
}
/** 一步一张卡:点中即选中。 */
function ChoiceCard({
on,
title,
icon: Icon,
onClick,
}: {
on: boolean;
title: string;
icon: typeof Bot;
onClick: () => void;
}) {
return (
<button
type="button"
onClick={onClick}
className={"pixel-card flex-1 min-w-[190px] items-start" + (on ? " pixel-card--on" : "")}
>
<span className="flex w-full items-center gap-2">
<span className="pixel-badge">
<Icon size={14} />
</span>
<span className="min-w-0 flex-1 truncate text-[15px] font-semibold">{title}</span>
{on && (
<span className="pixel-badge pixel-badge--accent shrink-0">
<Dot tone="green" />
已选
</span>
)}
</span>
</button>
);
}
/** hub 渲染出来的文件,内容已经是真值。 */
function Snippet({ files }: { files: DeployFile[] }) {
return (
<div className="grid gap-2">
{files.map((file) => (
<div key={file.kind} className="grid gap-1">
<span className="pixel-title text-[13px]">{file.filename}</span>
<Code text={file.content} />
</div>
))}
</div>
);
}
/**
* 第 3 步:走到这里就已经签好了,只管看、重新签发、完成。
*
* 名字已在册时不把人堵死 —— 那通常就是同一台 Agent 再接一次,直接给原来那一行换一把
* 新的,不额外解释。
*/
function Credential({
signed,
busy,
error,
onReissue,
onBack,
onDone,
}: {
signed: Signed | null;
busy: boolean;
error: string;
onReissue: () => void;
onBack: () => void;
onDone: () => void;
}) {
return (
<div className="grid gap-2">
{error && <ErrorNote error={error} />}
{busy && !signed && <Spinner />}
{signed && (
<>
<div className="flex flex-wrap items-center gap-2">
<span className="pixel-title">agent_token</span>
<PixelButton
size="sm"
variant="ghost"
className="ml-auto"
disabled={busy}
onClick={onReissue}
>
<KeyRound size={12} />
重新签发
</PixelButton>
</div>
<Code text={signed.token} />
<Snippet files={signed.plan.files} />
</>
)}
<div className="flex flex-wrap gap-2">
<PixelButton onClick={onBack}>上一步</PixelButton>
<PixelButton variant="primary" disabled={busy || !signed} onClick={onDone}>
<Check size={14} />
完成
</PixelButton>
</div>
</div>
);
}
/** 桥接的落点参数:一个进程只服务一个目录、一档权限。 */
function BridgeFields({
workdir,
setWorkdir,
mode,
setMode,
}: {
workdir: string;
setWorkdir: (value: string) => void;
mode: string;
setMode: (value: string) => void;
}) {
return (
<>
<Field label="工作目录">
<Input
value={workdir}
placeholder="~/code/目标仓库"
onChange={(event) => setWorkdir(event.target.value)}
/>
</Field>
<Field label="权限">
<Select value={mode} onChange={(event) => setMode(event.target.value)}>
<option value="readonly">readonly 只读</option>
<option value="write">write 可改文件</option>
</Select>
</Field>
</>
);
}
const STEPS = ["选择类型", "选择 Agent", "生成凭证"] as const;
/** 步骤条:只能跳回已经走过的步骤,往前走要点「下一步」。 */
function Stepper({
step,
reached,
onJump,
}: {
step: number;
reached: number;
onJump: (step: number) => void;
}) {
return (
<ol className="flex flex-wrap items-center gap-2">
{STEPS.map((label, index) => {
const number = index + 1;
const current = number === step;
const done = number < step;
const clickable = number <= reached;
return (
<li key={label} className="flex items-center gap-2">
<button
type="button"
disabled={!clickable}
onClick={() => onJump(number)}
className={
"pixel-badge " +
(current ? "pixel-badge--accent " : "") +
(clickable ? "pixel-link " : "pixel-muted ")
}
>
{done ? <Check size={12} /> : <Dot tone={current ? "green" : "gray"} />}
{number} · {label}
</button>
{number < STEPS.length && <span className="pixel-muted">→</span>}
</li>
);
})}
</ol>
);
}
/** 一行一次签发:平时只有「签给谁、哪一类、什么时候」,点开才是那把 token 和那段配置。 */
function RecordRow({ row }: { row: Issuance }) {
const kind = row.kind as AgentKind;
return (
<details className="pixel-card group py-2.5">
<summary className="flex cursor-pointer flex-wrap items-center gap-2 text-[13px]">
<ChevronRight className="transition-transform group-open:rotate-90" size={14} />
<span className="pixel-mono font-semibold">{row.agent_name}</span>
<Badge tone="accent">{KIND_LABEL[kind] ?? row.kind}</Badge>
<span className="pixel-muted pixel-mono text-[12px]">{clockOf(row.created_at)}</span>
{!row.active && <Badge tone="gray">已失效</Badge>}
</summary>
<div className="grid gap-2">
{row.agent_token && <Code text={row.agent_token} />}
<Snippet files={row.files} />
</div>
</details>
);
}
/**
* 签发记录:每次签发由 hub 存一份完整的档(片段连 token 一起),
* 所以这里回看到的原样,跟当时屏幕上的一字不差。
*/
function Records({ nonce }: { nonce: number }) {
const records = useAsync(() => api.issuances(), [nonce]);
const rows = records.data ?? [];
return (
<Panel title="签发记录" icon={<ScrollText size={14} />}>
{records.error ? (
<ErrorNote error={records.error} />
) : rows.length ? (
<div className="grid gap-2">
{rows.map((row) => (
<RecordRow key={row.id} row={row} />
))}
</div>
) : (
<Empty title="还没有签发记录" />
)}
</Panel>
);
}
export default function ConnectPage() {
const toast = useToast();
const meta = useAsync(() => api.meta(), []);
const [step, setStep] = useState(1);
const [reached, setReached] = useState(1);
const [type, setType] = useState<AccessType>("channel");
const [target, setTarget] = useState<Target>(targetsIn("channel")[0]);
const [name, setName] = useState("");
const [workdir, setWorkdir] = useState("");
const [permission, setPermission] = useState("readonly");
const [signed, setSigned] = useState<Record<string, Signed>>({});
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [configured, setConfigured] = useState(0);
const agentName = name.trim() || target.id;
// 桥接的落点参数存在这一行的 config 里,hub 生成片段时把它们抬回片段,
// 所以存档里那条命令和当时贴出去的完全一致。
const landingSpec: Record<string, unknown> =
target.kind === "bridge"
? { cli: target.cli, workdir: workdir.trim() || "~/code/目标仓库", mode: permission }
: {};
const spec: Record<string, unknown> = { name: agentName, config: landingSpec };
const signature = target.id + "|" + JSON.stringify(spec);
const go = (next: number) => {
setStep(next);
setReached((current) => Math.max(current, next));
};
/** 名字已在册 = 同一台 Agent 再接一次,直接给原来那一行换一把新的凭证。 */
const ensureAgent = async () => {
try {
return await api.createAgent({
...spec,
driver: target.driver,
connection_mode: target.connectionMode,
issue_credential: true,
});
} catch (exc) {
if (!/already exists/i.test(asText(exc))) throw exc;
return api.issueCredential(agentName);
}
};
/** 第 3 步的凭证不是点出来的:走到这一步就签。 */
const sign = async () => {
setBusy(true);
setError("");
try {
const created = await ensureAgent();
const token = created.agent_token ?? "";
const plan = await api.deployPlan({
kinds: [target.kind],
agent_ref: created.id,
agent: spec,
agent_token: token,
record: true,
});
setSigned((current) => ({ ...current, [signature]: { token, plan } }));
} catch (exc) {
setError(asText(exc));
} finally {
setBusy(false);
}
};
const enter = (next: number) => {
if (next === 3 && !signed[signature] && !busy) void sign();
go(next);
};
const finish = () => {
setSigned((current) => {
const rest = { ...current };
delete rest[signature];
return rest;
});
setStep(1);
setReached(1);
setName("");
setConfigured((current) => current + 1);
toast("ok", "已签发 " + agentName);
};
/** 换类型时把 Agent 选项挪到那一档的第一项,否则会出现「桥接 + nanobot」这种自相矛盾的表单。 */
const pickType = (next: AccessType) => {
setType(next);
if (target.type !== next) setTarget(targetsIn(next)[0]);
};
return (
<div className="grid gap-3">
<div className="flex flex-wrap items-center gap-2">
<span className="pixel-muted pixel-mono text-[12px]">Hub 地址 {meta.data?.url || "-"}</span>
<CopyButton text={meta.data?.url ?? ""} />
</div>
<Panel title="接入向导" icon={<Cable size={14} />}>
<div className="grid gap-4">
<Stepper step={step} reached={reached} onJump={enter} />
{step === 1 && (
<section className="grid gap-2">
<div className="flex flex-wrap items-stretch gap-2">
{TYPES.map((item) => (
<ChoiceCard
key={item.id}
on={type === item.id}
title={item.label}
icon={item.icon}
onClick={() => pickType(item.id)}
/>
))}
</div>
<div className="flex flex-wrap gap-2">
<PixelButton variant="primary" onClick={() => go(2)}>
下一步
</PixelButton>
</div>
</section>
)}
{step === 2 && (
<section className="grid gap-2">
<div className="flex flex-wrap items-stretch gap-2">
{targetsIn(type).map((item) => (
<ChoiceCard
key={item.id}
on={target.id === item.id}
title={item.label}
icon={item.icon}
onClick={() => setTarget(item)}
/>
))}
</div>
<div
className={
"grid gap-2 " +
(target.kind === "bridge"
? "md:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)_150px]"
: "md:grid-cols-[minmax(0,1fr)]")
}
>
<Field label="Agent 名字">
<Input
value={name}
placeholder={target.id}
onChange={(event) => setName(event.target.value)}
/>
</Field>
{target.kind === "bridge" && (
<BridgeFields
workdir={workdir}
setWorkdir={setWorkdir}
mode={permission}
setMode={setPermission}
/>
)}
</div>
<div className="flex flex-wrap gap-2">
<PixelButton onClick={() => go(1)}>上一步</PixelButton>
<PixelButton variant="primary" onClick={() => enter(3)}>
下一步
</PixelButton>
</div>
</section>
)}
{step === 3 && (
<Credential
signed={signed[signature] ?? null}
busy={busy}
error={error}
onReissue={() => void sign()}
onBack={() => go(2)}
onDone={finish}
/>
)}
</div>
</Panel>
<Records nonce={configured} />
</div>
);
}