Add runtime provider controls and searchable AI routing
CI / verify (push) Has been cancelled
CI / publish (push) Has been cancelled

Manage provider keys at runtime, route current-information questions through server-side search with safe fallback, and scope OOBE usage claims to grants.
This commit is contained in:
Rocky
2026-08-22 16:33:17 +08:00
parent f8fa93dc48
commit 9fb947aa7d
43 changed files with 2079 additions and 80 deletions
@@ -0,0 +1,229 @@
import { KeyRound, RefreshCw, ServerCog } from "lucide-react";
import { useCallback, useEffect, useState, type FormEvent } from "react";
import { toast } from "sonner";
import { adminApi, ApiError } from "../../api/client";
import type {
ManagedProviderId,
ManagedProviderOverview,
ManagedProviderStatus,
} from "../../api/types";
import {
Badge,
Button,
Card,
ErrorState,
Input,
LoadingState,
PageHeader,
} from "../../components/primitives";
import { formatDateTime } from "../../lib/format";
const PROVIDERS: Array<{
id: ManagedProviderId;
name: string;
description: string;
}> = [
{
id: "deepseek",
name: "DeepSeek",
description: "用于润色、AI 和 Agent 等托管文本能力。",
},
{
id: "volcengine",
name: "火山引擎",
description: "用于托管语音识别能力,仅替换 API Key。",
},
];
export function ProvidersPage() {
const [overview, setOverview] = useState<ManagedProviderOverview>();
const [loading, setLoading] = useState(true);
const [error, setError] = useState<unknown>();
const load = useCallback(async () => {
setLoading(true);
setError(undefined);
try {
setOverview(await adminApi.providers());
} catch (cause) {
setError(cause);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
}, [load]);
const updateStatus = useCallback((updated: ManagedProviderStatus) => {
setOverview((current) => {
if (!current) return current;
const providers = current.providers.filter(
(item) => item.providerId !== updated.providerId,
);
return { providers: [...providers, updated] };
});
}, []);
if (loading) return <LoadingState label="加载 Provider 配置" />;
if (error || !overview) return <ErrorState error={error} retry={() => void load()} />;
return (
<div className="space-y-6">
<PageHeader
eyebrow="Managed Providers"
title="Provider 配置"
description="替换托管网关使用的上游 API Key。新配置只影响之后开始的请求,现有密钥不会返回浏览器。"
actions={
<Button variant="secondary" onClick={() => void load()}>
<RefreshCw className="size-4" aria-hidden />
</Button>
}
/>
<Card className="border-warning/25 bg-warning-soft/30 p-5 text-sm leading-6 text-foreground sm:p-6">
<div className="flex gap-3">
<span className="mt-0.5 grid size-9 shrink-0 place-items-center rounded-xl bg-warning-soft text-warning">
<KeyRound className="size-4" aria-hidden />
</span>
<p>
Key Key
</p>
</div>
</Card>
<div className="grid gap-5 xl:grid-cols-2">
{PROVIDERS.map((provider) => (
<ProviderCard
key={provider.id}
providerId={provider.id}
name={provider.name}
description={provider.description}
status={overview.providers.find((item) => item.providerId === provider.id)}
onUpdated={updateStatus}
/>
))}
</div>
</div>
);
}
function ProviderCard({
providerId,
name,
description,
status,
onUpdated,
}: {
providerId: ManagedProviderId;
name: string;
description: string;
status?: ManagedProviderStatus;
onUpdated: (status: ManagedProviderStatus) => void;
}) {
const [apiKey, setApiKey] = useState("");
const [saving, setSaving] = useState(false);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const normalized = apiKey.trim();
if (!validApiKey(normalized)) {
toast.error("API Key 必须为 1512 个字符,且不能包含换行");
return;
}
if (!window.confirm(`确定替换 ${name} API Key?保存后,新请求将立即使用该 Key。`)) {
return;
}
setSaving(true);
try {
const updated = await adminApi.updateProviderApiKey(providerId, {
apiKey: normalized,
});
setApiKey("");
onUpdated(updated);
toast.success(`${name} API Key 已替换`);
} catch (error) {
toast.error(error instanceof ApiError ? error.message : `${name} API Key 替换失败`);
} finally {
setSaving(false);
}
}
return (
<Card className="overflow-hidden">
<div className="border-b border-border bg-surface-muted/35 p-5 sm:p-6">
<div className="flex items-start gap-3">
<span className="grid size-10 shrink-0 place-items-center rounded-xl bg-primary-soft text-primary">
<ServerCog className="size-5" aria-hidden />
</span>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-lg font-bold">{name}</h2>
<Badge tone={status?.configured ? "success" : "danger"}>
{status?.configured ? "已配置" : "未配置"}
</Badge>
</div>
<p className="mt-1 text-sm leading-6 text-muted">{description}</p>
</div>
</div>
<dl className="mt-5 grid gap-3 text-sm sm:grid-cols-2">
<StatusItem label="当前来源" value={sourceLabel(status)} />
<StatusItem
label="最后替换"
value={status?.updatedAt ? formatDateTime(status.updatedAt) : "随服务器部署"}
/>
</dl>
</div>
<form className="space-y-4 p-5 sm:p-6" onSubmit={(event) => void submit(event)}>
<label className="block text-sm font-semibold" htmlFor={`${providerId}-api-key`}>
<span className="mb-2 block">{name} API Key</span>
<Input
id={`${providerId}-api-key`}
type="password"
autoComplete="new-password"
maxLength={512}
value={apiKey}
onChange={(event) => setApiKey(event.target.value)}
placeholder={`输入新的 ${name} API Key`}
aria-describedby={`${providerId}-api-key-help`}
/>
</label>
<p id={`${providerId}-api-key-help`} className="text-xs leading-5 text-muted">
Key
</p>
<Button type="submit" loading={saving} disabled={!apiKey.trim()}>
<KeyRound className="size-4" aria-hidden />
{name} API Key
</Button>
</form>
</Card>
);
}
function StatusItem({ label, value }: { label: string; value: string }) {
return (
<div>
<dt className="text-xs font-semibold text-muted">{label}</dt>
<dd className="mt-1 font-medium text-foreground">{value}</dd>
</div>
);
}
function sourceLabel(status?: ManagedProviderStatus): string {
if (!status?.configured) return "尚未配置";
return status.source === "RUNTIME_OVERRIDE" ? "管理后台" : "环境变量";
}
function validApiKey(value: string): boolean {
return (
value.length >= 1 &&
value.length <= 512 &&
!value.includes("\n") &&
!value.includes("\r")
);
}