import { App, Button, Form, Input, InputNumber, Modal, Select, Switch } from "antd";
import type { FormInstance } from "antd";
import type { ColumnsType } from "antd/es/table";
import { Pencil, Plus, Power, Search, Trash2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useSearchParams } from "react-router";
import { ChannelHeadersEditor, validateChannelHeaders } from "@/components/channel-headers-editor";
import { PaginationBar } from "@/components/layout/workspace-page";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { desktopLocalChannelFormState, desktopLocalChannelPayloadValue, DESKTOP_LOCAL_CHANNEL_EXAMPLE_BASE_URL } from "@/lib/desktop-local-channel";
import { refreshSystemChannels } from "@/lib/user-session";
import { createAdminChannel, deleteAdminChannel, listAdminChannels, updateAdminChannel } from "@/services/api/auth";
import { type ChannelHeader, type ModelChannel } from "@/stores/use-config-store";
import { useUserStore } from "@/stores/use-user-store";
import { useAdminContext } from "../admin-context";
import { AdminPageFrame } from "../components/admin-shell";
import { AdminDataTable, AdminRowActions, AdminStatusBadge, AdminTableEmpty, configuredSecretText } from "../components/admin-ui";
import { ChannelModelManager } from "../components/channel-model-manager";
import { ChannelOrderDialog } from "../components/channel-order-dialog";
type ChannelFormValues = {
name: string;
publicAlias?: string;
baseUrl: string;
allowLocalChannel?: boolean;
apiKey?: string;
secretKey?: string;
headers?: ChannelHeader[];
useGlobalConcurrency?: boolean;
concurrencyLimit?: number;
enabled?: boolean;
};
export function adminLocalChannelFormOwner(desktopLocalChannelsEnabled: boolean, hostname: string, requestedAllowLocalChannel?: boolean) {
const state = desktopLocalChannelFormState(desktopLocalChannelsEnabled, hostname, requestedAllowLocalChannel);
return { ...state, payloadValue: desktopLocalChannelPayloadValue(desktopLocalChannelsEnabled, hostname, requestedAllowLocalChannel) };
}
export function AdminLocalChannelSwitch({ visible, checked, onChange }: { visible: boolean; checked: boolean; onChange: (checked: boolean) => void }) {
if (!visible) return null;
return (
);
}
export function AdminLocalChannelFields({ visible, checked, form }: { visible: boolean; checked: boolean; form: Pick, "setFieldValue"> }) {
return (
<>
form.setFieldValue("allowLocalChannel", value)} />
>
);
}
export function adminChannelSavePayload(values: ChannelFormValues, desktopLocalChannelsEnabled: boolean, hostname: string) {
return {
name: values.name.trim(),
publicAlias: values.publicAlias?.trim() || "",
baseUrl: values.baseUrl.trim(),
allowLocalChannel: adminLocalChannelFormOwner(desktopLocalChannelsEnabled, hostname, values.allowLocalChannel).payloadValue,
apiKey: values.apiKey?.trim() || "",
secretKey: values.secretKey?.trim() || "",
headers: values.headers || [],
useGlobalConcurrency: values.useGlobalConcurrency !== false,
concurrencyLimit: values.useGlobalConcurrency === false ? values.concurrencyLimit : undefined,
enabled: values.enabled !== false,
};
}
export default function ChannelsPage() {
const { message, modal } = App.useApp();
const { reloadReferences } = useAdminContext();
const [searchParams, setSearchParams] = useSearchParams();
const keyword = searchParams.get("filter") || "";
const status = normalizeStatus(searchParams.get("status"));
const page = positiveInt(searchParams.get("page"), 1);
const pageSize = normalizePageSize(searchParams.get("pageSize"));
const debouncedKeyword = useDebouncedValue(keyword);
const [channels, setChannels] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
const [drawerOpen, setDrawerOpen] = useState(false);
const [editingChannel, setEditingChannel] = useState(null);
const [saving, setSaving] = useState(false);
const [managingChannel, setManagingChannel] = useState(null);
const requestSequence = useRef(0);
const [form] = Form.useForm();
const useGlobalConcurrency = Form.useWatch("useGlobalConcurrency", form) !== false;
const requestedAllowLocalChannel = Form.useWatch("allowLocalChannel", form) === true;
const desktopLocalChannelsEnabled = useUserStore((state) => state.features.desktopLocalChannelsEnabled);
const desktopLocalChannelHostname = typeof window === "undefined" ? "" : window.location.hostname;
const desktopLocalChannelControl = adminLocalChannelFormOwner(desktopLocalChannelsEnabled, desktopLocalChannelHostname, requestedAllowLocalChannel);
const allowLocalChannel = desktopLocalChannelControl.checked;
const showDesktopLocalChannelControl = desktopLocalChannelControl.visible;
const hasFilters = Boolean(keyword || status !== "all");
const updateUrl = (patch: Record, replace = false) => {
const next = new URLSearchParams(searchParams);
Object.entries(patch).forEach(([key, value]) => {
const isDefault = (key === "filter" && value === "") || (key === "status" && value === "all") || (key === "page" && value === 1) || (key === "pageSize" && value === 20);
if (isDefault) next.delete(key);
else next.set(key, String(value));
});
setSearchParams(next, { replace });
};
const reload = async () => {
const sequence = ++requestSequence.current;
setLoading(true);
try {
const result = await listAdminChannels({ keyword: debouncedKeyword || undefined, status: status === "all" ? undefined : status, page, pageSize });
if (sequence !== requestSequence.current) return;
setChannels(result.channels);
setTotal(result.total);
if (result.total > 0 && result.channels.length === 0 && page > 1) updateUrl({ page: 1 }, true);
} catch (error) {
if (sequence === requestSequence.current) message.error(error instanceof Error ? error.message : "读取渠道列表失败");
} finally {
if (sequence === requestSequence.current) setLoading(false);
}
};
useEffect(() => {
void reload();
}, [debouncedKeyword, status, page, pageSize]);
const syncChannels = async () => {
await reloadReferences();
try {
await refreshSystemChannels();
} catch (error) {
message.warning(error instanceof Error ? `后台已保存,但配置同步失败:${error.message}` : "后台已保存,但配置同步失败,请稍后重新打开配置");
}
};
const openDrawer = (channel?: ModelChannel) => {
setEditingChannel(channel || null);
form.resetFields();
form.setFieldsValue(
channel
? {
name: channel.name,
baseUrl: channel.baseUrl,
allowLocalChannel: adminLocalChannelFormOwner(desktopLocalChannelsEnabled, desktopLocalChannelHostname, channel.allowLocalChannel).checked,
apiKey: "",
secretKey: "",
headers: channel.headers || [],
useGlobalConcurrency: !channel.concurrencyLimit,
concurrencyLimit: channel.concurrencyLimit || undefined,
enabled: channel.enabled !== false,
}
: { name: "", baseUrl: "", allowLocalChannel: false, apiKey: "", secretKey: "", headers: [], useGlobalConcurrency: true, concurrencyLimit: undefined, enabled: true },
);
setDrawerOpen(true);
form.setFieldsValue({ publicAlias: channel?.publicAlias || "" });
};
const closeDrawer = () => {
if (saving) return;
if (!form.isFieldsTouched()) {
setDrawerOpen(false);
return;
}
modal.confirm({ title: "放弃渠道修改?", content: "尚未保存的连接信息将丢失。", okText: "放弃修改", cancelText: "继续编辑", okButtonProps: { danger: true }, onOk: () => setDrawerOpen(false) });
};
const save = async () => {
const values = await form.validateFields();
const headerError = validateChannelHeaders(values.headers);
if (headerError) {
message.error(headerError);
return;
}
if (!editingChannel && !values.apiKey?.trim()) {
message.error("请填写 API Key 或 Access Key");
return;
}
setSaving(true);
try {
const payload = adminChannelSavePayload(values, desktopLocalChannelsEnabled, desktopLocalChannelHostname);
await (editingChannel ? updateAdminChannel(editingChannel.id, payload) : createAdminChannel(payload));
await syncChannels();
setDrawerOpen(false);
form.resetFields();
await reload();
message.success(editingChannel ? "系统渠道已更新" : "系统渠道已创建");
} catch (error) {
message.error(error instanceof Error ? error.message : "保存系统渠道失败");
} finally {
setSaving(false);
}
};
const toggleChannel = async (channel: ModelChannel) => {
try {
await updateAdminChannel(channel.id, { enabled: channel.enabled === false });
await syncChannels();
await reload();
message.success(channel.enabled === false ? "系统渠道已启用" : "系统渠道已停用");
} catch (error) {
message.error(error instanceof Error ? error.message : "更新系统渠道失败");
}
};
const removeChannel = async (channel: ModelChannel) => {
try {
await deleteAdminChannel(channel.id);
await syncChannels();
await reload();
message.success("系统渠道已删除");
} catch (error) {
message.error(error instanceof Error ? error.message : "删除系统渠道失败");
}
};
const columns: ColumnsType = [
{
title: "渠道",
dataIndex: "name",
render: (_, channel) => (
{channel.name}
{channel.baseUrl}
),
},
{ title: "前台名称", width: 160, render: (_, channel) => {channel.publicAlias || channel.name} },
{ title: "模型", dataIndex: "models", width: 100, align: "center", render: (models: string[]) => `${models?.length || 0} 个` },
{ title: "最大并发", dataIndex: "concurrencyLimit", width: 120, align: "center", render: (value: number) => (value > 0 ? value : 跟随系统) },
{ title: "凭证", width: 130, align: "center", render: (_, channel) => },
{ title: "状态", dataIndex: "enabled", width: 100, align: "center", render: (enabled) => },
{
title: "操作",
width: 250,
align: "center",
render: (_, channel) => (
setManagingChannel(channel) }}
actions={[
{ key: "edit", label: "编辑", icon: , onClick: () => openDrawer(channel) },
{
key: "toggle",
label: channel.enabled !== false ? "停用渠道" : "启用渠道",
icon: ,
danger: channel.enabled !== false,
confirm: {
title: channel.enabled !== false ? "停用这个系统渠道?" : "启用这个系统渠道?",
description: channel.enabled !== false ? "停用后新任务不会再使用该渠道,但仍会保留在列表中,可随时重新启用。" : "启用后,配置完整的模型会重新进入系统可用模型集合。",
okText: channel.enabled !== false ? "确认停用" : "确认启用",
},
onClick: () => toggleChannel(channel),
},
{
key: "delete",
label: "删除渠道",
icon: ,
danger: true,
confirm: { title: "删除这个系统渠道?", description: "删除后渠道及所属模型将不再显示,API Key 会被清除,历史账单和调用记录继续保留。该操作不能在页面恢复。", okText: "确认删除" },
onClick: () => removeChannel(channel),
},
]}
/>
),
},
];
if (managingChannel) {
return (
setManagingChannel(null)}
onChanged={async () => {
await syncChannels();
await reload();
}}
/>
);
}
return (
{
await syncChannels();
await reload();
}}
/>
} onClick={() => openDrawer()}>
新增系统渠道
}
>
}
value={keyword}
placeholder="搜索渠道名称、别名或地址"
onChange={(event) => updateUrl({ filter: event.target.value, page: 1 }, true)}
/>
}
toolbarFilters={
);
}
function positiveInt(value: string | null, fallback: number) {
const parsed = Number(value);
return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
}
function normalizePageSize(value: string | null) {
const parsed = positiveInt(value, 20);
return [20, 50, 100].includes(parsed) ? parsed : 20;
}
function normalizeStatus(value: string | null): "all" | "enabled" | "disabled" {
return value === "enabled" || value === "disabled" ? value : "all";
}
function channelSecretText(channel: ModelChannel) {
return channel.hasSecretKey ? "已配置,留空不修改" : "未配置";
}