import { useEffect, useRef, useState } from 'react'; import { Activity, Check, CircleHelp, KeyRound, Layers3, Plus, Power, RefreshCw, Route, Server, Settings2 } from 'lucide-react'; import { api, downloadArtifact } from './api'; import type { Config, ModelSelection } from './types'; import './ModelCenter.css'; type Connection = { id: string; name: string; brand: string; protocol: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean; requiresKey: boolean; streaming?: boolean; capabilityDeclarations?: Record; capabilities?: Record; capabilityEvidence?: { checkedAt: string }; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; savedCredential?: { status: string }; health: { state: string; reason?: string; cooldownUntil?: number } }; type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; maxAttempts: number; revision?: number; queueTimeoutMs: number }; type Attempt = { id: string; connectionId: string; poolId: string | null; model: string; protocol?: string; streaming?: boolean; rejections?: { connectionName: string; capability: string; reason: string }[]; status: string; startedAt: string; ordinal: number; usageStatus: string; reason?: string; taskId?: string; sessionId?: string; runId: string; requestArtifactId?: string; responseArtifactId?: string; responseSha256?: string; responseRedacted?: boolean; stream?: { bytes: number; capturedBytes?: number; frames: number; sha256: string; terminal: boolean }; usage?: { prompt_tokens?: number; completion_tokens?: number } }; type ImportRecord = { id: string; source: string; path: string; enabled: boolean; lastCheckedAt?: string; lastSyncedAt?: string; lastError?: string; lastResult?: { imported?: number; conflicts?: string[] } }; type Center = { revision: number; selected: { type: string; id: string }; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: Attempt[]; waiting: number }; type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[]; artifacts?: { offset: number; checked: number; total: number; remaining: number; olderOffset: number | null; newerOffset: number | null; results: { id: string; passed: boolean; error?: string }[] } }; type SavedCredential = { id: string; name: string; revision: number; status: string; enabled?: boolean; savedAt?: string; message: string }; type CredentialView = { supported: boolean; unavailable: boolean; connections: SavedCredential[]; scope: string }; const savedStates: Record = { not_saved: '仅本次内存', saved: '本机加密保存', disabled: '关闭自动加载', source_changed: '配置已变化', decrypt_failed: '无法解密', user_mismatch: '用户不匹配', directory_mismatch: '目录不匹配', unavailable: '保存登记不可用' }; const states: Record = { configured: '已配置', needs_key: '待填凭据', disabled: '已停用', needs_attention: '需要处理', cooling: '冷却中', completed: '收到响应', failed: '失败', running: '请求中', unknown: '结果待核对', interrupted: '已中断', rejected: '能力不匹配', passed: '通过', attention: '待配置' }; const initial = { name: '', brand: '自定义', protocol: 'chat-completions', streaming: false, capabilityDeclarations: { text: 'supported', tools: 'supported', streaming: 'unknown', vision: 'unknown', audio: 'unknown' } as Record, model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, contextLimit: 16000, maxOutputTokens: 2048, concurrency: 1 }; const capabilityLabels: Record = { text: '文本', tools: '工具', streaming: '流式', vision: '视觉', audio: '语音' }; const capabilityStates: Record = { protocol_declared: '声明支持', verified: '已验证', unknown: '待验证', unsupported: '不支持' }; const emptyPool: Pool = { name: '', members: [], strategy: 'round-robin', sticky: true, maxAttempts: 3, queueTimeoutMs: 15000 }; export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Config, selection?: ModelSelection) => void; onLegacy: () => void; busy: boolean }) { const [view, setView] = useState
(null); const [tab, setTab] = useState('connections'); const [draft, setDraft] = useState(initial); const [editing, setEditing] = useState(false), [key, setKey] = useState(''); const [persistKey, setPersistKey] = useState(false), [persistImports, setPersistImports] = useState(false); const [credentialView, setCredentialView] = useState(null), [credentialKey, setCredentialKey] = useState(''), [credentialTarget, setCredentialTarget] = useState(''); const [pool, setPool] = useState(emptyPool), [poolEditing, setPoolEditing] = useState(false); const [working, setWorking] = useState(false), [notice, setNotice] = useState(''); const [probeScopes, setProbeScopes] = useState>({}); const [operations, setOperations] = useState(null), [autoInspect, setAutoInspect] = useState(false); const [importPath, setImportPath] = useState(''), [importSource, setImportSource] = useState('ccswitch'); const [preview, setPreview] = useState<{ id: string; entries: { id: string; name: string; model: string; baseUrl: string; hasKey: boolean }[]; notices: string[] } | null>(null); const [discovery, setDiscovery] = useState<{ source: string; path: string; available: boolean; supported: boolean; detail?: string }[]>([]); const alive = useRef(true), generation = useRef(0); const tabsRef = useRef(null); async function refresh() { const marker = ++generation.current; const result = await api
('/model-center'); if (alive.current && marker === generation.current) setView(result); } async function act(action: () => Promise) { setWorking(true); setNotice(''); try { await action(); if (alive.current) { await refresh(); if (credentialView) await refreshCredentials(); } } catch (cause) { if (alive.current) setNotice(cause instanceof Error ? cause.message : '操作未完成,请刷新核对。'); } finally { if (alive.current) setWorking(false); } } async function inspect(offset?: number) { const value = await api('/operations' + (offset === undefined ? '' : '?artifactOffset=' + offset)); if (alive.current) setOperations(value); } async function refreshCredentials() { const value = await api('/model-center/credentials'); if (alive.current) setCredentialView(value); } useEffect(() => { alive.current = true; void refresh().catch(error => { if (alive.current) setNotice(error.message); }); return () => { alive.current = false; generation.current++; }; }, []); useEffect(() => { if (!autoInspect || tab !== 'operations') return; const timer = window.setInterval(() => { void inspect().catch(error => { if (alive.current) setNotice(error.message); }); }, 30000); return () => window.clearInterval(timer); }, [autoInspect, tab]); useEffect(() => { setCredentialKey(''); if (tab === 'credentials') void refreshCredentials().catch(error => { if (alive.current) setNotice(error.message); }); }, [tab]); useEffect(() => { const ensureVisible = () => { const nav = tabsRef.current, button = nav?.querySelector('button[aria-current]'); if (!nav || !button) return; const area = nav.getBoundingClientRect(), target = button.getBoundingClientRect(), start = target.left - area.left; if (start < 0) nav.scrollLeft += start - 12; else if (start + target.width > nav.clientWidth) nav.scrollLeft += start + target.width - nav.clientWidth + 12; }; const frame = requestAnimationFrame(ensureVisible); window.addEventListener('resize', ensureVisible); return () => { cancelAnimationFrame(frame); window.removeEventListener('resize', ensureVisible); }; }, [tab]); const selected = view?.selected; const selectionName = selected?.type === 'pool' ? view?.pools.find(value => value.id === selected.id)?.name : view?.connections.find(value => value.id === selected?.id)?.name; const locked = working || busy; return
MODEL CONTROL

连接有序,执行有据。

统一管理模型服务、调度和每次真实请求。

当前路由{selectionName || '原模型连接'}{view?.waiting ?? 0} 等待
{notice &&
{notice}
} {busy &&

有任务正在执行;连接可停用,其他配置请在任务结束后修改。

} {!view ?

正在读取实际连接状态…

:
{tab === 'connections' && <>

模型连接

默认仅在本次宿主内存中使用;可在凭据保存中选择本机加密。已配置与调用通过分别显示。

{view.connections.map(value =>

{value.name}

{value.brand} · {value.protocol === 'responses' ? 'Responses' : 'Chat Completions'}{value.streaming ? ' · 流式开启' : ''}
{states[value.status]}
模型
{value.model || '尚未填写'}
接口
{value.baseUrl}
凭据
{value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}
请求 / 容量
{value.activeRequests} 在途 · 并发 {value.concurrency} · 上下文 {value.contextLimit.toLocaleString()}
{Object.entries(capabilityLabels).map(([key, title]) => {title}:{capabilityStates[value.capabilities?.[key] ?? 'unknown']})}
{value.health.reason &&

{value.health.reason}{!!value.health.cooldownUntil && value.health.cooldownUntil > Date.now() && ' · 冷却至 ' + new Date(value.health.cooldownUntil).toLocaleTimeString()}

}
{value.id !== 'legacy-default' && }
)}
{editing &&
{ event.preventDefault(); void act(async () => { await api('/model-center/connections', { ...draft, ...(key ? { apiKey: key } : {}), ...(persistKey ? { persistKey: true } : {}) }); if (alive.current) { setKey(''); setEditing(false); setNotice(persistKey ? '连接与本机加密凭据已一起保存。' : '连接已保存。'); } }); }}>

{draft.id ? '编辑模型连接' : '添加模型连接'}

品牌仅用于分类,请选择服务实际提供的协议。能力检测会发起一次模型请求,可能产生费用;使用合成输入,不发送项目文件。文本检测不能证明工具或视觉能力。配置变化后需重新检测并核对凭据保存状态。

} } {tab === 'credentials' &&

本机加密凭据

使用当前Windows用户加密。保存后的 Key 不会回显或包含在导出中。

{!credentialView ?

正在核对本机保存状态…

: <>

只保存这次填写或确认导入的凭据。临时连接在宿主退出后需要重新填写。

{credentialView.unavailable &&

原保存登记格式不可用;原数据保留,请核对后修复。

}
{ event.preventDefault(); void act(async () => { const target = view.connections.find(value => value.id === (credentialTarget || view.connections[0]?.id)); if (!target) return; const result = await api<{ config: Config }>('/model-center/credentials', { id: target.id, revision: target.revision, action: 'save', apiKey: credentialKey }); if (alive.current) { setCredentialKey(''); setNotice('本机加密凭据已保存;宿主重启后按原连接身份加载。'); onConfig(result.config); } }); }}>

只保存这次新填的凭据。不同用户、目录或连接配置无法加载原保存块。

{credentialView.connections.map(value =>

{value.name}

{savedStates[value.status] || value.status}

{value.message}

{value.savedAt &&

保存于 {new Date(value.savedAt).toLocaleString()}

}
{value.status !== 'not_saved' && <> }
)}

删除本机保存保留本次内存连接;清除该连接凭据会同时移除本机保存与内存凭据。

}
} {tab === 'pools' && <>

模型池

按能力、凭据、健康和并发选择成员,切换保留已完成操作。

{!view.pools.length &&

添加多个连接后建立模型池,设置轮询与故障切换规则。

} {view.pools.map(value =>

{value.name}

{value.strategy === 'weighted' ? '权重轮询' : '顺序轮询'} · {value.members.length} 个成员 · {value.maxAttempts} 次尝试上限 · {value.sticky ? '运行内保持连接' : '每次请求重新选择'}

{value.members.map(member => {view.connections.find(connection => connection.id === member.connectionId)?.name} ×{member.weight})}
)} {poolEditing &&
{ event.preventDefault(); void act(async () => { await api('/model-center/pools', pool); if (alive.current) setPoolEditing(false); }); }}>

模型池规则

模型池成员与权重{view.connections.map(connection => { const member = pool.members.find(value => value.connectionId === connection.id); return ; })}
} } {tab === 'attempts' && <>

请求账本

最近100次物理请求;最多保存1000次。未知用量保持未知。

{view.attempts.length} 条记录
{!view.attempts.length &&

当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。

}
{view.attempts.map(value =>
{states[value.status]}{value.model}

{view.connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol === 'responses' ? 'Responses' : value.protocol ? 'Chat Completions' : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}

Run {value.runId}{value.stream &&

{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}

原流 SHA256 {value.stream.sha256}{value.responseSha256 && 工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}}{value.sessionId && value.responseArtifactId && }
}{value.reason &&

{value.reason}

}{!!value.rejections?.length &&

{value.rejections.map(item => item.connectionName + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}

}
)}
} {tab === 'imports' && <>

已有配置导入

先预览来源和模型,再导入。原客户端配置保持原样。

{view.imports.length > 0 && <>

已登记来源

{view.imports.map(value =>
{value.source}{value.path}{value.enabled ? '每分钟检查' : '自动同步已关闭'}{value.lastCheckedAt &&

最近检查 {new Date(value.lastCheckedAt).toLocaleString()}

}{value.lastError &&

{value.lastError}

}{!!value.lastResult?.conflicts?.length &&

有 {value.lastResult.conflicts.length} 项与手动修改冲突,已保留工作台中的修改。

}
)}} {discovery.map(value =>
{value.source}{value.path || '当前版本尚无可发现的配置路径'}{value.available ? value.supported ? '可预览' : '当前不支持' : '未发现'}{value.detail &&

{value.detail}

}
)}
{preview &&

本次预览

{preview.entries.map(value =>

{value.name} · {value.model} · {value.baseUrl} · {value.hasKey ? '含临时凭据' : '无凭据'}

)}{preview.notices.map((value, index) =>

{value}

)}
} } {tab === 'operations' && <>

运行巡检

核对宿主、任务、来源与数据,按页检查历史工件。

{operations ? <>

{new Date(operations.checkedAt).toLocaleString()} · v{operations.version} · {operations.activeTasks} 活动任务 · {operations.queue} 排队

{operations.checks.map(value =>
{states[value.status] || value.status}

{value.title}

{value.detail}

)}
{operations.artifacts &&

本页核对 {operations.artifacts.checked} 项 · 全部 {operations.artifacts.total} 项 · 本页未覆盖 {operations.artifacts.remaining} 项

{operations.artifacts.results.filter(value => !value.passed).map(value =>

工件 {value.id}:{value.error}

)}
}

{operations.scope}

:

执行一次本地检查,查看实际结果与检查范围。

}}
}
; }