Files
Agent-Workbench/src/client/ModelCenter.tsx
T

225 lines
47 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<string, unknown>; outputTokenField?: string; streaming?: boolean; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; 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<string, string> = { reference: '共用上游凭据', not_saved: '仅本次内存', saved: '本机加密保存', disabled: '关闭自动加载', source_changed: '配置已变化', decrypt_failed: '无法解密', user_mismatch: '用户不匹配', directory_mismatch: '目录不匹配', unavailable: '保存登记不可用' };
const states: Record<string, string> = { 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<string, string>, model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, ...DEFAULT_MODEL_CAPACITY, concurrency: 1 };
const capabilityLabels: Record<string, string> = { text: '文本', tools: '工具', streaming: '流式', vision: '视觉', audio: '语音' };
const capabilityStates: Record<string, string> = { 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<Center | null>(null);
const [runtimeConfig, setRuntimeConfig] = useState<Config | null>(null);
const [tab, setTab] = useState('connections');
const [draft, setDraft] = useState<typeof initial & ModelSpecConnection & { id?: string; revision?: number; upstreamModel?: CatalogModel; messagesAuth?: string; parameterProfile?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string }>(initial);
const [editing, setEditing] = useState(false), [key, setKey] = useState('');
const [nativeTarget, setNativeTarget] = useState<Connection | null>(null);
const [catalogSource, setCatalogSource] = useState<string | null>(null);
const [persistKey, setPersistKey] = useState(false), [persistImports, setPersistImports] = useState(false);
const [credentialView, setCredentialView] = useState<CredentialView | null>(null), [credentialKey, setCredentialKey] = useState(''), [credentialTarget, setCredentialTarget] = useState('');
const [pool, setPool] = useState<Pool>(emptyPool), [poolEditing, setPoolEditing] = useState(false);
const [working, setWorking] = useState(false), [notice, setNotice] = useState('');
const [noticeFailure, setNoticeFailure] = useState<RuntimeFailure | null>(null);
const [probeScopes, setProbeScopes] = useState<Record<string, string>>({});
const [networkTarget, setNetworkTarget] = useState('');
const [operations, setOperations] = useState<Operations | null>(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<HTMLElement>(null);
async function refresh() {
const marker = ++generation.current;
const [result, selection] = await Promise.all([api<Center>('/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<void>) {
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>('/operations' + (offset === undefined ? '' : '?artifactOffset=' + offset)); if (alive.current) setOperations(value); }
async function refreshCredentials() { const value = await api<CredentialView>('/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<HTMLButtonElement>('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 <section className="model-center" aria-label="模型控制台" aria-busy={working}>
<div className="mc-overview"><div><span className="mc-eyebrow">ORVEN / MODELS</span><h2>选择模型,继续开发。</h2><p>接入你信任的模型,为项目选择合适的能力。</p></div><div className="mc-current"><Route size={18} /><span>新任务默认<strong>{runtimeConfig?.mode === 'demo' ? '尚未选择' : selectionName || '正在读取'}</strong></span><span className="mc-count">{view?.waiting ?? 0} 等待</span></div></div>
<nav ref={tabsRef} className="mc-tabs" aria-label="模型中心分类">{[['connections', '模型连接', Server], ['network', '连接诊断', Activity], ['pools', '模型池', Layers3], ['budgets', '运行预算', Settings2], ['waits', '等待时限', Settings2], ['attempts', '请求账本', Route], ['imports', '配置导入', Settings2], ['credentials', '凭据保存', KeyRound], ['operations', '运行巡检', Activity]].map(([id, title, Icon]) => {
const Symbol = Icon as typeof Server; return <button key={id as string} type="button" aria-current={tab === id ? 'page' : undefined} onClick={() => { setTab(id as string); setNotice(''); }}><Symbol size={16} />{title as string}</button>;
})}<button className="mc-refresh" type="button" disabled={working} onClick={() => void act(refresh)} aria-label="刷新模型中心"><RefreshCw size={16} /></button></nav>
{notice && <div className="mc-notice" role="status">{notice}{noticeFailure && <ModelErrorDetails failure={noticeFailure} />}</div>}
{busy && <p className="mc-notice">有任务正在执行;连接可停用,其他配置请在任务结束后修改。</p>}
{!view ? <p className="mc-empty">正在读取实际连接状态…</p> : <div className="mc-content">
{tab === 'connections' && <> <section className="mc-route-control" aria-label="默认模型选择">
<div className="mc-route-heading"><div><h3>新任务默认模型</h3><p>选择已保存的连接,或使用模型池调度。切换本身不请求模型。</p></div><button className="button secondary" disabled={locked} onClick={addConnection}><Plus size={15} />添加模型</button></div>
<label className="mc-route-select">当前选择<select aria-label="新任务默认模型" disabled={locked || !runtimeConfig} value={runtimeConfig?.mode === 'demo' || !connections.some(value => value.id === selected?.id) && selected?.type !== 'pool' ? '' : selected?.type + ':' + selected?.id} onChange={event => void selectRoute(event.target.value)}>
<option value="" disabled>选择模型或添加连接</option>
<optgroup label="模型连接">{connections.map(connection => <option key={connection.id} value={(connection.id === 'legacy-default' ? 'legacy' : 'connection') + ':' + connection.id} disabled={!connection.enabled || connection.requiresKey && !connection.hasKey}>{connection.name} · {connection.model || '尚未填写型号'}{connection.status !== 'configured' ? ' · ' + states[connection.status] : ''}</option>)}</optgroup>
{!!view.pools.length && <optgroup label="模型池">{view.pools.map(pool => <option key={pool.id} value={'pool:' + pool.id}>{pool.name} · {pool.members.length} 个连接</option>)}</optgroup>}
</select></label>
<div className="mc-route-detail">{runtimeConfig?.mode === 'demo' ? '请从上游获取模型,或选择已配置的连接开始开发。' : selected?.type === 'pool' ? '模型池按成员配置调度;每次实际连接和返回型号保存在请求账本。' : (() => { const connection = connections.find(c => c.id === selected?.id); return connection ? `${protocolLabel(connection.protocol)} · ${previewUrl(connection)} · 请求 ${connection.model || '未配置'}` : '请选择可用连接。'; })()}</div>
{runModel && <div className="mc-run-model"><strong>当前会话最近运行</strong><span>{runModel.mode === 'demo' ? '离线演示' : runModel.routing?.members?.length ? runModel.routing.members.map(member => member.name + ' · ' + member.model).join(';') : runModel.model}</span><small>这是该次运行封存的请求配置;实际返回型号请看请求账本。更改默认选择不会改写旧记录。</small></div>}
</section></>}
{tab === 'budgets' && runtimeConfig && <ModelBudgetSettings key={JSON.stringify(runtimeConfig)} value={runtimeConfig} disabled={locked} onSave={input => void act(async () => { await api('/model-center/runtime-budgets', input); if (alive.current) setNotice('运行预算已保存,当前模型选择保持。'); })} />}
{tab === 'waits' && <ModelWaitSettings key={JSON.stringify(view.waitSettings)} value={view.waitSettings} disabled={locked} onSave={value => void act(async () => {
const result = await api<{ config: Config }>('/model-center/wait-settings', value);
if (alive.current) { onConfig(result.config); setNotice('等待时限已保存,从下一次运行生效。当前模型路由保持。'); }
})} />}
{tab === 'connections' && <>
<div className="mc-section-title"><div><h3>模型连接</h3><p>从上游获取目录并选择多个型号,可手动使用或加入自动适配模型池。</p></div><div className="mc-row-actions"><button className="button primary" disabled={locked} onClick={() => { setCatalogSource(''); setEditing(false); setNativeTarget(null); }}><Plus size={16} />从上游添加模型</button><button className="button secondary" disabled={locked} onClick={addConnection}>手动填写(兼容)</button></div></div>
{catalogSource !== null && <ModelCatalog key={catalogSource} sources={connections} sourceId={catalogSource} busy={locked} onSaved={refresh} onClose={() => setCatalogSource(null)} />}
{!connections.length && catalogSource === null && !editing && <div className="mc-empty"><strong>还没有模型连接</strong><p>从上游获取可用型号,选择后即可开始开发。</p></div>}
<div className="mc-connections">{connections.map(value => <article className={'mc-connection ' + (!value.enabled ? 'mc-disabled' : '')} key={value.id} data-connection-id={value.id}>
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · {protocolLabel(value.protocol)}{value.streaming ? ' · 流式开启' : ''}</span></div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span></div>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>请求地址</dt><dd>{previewUrl(value)}</dd>{value.protocol === 'anthropic-messages' && <><dt>协议输出参数</dt><dd>{protocolOutput(value)}</dd><dt>鉴权</dt><dd>{value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · anthropic-version 2023-06-01</dd></>}<dt>凭据</dt><dd>{value.credentialSource ? '共用 ' + (connections.find(source => source.id === value.credentialSource!.connectionId)?.name ?? '源连接') + (value.hasKey ? ' 的上游凭据' : ';请核对源连接是否启用及凭据') : value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>当前请求</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency === 0 ? '不限' : value.concurrency}</dd>{passthrough ? <><dt>模型最大上下文</dt><dd>{upstreamCapacity(value, 'contextLimit')}</dd><dt>模型最大输出</dt><dd>{upstreamCapacity(value, 'maxOutputTokens')}</dd></> : <><dt>连接容量声明</dt><dd>上下文 {value.contextLimit.toLocaleString()} · 输出 {value.maxOutputTokens.toLocaleString()}</dd></>}</dl>
{value.upstreamModel && <p className="mc-help">型号来自上游目录,能力按目录声明与显式设置保存;可在“推理与能力”查看已接入范围。</p>}
{!!value.modelSpecification?.conflicts.length && <p className="mc-help">有 {value.modelSpecification.conflicts.length} 项规格声明差异,可在“推理与能力”的“模型规格与来源”查看。原目录与显式设置分别保留。</p>}
<div className="mc-capabilities">{Object.entries(capabilityLabels).map(([key, title]) => <span key={key} data-capability={value.capabilities?.[key] ?? 'unknown'}>{title}:{capabilityStates[value.capabilities?.[key] ?? 'unknown']}</span>)}</div>
{value.health.reason && <p className="mc-card-warning">{value.health.reason}{!!value.health.cooldownUntil && value.health.cooldownUntil > Date.now() && ' · 冷却至 ' + new Date(value.health.cooldownUntil).toLocaleTimeString()}</p>}
<footer><button className="button secondary" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id }); onConfig(result.config, { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id, name: value.name }); })}>{runtimeConfig?.mode !== 'demo' && selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{runtimeConfig?.mode !== 'demo' && selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
<button className="button secondary" disabled={locked} onClick={() => { setDraft({ ...initial, ...value, modelIdentityAliasesText: (value.modelIdentityAliases ?? []).join(', '), streaming: value.streaming === true, capabilityDeclarations: { ...initial.capabilityDeclarations, ...value.capabilityDeclarations } }); setKey(''); setPersistKey(false); setEditing(true); setCatalogSource(null); setNativeTarget(null); }}>编辑</button>
<button className="button secondary" disabled={locked || !value.enabled} onClick={() => { setCatalogSource(value.credentialSource?.connectionId ?? value.id); setEditing(false); setNativeTarget(null); }}>获取同源模型</button>
<button className="button secondary" onClick={() => { setNetworkTarget(value.id); setTab('network'); }}>连接诊断</button>
<button className="mc-icon-action" aria-label={(value.enabled ? '停用' : '启用') + value.name} disabled={working} onClick={() => void act(async () => { await api('/model-center/toggle', { id: value.id, enabled: !value.enabled }); })}><Power size={15} />{value.enabled ? '停用' : '启用'}</button>
<label className="mc-probe-scope">检测范围<select aria-label={value.name + '检测范围'} value={probeScopes[value.id] ?? 'text'} disabled={locked} onChange={event => setProbeScopes({ ...probeScopes, [value.id]: event.target.value })}><option value="text">文本响应</option><option value="tools">工具调用</option><option value="streaming">流式文本</option><option value="vision">合成图像识别</option></select></label>
<button className="button secondary" disabled={locked} onClick={() => { setNativeTarget(value); setEditing(false); }}>推理与能力</button><button className="mc-probe" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ scope: string }>('/model-center/probe', { id: value.id, scope: probeScopes[value.id] ?? 'text' }); if (alive.current) setNotice(capabilityLabels[result.scope] + '检测通过;只验证所选能力,原请求与用量已记入账本。'); })}>验证响应(调用模型)</button></footer>
</article>)}</div>
{nativeTarget && <NativeParameters executionMode={runtimeConfig?.executionMode} key={nativeTarget.id + ":" + nativeTarget.revision} connection={nativeTarget} busy={locked} onCancel={() => 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 && <form className="mc-editor" aria-label="编辑模型连接" onSubmit={event => { 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 ? '连接与本机加密凭据已一起保存。' : '连接已保存。'); } }); }}>
<h3>{draft.id ? '编辑模型连接' : '添加模型连接'}</h3><div className="mc-form-grid">
<label>连接名称<input required value={draft.name} onChange={event => setDraft({ ...draft, name: event.target.value })} /></label>
<label>服务品牌<select value={draft.brand} onChange={event => setDraft({ ...draft, brand: event.target.value })}>{['自定义', 'OpenAI', 'Claude 兼容代理', 'DeepSeek', 'Ollama', 'vLLM', '兼容服务'].map(brand => <option key={brand}>{brand}</option>)}</select></label>
<label>接口协议<select aria-label="接口协议" value={draft.protocol} onChange={event => setDraft({ ...draft, protocol: event.target.value, parameterProfile: 'auto', nativeParameters: {}, outputTokenField: undefined })}><option value="chat-completions">Chat Completions</option><option value="responses">OpenAI Responses</option><option value="anthropic-messages">Anthropic Messages</option></select></label>
<label>工具调用能力<select aria-label="工具调用能力" value={draft.capabilityDeclarations.tools} onChange={event => setDraft({ ...draft, capabilityDeclarations: { ...draft.capabilityDeclarations, tools: event.target.value } })}><option value="supported">服务声明支持</option><option value="unknown">尚未确定</option><option value="unsupported">明确不支持</option></select></label>
<label>流式能力<select aria-label="流式能力" value={draft.capabilityDeclarations.streaming} onChange={event => setDraft({ ...draft, streaming: event.target.value === 'supported' && draft.streaming, capabilityDeclarations: { ...draft.capabilityDeclarations, streaming: event.target.value } })}><option value="unknown">尚未确定</option><option value="supported">服务声明支持</option><option value="unsupported">明确不支持</option></select></label>
<label>视觉能力<select aria-label="视觉能力" value={draft.capabilityDeclarations.vision} onChange={event=>setDraft({...draft,capabilityDeclarations:{...draft.capabilityDeclarations,vision:event.target.value}})}><option value="unknown">尚未确定</option><option value="supported">服务声明支持</option><option value="unsupported">明确不支持</option></select></label>
<label className="mc-checkbox"><input type="checkbox" checked={draft.streaming} disabled={runtimeConfig?.executionMode !== 'unrestricted' && draft.capabilityDeclarations.streaming !== 'supported'} onChange={event => setDraft({ ...draft, streaming: event.target.checked })} />使用流式输出</label>
<label className="mc-full">接口根地址<input type="url" required value={draft.baseUrl} onChange={event => setDraft({ ...draft, baseUrl: event.target.value })} /></label>
<p className="mc-help mc-full" aria-label="请求地址预览">POST {previewUrl(draft)}<br />{draft.protocol === 'anthropic-messages' ? '填写服务根地址或 /v1 根地址,工作台补齐 /v1/messages。鉴权按供应商文档选择。' : '工作台按此根地址追加协议路径;服务要求 /v1 时,请在根地址中填写。'}切换协议会重置本表单的原生参数,保存后从新任务生效。</p>
{draft.protocol === 'anthropic-messages' && <label>Messages 鉴权<select aria-label="Messages 鉴权" value={draft.messagesAuth ?? 'api-key'} onChange={event => setDraft({ ...draft, messagesAuth: event.target.value })}><option value="api-key">x-api-key(Anthropic 标准)</option><option value="bearer">Bearer(兼容服务)</option></select></label>}
<label>请求模型名称<input required value={draft.model} onChange={event => setDraft({ ...draft, model: event.target.value })} /></label>
<label>型号核对<select aria-label="型号核对" value={draft.modelIdentityPolicy} onChange={event => setDraft({ ...draft, modelIdentityPolicy: event.target.value })}><option value="record">记录请求与返回型号</option><option value="require-match">严格核对型号</option></select></label>
<p className="mc-help mc-full">{runtimeConfig?.executionMode === 'unrestricted' ? '当前完全开放执行:记录型号差异后继续;所选核对策略仍会保存。' : '严格核对时,型号不一致或无法核对会暂停并保留原响应。'}</p>
<label className="mc-full">允许的返回型号(可选,逗号分隔)<input value={draft.modelIdentityAliasesText} onChange={event => setDraft({ ...draft, modelIdentityAliasesText: event.target.value })} /></label>
<label className="mc-full">型号映射依据<input required={draft.modelIdentityAliasesText.trim().length > 0} value={draft.modelIdentityAliasSource} placeholder="填写供应商映射说明或可核对的出处" onChange={event => setDraft({ ...draft, modelIdentityAliasSource: event.target.value })} /></label>
<label>临时 API Key<input type="password" autoComplete="off" value={key} placeholder={draft.id ? '留空保留本次凭据' : '按服务要求填写'} onChange={event => setKey(event.target.value)} /></label>
{passthrough ? <div className="mc-full" aria-label="连接容量策略"><strong>默认透传 · 不设本地上限</strong><dl className="mc-capacity-facts"><div><dt>模型最大上下文</dt><dd aria-label="模型最大上下文">{upstreamCapacity(draft, 'contextLimit')}</dd></div><div><dt>模型最大输出</dt><dd aria-label="模型最大输出">{upstreamCapacity(draft, 'maxOutputTokens')}</dd></div></dl><p className="mc-help">容量来自当前型号的上游目录或官方规格,仅供查看;未公开时本地无限制。完整发送上下文;Messages 按协议带 max_tokens,其它协议默认不附加输出上限,上游错误原文保留。</p></div> : <>
<label>上下文上限<input type="number" required step="1" min="1000" value={draft.contextLimit} onChange={event => setDraft({ ...draft, contextLimit: Number(event.target.value) })} /></label>
<label>输出上限<input type="number" required step="1" min="256" value={draft.maxOutputTokens} onChange={event => setDraft({ ...draft, maxOutputTokens: Number(event.target.value) })} /></label>
<div className="mc-full"><p className="mc-help">容量优先使用上游目录,缺项时采用已知型号的官方规格;未知型号由上游决定。推理可能共享输出额度。</p><button type="button" className="button secondary" onClick={() => setDraft({ ...draft, contextLimit: modelCapacityDeclaration(draft, 'contextLimit')?.value ?? DEFAULT_MODEL_CAPACITY.contextLimit, maxOutputTokens: modelCapacityDeclaration(draft, 'maxOutputTokens')?.value ?? DEFAULT_MODEL_CAPACITY.maxOutputTokens })}>{modelCapacityDeclaration(draft, 'contextLimit') || modelCapacityDeclaration(draft, 'maxOutputTokens') ? '采用已知模型容量' : '填入开发初始值'}</button></div>
</>}
<label>{runtimeConfig?.executionMode === 'unrestricted' ? '并发请求数(0 为不限)' : '并发请求上限'}<input type="number" min={runtimeConfig?.executionMode === 'unrestricted' ? 0 : 1} max={runtimeConfig?.executionMode === 'unrestricted' ? undefined : 8} value={draft.concurrency} onChange={event => setDraft({ ...draft, concurrency: Number(event.target.value) })} /></label>
<label className="mc-checkbox"><input type="checkbox" checked={draft.requiresKey} onChange={event => setDraft({ ...draft, requiresKey: event.target.checked })} />服务需要 API Key</label></div>
<label className="mc-checkbox"><input type="checkbox" checked={persistKey} onChange={event => setPersistKey(event.target.checked)} />本机加密保存本次填写的 API Key</label>
<p className="mc-help"><CircleHelp size={14} />品牌仅用于分类,请选择服务实际提供的协议。能力检测会发起一次模型请求,可能产生费用;使用合成输入,不发送项目文件。文本检测不能证明工具或视觉能力。配置变化后需重新检测并核对凭据保存状态。</p>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => { setEditing(false); setKey(''); }}>取消</button><button className="button primary" disabled={locked || persistKey && !key.trim()} type="submit">保存模型连接</button></div>
</form>}
</>}
{tab === 'network' && <ModelNetworkDiagnostics connections={connections} initialId={networkTarget || (selected?.type !== 'pool' ? selected?.id : undefined)} disabled={locked} />}
{tab === 'credentials' && <section aria-label="本机加密凭据">
<div className="mc-section-title"><div><h3>本机加密凭据</h3><p>使用当前Windows用户加密。保存后的 Key 不会回显或包含在导出中。</p></div></div>
{!credentialView ? <p className="mc-empty">正在核对本机保存状态…</p> : <>
<p className="mc-help">只保存这次填写或确认导入的凭据。临时连接在宿主退出后需要重新填写。</p>
{credentialView.unavailable && <p className="mc-card-warning">原保存登记格式不可用;原数据保留,请核对后修复。</p>}
{!connections.length && <p className="mc-empty">请先添加模型连接,再管理凭据。</p>}
{!!connections.length && <form className="mc-editor" aria-label="保存加密凭据" onSubmit={event => { 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); }
}); }}>
<div className="mc-form-grid"><label>选择保存连接<select aria-label="选择保存连接" value={credentialTarget || connections[0]?.id || ''} onChange={event => { setCredentialTarget(event.target.value); setCredentialKey(''); }}>{connections.filter(value => !value.credentialSource).map(value => <option key={value.id} value={value.id}>{value.name} · {value.model || '未填写模型'}</option>)}</select></label>
<label>重新填写 API Key<input type="password" autoComplete="off" value={credentialKey} onChange={event => setCredentialKey(event.target.value)} /></label></div>
<p className="mc-help">只保存这次新填的凭据。不同用户、目录或连接配置无法加载原保存块。</p>
<div className="mc-actions"><button type="submit" className="button primary" disabled={locked || !credentialView.supported || credentialView.unavailable || !credentialKey.trim()}>加密保存凭据</button></div>
</form>}
<div className="mc-connections">{credentialView.connections.filter(value => connections.some(connection => connection.id === value.id)).map(value => <article className="mc-connection" key={value.id}>
<div className="mc-card-heading"><KeyRound size={20} /><div><h4>{value.name}</h4><span>{savedStates[value.status] || value.status}</span></div></div>
<p className="mc-help">{value.message}</p>{value.savedAt && <p className="mc-help">保存于 {new Date(value.savedAt).toLocaleString()}</p>}
<div className="mc-actions">{value.status !== 'not_saved' && value.status !== 'reference' && <>
<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/credentials', { id: value.id, revision: value.revision, action: value.enabled ? 'disable' : 'enable' }); })}>{value.enabled ? '关闭自动加载' : '启用自动加载'}</button>
<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/credentials', { id: value.id, revision: value.revision, action: 'delete' }); })}>删除本机保存</button>
</>}
{value.status !== 'reference' && <button className="button secondary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/credentials', { id: value.id, revision: value.revision, action: 'forget' }); if (alive.current) onConfig(result.config); })}>清除该连接凭据</button>}
</div>
</article>)}</div><p className="mc-help">删除本机保存保留本次内存连接;清除该连接凭据会同时移除本机保存与内存凭据。</p>
</>}
</section>}
{tab === 'pools' && <><div className="mc-section-title"><div><h3>模型池</h3><p>自动选择优先已知适配成员,能力未知时保留后备尝试。明确不支持的成员不参与自动选择,仍可手动选用。透传请求失败后保留原错,等待处理。</p></div><button className="button primary" disabled={locked} onClick={() => { setPool(emptyPool); setPoolEditing(true); }}><Plus size={16} />新建模型池</button></div>
{!view.pools.length && <p className="mc-empty">添加多个连接后建立模型池,设置轮询或权重与连接亲和。</p>}
{view.pools.map(value => <article className="mc-pool" key={value.id}><Layers3 size={23} /><div><h4>{value.name}</h4><p>{value.strategy === 'weighted' ? '权重轮询' : '顺序轮询'} · {value.members.length} 个成员 · {value.maxAttempts} 次尝试上限 · {value.sticky ? '运行内保持连接' : '每次请求重新选择'}</p><div className="mc-members">{value.members.map(member => <span key={member.connectionId}>{connections.find(connection => connection.id === member.connectionId)?.name} ×{member.weight}</span>)}</div></div><div className="mc-actions"><button className="button secondary" disabled={locked} onClick={() => { setPool(value); setPoolEditing(true); }}>编辑</button><button className="button primary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: 'pool', id: value.id }); onConfig(result.config, { type: 'pool', id: value.id!, name: value.name }); })}>{selected?.id === value.id ? '当前模型池' : '使用此模型池'}</button></div></article>)}
{poolEditing && <form className="mc-editor" aria-label="编辑模型池" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/pools', pool); if (alive.current) setPoolEditing(false); }); }}><h3>模型池规则</h3><div className="mc-form-grid"><label>模型池名称<input required value={pool.name} onChange={event => setPool({ ...pool, name: event.target.value })} /></label><label>调度策略<select value={pool.strategy} onChange={event => setPool({ ...pool, strategy: event.target.value })}><option value="round-robin">顺序轮询</option><option value="weighted">权重轮询</option></select></label><label>单请求尝试上限<input type="number" min="1" max="8" value={pool.maxAttempts} onChange={event => setPool({ ...pool, maxAttempts: Number(event.target.value) })} /></label><label>排队上限(秒)<input type="number" min="1" max="60" value={pool.queueTimeoutMs / 1000} onChange={event => setPool({ ...pool, queueTimeoutMs: Number(event.target.value) * 1000 })} /></label></div><label className="mc-checkbox"><input type="checkbox" checked={pool.sticky} onChange={event => setPool({ ...pool, sticky: event.target.checked })} />同一运行优先保持连接;明确失败后才切换</label>
<fieldset><legend>模型池成员与权重</legend>{connections.map(connection => { const member = pool.members.find(value => value.connectionId === connection.id); return <label key={connection.id} className="mc-member-choice"><input type="checkbox" checked={!!member} onChange={event => setPool({ ...pool, members: event.target.checked ? [...pool.members, { connectionId: connection.id, weight: 1 }] : pool.members.filter(value => value.connectionId !== connection.id) })} /><span>{connection.name}<small>{connection.model || '尚未选择模型'} · {states[connection.status]}</small></span><input type="number" aria-label={connection.name + '权重'} disabled={!member} min="1" max="10" value={member?.weight ?? 1} onChange={event => setPool({ ...pool, members: pool.members.map(value => value.connectionId === connection.id ? { ...value, weight: Number(event.target.value) } : value) })} /></label>; })}</fieldset>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => setPoolEditing(false)}>取消</button><button className="button primary" disabled={locked || !pool.members.length}>保存模型池</button></div></form>}
</>}
{tab === 'attempts' && <ModelRequestLedger connections={view.connections} refreshVersion={view} />}
{tab === 'imports' && <><div className="mc-section-title"><div><h3>已有配置导入</h3><p>先预览来源和模型,再导入。原客户端配置保持原样。</p></div><button className="button secondary" disabled={working} onClick={() => void act(async () => { const value = await api<{ sources: typeof discovery }>('/model-center/imports'); if (alive.current) setDiscovery(value.sources); })}>识别本机来源</button></div>
{view.imports.length > 0 && <><h4>已登记来源</h4>{view.imports.map(value => <article className="mc-import-source" key={value.id}><strong>{value.source}</strong><code>{value.path}</code><span>{value.enabled ? '每分钟检查' : '自动同步已关闭'}</span>{value.lastCheckedAt && <p>最近检查 {new Date(value.lastCheckedAt).toLocaleString()}</p>}{value.lastError && <p className="mc-card-warning">{value.lastError}</p>}{!!value.lastResult?.conflicts?.length && <p className="mc-card-warning">有 {value.lastResult.conflicts.length} 项与手动修改冲突,已保留工作台中的修改。</p>}<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/import-toggle', { id: value.id, enabled: !value.enabled }); })}>{value.enabled ? '关闭自动同步' : '启用自动同步'}</button></article>)}<button className="button secondary" disabled={locked || !view.imports.some(value => value.enabled)} onClick={() => void act(async () => { const result = await api<{ results: { imported?: string[]; conflicts?: string[]; error?: string }[] }>('/model-center/import-sync', {}); const imported = result.results.reduce((sum, value) => sum + (value.imported?.length ?? 0), 0); const conflicts = result.results.reduce((sum, value) => sum + (value.conflicts?.length ?? 0), 0); if (alive.current) setNotice(`已检查启用来源:更新 ${imported} 项,冲突 ${conflicts} 项。`); })}>立即同步已启用来源</button></>}
{discovery.map(value => <article className="mc-import-source" key={value.source}><strong>{value.source}</strong><code>{value.path || '当前版本尚无可发现的配置路径'}</code><span>{value.available ? value.supported ? '可预览' : '当前不支持' : '未发现'}</span>{value.detail && <p>{value.detail}</p>}<button className="button secondary" disabled={!value.available || !value.supported || locked} onClick={() => { setImportSource(value.source); setImportPath(value.path); }}>选择来源</button></article>)}
<div className="mc-editor"><div className="mc-form-grid"><label>配置格式<select value={importSource} onChange={event => setImportSource(event.target.value)}><option value="ccswitch">CCSwitch SQLite</option><option value="workbench-json">工作台连接 JSON</option></select></label><label>本地文件路径<input value={importPath} onChange={event => { setImportPath(event.target.value); setPreview(null); }} /></label></div><button className="button secondary" disabled={locked || !importPath} onClick={() => void act(async () => { const value = await api<typeof preview>('/model-center/import-preview', { source: importSource, path: importPath }); if (alive.current) setPreview(value); })}>预览可导入连接</button></div>
{preview && <div className="mc-editor"><h3>本次预览</h3>{preview.entries.map(value => <p key={value.id}>{value.name} · {value.model} · {value.baseUrl} · {value.hasKey ? '含临时凭据' : '无凭据'}</p>)}{preview.notices.map((value, index) => <p className="mc-help" key={index}>{value}</p>)}<label className="mc-checkbox"><input type="checkbox" checked={persistImports} onChange={event => setPersistImports(event.target.checked)} />本机加密保存本次确认导入的凭据</label><button className="button primary" disabled={locked || !preview.entries.length} onClick={() => void act(async () => { await api('/model-center/import-apply', { previewId: preview.id, persistCredentials: persistImports }); if (alive.current) { setPreview(null); setNotice(persistImports ? '连接与本次确认导入的加密凭据已共同保存。' : '已导入可支持的连接。临时凭据只在本次宿主内存中。'); } })}>导入这些连接</button></div>}
</>}
{tab === 'operations' && <><div className="mc-section-title"><div><h3>运行巡检</h3><p>核对宿主、任务、来源与数据,按页检查历史工件。</p></div><button className="button primary" disabled={working} onClick={() => void act(() => inspect())}><Activity size={15} />开始本地巡检</button></div><label className="mc-checkbox"><input type="checkbox" checked={autoInspect} onChange={event => setAutoInspect(event.target.checked)} />在此页面每30秒检查,离开即停止</label>{operations ? <><p className="mc-help">{new Date(operations.checkedAt).toLocaleString()} · v{operations.version} · {operations.activeTasks} 活动任务 · {operations.queue} 排队</p><div className="mc-checks">{operations.checks.map(value => <article key={value.id}><span className={'mc-state mc-state-' + value.status}>{states[value.status] || value.status}</span><div><h4>{value.title}</h4><p>{value.detail}</p></div></article>)}</div>{operations.artifacts && <div className="mc-operations-pages" aria-label="历史工件巡检分页"><p className="mc-help">本页核对 {operations.artifacts.checked} 项 · 全部 {operations.artifacts.total} 项 · 本页未覆盖 {operations.artifacts.remaining} 项</p><div className="mc-row-actions"><button className="button" disabled={working || operations.artifacts.olderOffset === null} onClick={() => void act(() => inspect(operations.artifacts!.olderOffset!))}>检查更早工件</button><button className="button" disabled={working || operations.artifacts.newerOffset === null} onClick={() => void act(() => inspect(operations.artifacts!.newerOffset!))}>检查较新工件</button></div>{operations.artifacts.results.filter(value => !value.passed).map(value => <p className="mc-help error" key={value.id}>工件 {value.id}:{value.error}</p>)}</div>}<p className="mc-help">{operations.scope}</p></> : <p className="mc-empty">执行一次本地检查,查看实际结果与检查范围。</p>}</>}
</div>}
</section>;
}