import { useEffect, useRef, useState } from 'react'; import { Activity, Check, CircleHelp, KeyRound, Layers3, Plus, Power, RefreshCw, Route, Server, Settings2 } from 'lucide-react'; import { api } from './api'; import type { Config, ModelSelection, ModelSnapshot, RuntimeFailure } from './types'; import './ModelCenter.css'; import { ModelRequestLedger, type ModelAttempt } from './ModelRequestLedger'; import { ModelWaitSettings, type WaitSettings } from './ModelWaitSettings'; import { NativeParameters, type NativeConnection } from './NativeParameters'; import { ModelErrorDetails } from './ModelErrorDetails'; import { ModelBudgetSettings } from './ModelBudgetSettings'; import { DEFAULT_MODEL_CAPACITY, messagesOutputSetting, modelCapacityDeclaration } from '../shared/contracts/model-capacity.mjs'; import { modelRequestUrl, protocolLabel } from '../shared/contracts/model-endpoint.mjs'; import { ModelNetworkDiagnostics } from './ModelNetworkDiagnostics'; import { ModelCatalog } from './ModelCatalog'; import type { CatalogModel } from '../shared/contracts/model-catalog.mjs'; import type { ModelSpecConnection } from '../shared/contracts/official-model-registry.mjs'; const previewUrl = (value: { protocol: string; baseUrl: string }) => { try { return modelRequestUrl(value); } catch { return '请填写有效的接口根地址'; } }; const upstreamCapacity = (value: ModelSpecConnection, field: 'contextLimit' | 'maxOutputTokens') => { const declaration = modelCapacityDeclaration(value, field); return declaration ? declaration.value.toLocaleString() + ' tokens · ' + (declaration.source === 'official_model_spec' ? ({ anthropic: 'Anthropic', openai: 'OpenAI', deepseek: 'DeepSeek' }[declaration.provider ?? ''] ?? '供应商') + ' 官方规格' : declaration.source === 'explicit_compatibility' ? '用户兼容覆盖' : '上游目录') : '本地无限制 · 由上游决定'; }; const protocolOutput = (value: ModelSpecConnection & { maxOutputTokens?: number }) => { const output = messagesOutputSetting(value); return output.source === 'upstream_optional' ? '默认省略 max_tokens · 官方 HTTP 可选字段' : 'max_tokens = ' + String(output.value) + ' · ' + ({ upstream_catalog: '上游目录最大值', official_model_spec: '官方同步输出规格', explicit_native: '显式原生参数', explicit_compatibility: '用户兼容覆盖' }[output.source] ?? '连接声明,最大值未验证'); }; type Connection = NativeConnection & { id: string; name: string; brand: string; protocol: string; parameterProfile?: string; messagesAuth?: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean; credentialSource?: { connectionId: string }; upstreamModel?: CatalogModel; requiresKey: boolean; modelIdentityPolicy?: string; modelIdentityAliases?: string[]; modelIdentityAliasSource?: string; nativeParameters?: Record; outputTokenField?: string; 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 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 }; waitSettings: WaitSettings; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: ModelAttempt[]; 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 = { reference: '共用上游凭据', 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 = { modelIdentityAliasesText: '', modelIdentityPolicy: 'record', modelIdentityAliases: [] as string[], modelIdentityAliasSource: '', 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, ...DEFAULT_MODEL_CAPACITY, 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, busy, runModel }: { onConfig: (value: Config, selection?: ModelSelection) => void; busy: boolean; runModel?: ModelSnapshot }) { const [view, setView] = useState
(null); const [runtimeConfig, setRuntimeConfig] = useState(null); const [tab, setTab] = useState('connections'); const [draft, setDraft] = useState; outputTokenField?: string }>(initial); const [editing, setEditing] = useState(false), [key, setKey] = useState(''); const [nativeTarget, setNativeTarget] = useState(null); const [catalogSource, setCatalogSource] = useState(null); 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 [noticeFailure, setNoticeFailure] = useState(null); const [probeScopes, setProbeScopes] = useState>({}); const [networkTarget, setNetworkTarget] = 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, selection] = await Promise.all([api
('/model-center'), api<{ config: Config; modelSelection: ModelSelection }>('/model-center/selection')]); if (alive.current && marker === generation.current) { setView(result); setRuntimeConfig(selection.config); onConfig(selection.config, selection.modelSelection); } } function addConnection() { setTab('connections'); setDraft(initial); setKey(''); setPersistKey(false); setCatalogSource(null); setNativeTarget(null); setEditing(true); } async function selectRoute(value: string) { await act(async () => { const [type, id] = value.split(':'); await api('/model-center/select', { type, id }); if (alive.current) setNotice('默认模型已更新;后续运行使用此选择,旧运行保留原记录。'); }); } async function act(action: () => Promise) { setWorking(true); setNotice(''); setNoticeFailure(null); try { await action(); if (alive.current) { await refresh(); if (credentialView) await refreshCredentials(); } } catch (cause) { if (alive.current) { setNotice(cause instanceof Error ? cause.message : '操作未完成,请刷新核对。'); if (cause && typeof cause === 'object' && 'diagnostic' in cause && cause.diagnostic) setNoticeFailure(cause.diagnostic as RuntimeFailure); } } 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(() => { if (!editing) return; const frame = requestAnimationFrame(() => document.querySelector('.mc-editor[aria-label="编辑模型连接"]')?.scrollIntoView({ block: 'start' })); return () => cancelAnimationFrame(frame); }, [editing]); 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 connections = view?.connections.filter(value => value.id !== 'legacy-default' || value.model.trim()) ?? []; 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; const passthrough = !runtimeConfig || runtimeConfig.executionMode === 'unrestricted' || runtimeConfig.capacityMode === 'passthrough'; return
ORVEN / MODELS

选择模型,继续开发。

接入你信任的模型,为项目选择合适的能力。

新任务默认{runtimeConfig?.mode === 'demo' ? '尚未选择' : selectionName || '正在读取'}{view?.waiting ?? 0} 等待
{notice &&
{notice}{noticeFailure && }
} {busy &&

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

} {!view ?

正在读取实际连接状态…

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

新任务默认模型

选择已保存的连接,或使用模型池调度。切换本身不请求模型。

{runtimeConfig?.mode === 'demo' ? '请从上游获取模型,或选择已配置的连接开始开发。' : selected?.type === 'pool' ? '模型池按成员配置调度;每次实际连接和返回型号保存在请求账本。' : (() => { const connection = connections.find(c => c.id === selected?.id); return connection ? `${protocolLabel(connection.protocol)} · ${previewUrl(connection)} · 请求 ${connection.model || '未配置'}` : '请选择可用连接。'; })()}
{runModel &&
当前会话最近运行{runModel.mode === 'demo' ? '离线演示' : runModel.routing?.members?.length ? runModel.routing.members.map(member => member.name + ' · ' + member.model).join(';') : runModel.model}这是该次运行封存的请求配置;实际返回型号请看请求账本。更改默认选择不会改写旧记录。
}
} {tab === 'budgets' && runtimeConfig && void act(async () => { await api('/model-center/runtime-budgets', input); if (alive.current) setNotice('运行预算已保存,当前模型选择保持。'); })} />} {tab === 'waits' && void act(async () => { const result = await api<{ config: Config }>('/model-center/wait-settings', value); if (alive.current) { onConfig(result.config); setNotice('等待时限已保存,从下一次运行生效。当前模型路由保持。'); } })} />} {tab === 'connections' && <>

模型连接

从上游获取目录并选择多个型号,可手动使用或加入自动适配模型池。

{catalogSource !== null && setCatalogSource(null)} />} {!connections.length && catalogSource === null && !editing &&
还没有模型连接

从上游获取可用型号,选择后即可开始开发。

}
{connections.map(value =>

{value.name}

{value.brand} · {protocolLabel(value.protocol)}{value.streaming ? ' · 流式开启' : ''}
{states[value.status]}
模型
{value.model || '尚未填写'}
请求地址
{previewUrl(value)}
{value.protocol === 'anthropic-messages' && <>
协议输出参数
{protocolOutput(value)}
鉴权
{value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · anthropic-version 2023-06-01
}
凭据
{value.credentialSource ? '共用 ' + (connections.find(source => source.id === value.credentialSource!.connectionId)?.name ?? '源连接') + (value.hasKey ? ' 的上游凭据' : ';请核对源连接是否启用及凭据') : value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}
当前请求
{value.activeRequests} 在途 · 并发 {value.concurrency === 0 ? '不限' : value.concurrency}
{passthrough ? <>
模型最大上下文
{upstreamCapacity(value, 'contextLimit')}
模型最大输出
{upstreamCapacity(value, 'maxOutputTokens')}
: <>
连接容量声明
上下文 {value.contextLimit.toLocaleString()} · 输出 {value.maxOutputTokens.toLocaleString()}
}
{value.upstreamModel &&

型号来自上游目录,能力按目录声明与显式设置保存;可在“推理与能力”查看已接入范围。

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

有 {value.modelSpecification.conflicts.length} 项规格声明差异,可在“推理与能力”的“模型规格与来源”查看。原目录与显式设置分别保留。

}
{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()}

}
)}
{nativeTarget && setNativeTarget(null)} onSave={async input => { await act(async () => { const result = await api<{ config: Config }>("/model-center/native-parameters", input); if (alive.current) { onConfig(result.config); setNativeTarget(null); setNotice("原生参数已保存;新任务按所选协议发送,旧请求保持原记录。"); } }); }} />}{editing &&
{ event.preventDefault(); void act(async () => { await api('/model-center/connections', { ...draft, modelIdentityAliases: draft.modelIdentityAliasesText.split(',').map(v=>v.trim()).filter(Boolean), ...(key ? { apiKey: key } : {}), ...(persistKey ? { persistKey: true } : {}) }); if (alive.current) { setKey(''); setEditing(false); setNotice(persistKey ? '连接与本机加密凭据已一起保存。' : '连接已保存。'); } }); }}>

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

POST {previewUrl(draft)}
{draft.protocol === 'anthropic-messages' ? '填写服务根地址或 /v1 根地址,工作台补齐 /v1/messages。鉴权按供应商文档选择。' : '工作台按此根地址追加协议路径;服务要求 /v1 时,请在根地址中填写。'}切换协议会重置本表单的原生参数,保存后从新任务生效。

{draft.protocol === 'anthropic-messages' && }

{runtimeConfig?.executionMode === 'unrestricted' ? '当前完全开放执行:记录型号差异后继续;所选核对策略仍会保存。' : '严格核对时,型号不一致或无法核对会暂停并保留原响应。'}

{passthrough ?
默认透传 · 不设本地上限
模型最大上下文
{upstreamCapacity(draft, 'contextLimit')}
模型最大输出
{upstreamCapacity(draft, 'maxOutputTokens')}

容量来自当前型号的上游目录或官方规格,仅供查看;未公开时本地无限制。完整发送上下文;Messages 按协议带 max_tokens,其它协议默认不附加输出上限,上游错误原文保留。

: <>

容量优先使用上游目录,缺项时采用已知型号的官方规格;未知型号由上游决定。推理可能共享输出额度。

}

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

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

本机加密凭据

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

{!credentialView ?

正在核对本机保存状态…

: <>

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

{credentialView.unavailable &&

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

} {!connections.length &&

请先添加模型连接,再管理凭据。

} {!!connections.length &&
{ event.preventDefault(); void act(async () => { const target = connections.find(value => value.id === (credentialTarget || 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.filter(value => connections.some(connection => connection.id === value.id)).map(value =>

{value.name}

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

{value.message}

{value.savedAt &&

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

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

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

}
} {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 => {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); }); }}>

模型池规则

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

:

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

}}
}
; }