fix: select capable models and align effective permission evidence

This commit is contained in:
Agent Workbench Dev
2026-11-07 00:18:24 +08:00
parent 762597b99d
commit dcaecd8b0a
18 changed files with 572 additions and 43 deletions
+1 -1
View File
@@ -676,7 +676,7 @@ export default function App() {
{modelCenterOpen && <Modal title="模型中心" description="连接、模型池与执行健康统一管理。" wide onClose={() => setModelCenterOpen(false)}><ModelCenter busy={anyRunning} runModel={session?.execution?.run?.model} onConfig={(value, selection) => { setConfig(value); if (selection) setModelSelection(selection); }} /></Modal>}
{memoryOpen && selectedProject && <Modal title="项目记忆" description="项目事实与经验保留来源,采用可撤销;源码变化后重新核对。" wide onClose={() => setMemoryOpen(false)}><ProjectMemoryPanel key={selectedProject.id + ':' + (session?.id ?? '')} project={selectedProject} session={session?.projectId === selectedProject.id ? session : null} onSelectSession={selectSession} /></Modal>}
{skillsOpen && selectedProject && <Modal title="项目技能" description="管理当前项目的技能来源、版本与启用状态。" wide onClose={() => setSkillsOpen(false)}><SkillCenter key={selectedProject.id} projectId={selectedProject.id} busy={isRunning} /></Modal>}
{mcpOpen && selectedProject && <Modal title="项目 MCP 工具" description="实际探测本地 stdio 服务,选择可以请求的工具,并核对每次运行原记录。" wide onClose={() => setMcpOpen(false)}><McpPanel key={selectedProject.id + ':' + (session?.id ?? '')} projectId={selectedProject.id} session={session?.projectId === selectedProject.id ? session : null} busy={isRunning} onSession={acceptSession} onError={session ? failureFor(session) : failure} /></Modal>}
{mcpOpen && selectedProject && <Modal title="项目 MCP 工具" description="实际探测本地 stdio 服务,选择可以请求的工具,并核对每次运行原记录。" wide onClose={() => setMcpOpen(false)}><McpPanel key={selectedProject.id + ':' + (session?.id ?? '')} projectId={selectedProject.id} session={session?.projectId === selectedProject.id ? session : null} busy={isRunning} approvalMode={config?.approvalMode} onSession={acceptSession} onError={session ? failureFor(session) : failure} /></Modal>}
{workersOpen && session && <Modal title="隔离协作" description="固定父子目标、独立工作区、预算与原成果审查。" wide onClose={() => setWorkersOpen(false)}><WorkerPanel key={session.id} session={session} config={config} busy={isRunning} onSession={acceptSession} onNavigate={async (projectId, sessionId, view) => { setWorkersOpen(false); await navigateWorkspace(projectId, sessionId, () => true, view); }} onReview={() => { setWorkersOpen(false); showInspector('changes'); }} /></Modal>}
{evaluationsOpen && session && <Modal title="工程质量评测" description="固定需求与测试,比较原版和候选,审查后交付。" wide onClose={() => setEvaluationsOpen(false)}><EvaluationPanel key={session.id} session={session} config={config} busy={isRunning} onSession={acceptSession} onNavigate={async (projectId, sessionId, view) => { setEvaluationsOpen(false); await navigateWorkspace(projectId, sessionId, () => true, view); }} onReview={() => { setEvaluationsOpen(false); showInspector('changes'); }} onRecovery={() => { setEvaluationsOpen(false); setWorkersOpen(true); }} /></Modal>}
{toast && <div className="toast" role="status"><span>{toast}</span><IconButton label="关闭提示" onClick={() => setToast('')}><X size={14} /></IconButton></div>}
+7 -5
View File
@@ -5,6 +5,7 @@ import type { McpJob, McpRegistration, Session } from './types';
import { api } from './api';
import { Modal } from './components';
import { McpJobHistory } from './McpJobHistory';
import { approvalLabels, mcpPermissionContext } from '../shared/contracts/execution-policy.mjs';
import './McpPanel.css';
const active = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping'];
@@ -12,8 +13,8 @@ const stateName: Record<string, string> = { verified: '握手已核验', unverif
type View = { projectId: string; revision: number; protocolVersion: string; boundary: string; limits: Record<string, number>; registrations: McpRegistration[] };
type Draft = { name: string; executable: string; entry: string; timeoutMs: number };
export function McpPanel({ projectId, session, busy, onSession, onError }: {
projectId: string; session: Session | null; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void;
export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSession, onError }: {
projectId: string; session: Session | null; busy: boolean; approvalMode?: 'ask' | 'auto' | 'full'; onSession: (value: Session) => void; onError: (error: unknown) => void;
}) {
const [view, setView] = useState<View | null>(null), [jobs, setJobs] = useState<McpJob[]>([]);
const [working, setWorking] = useState(false), [error, setError] = useState(''), [notice, setNotice] = useState('');
@@ -25,6 +26,7 @@ export function McpPanel({ projectId, session, busy, onSession, onError }: {
const url = '/projects/' + projectId + '/mcp';
const busyJobs = jobs.some(job => active.includes(job.status));
const locked = busy || busyJobs || working;
const permission = mcpPermissionContext({ approvalMode }).action === 'execute' ? '任务中的已启用调用直接执行。' : '外部工具调用由工作台请求批准。';
useEffect(() => { mounted.current = true; return () => { mounted.current = false; generation.current++; }; }, []);
async function load(current = generation.current) {
@@ -89,16 +91,16 @@ export function McpPanel({ projectId, session, busy, onSession, onError }: {
const value = await api<McpRegistration>(url + '/configure', { id: registration.id, configurationRevision: registration.configurationRevision,
enabled: !!selectedTools[registration.id]?.length, allowedTools: selectedTools[registration.id] ?? [] });
revisions.current.set(value.id, -1);
}, selectedTools[registration.id]?.length ? '已保存所选工具并启用。每次调用仍需单独确认。' : '已停用该 MCP。');
}, selectedTools[registration.id]?.length ? '已保存所选工具并启用。' + permission : '已停用该 MCP。');
const disable = (registration: McpRegistration) => perform(async () => {
await api(url + '/configure', { id: registration.id, configurationRevision: registration.configurationRevision, enabled: false, allowedTools: [] });
revisions.current.set(registration.id, -1);
}, '该 MCP 已停用,后续请求不会再发送它的工具目录。');
return <section className="mcp-panel" aria-label="项目MCP工具管理" aria-busy={working}>
<header className="mcp-heading"><div><span className="mcp-kicker"><PlugZap size={15} />项目能力 / MCP</span><h3>受控连接外部工具</h3><p>登记本地 stdio 程序,读取实际握手与参数契约。每次探测和工具调用都需要确认,启用不代表自动执行。</p></div>
<header className="mcp-heading"><div><span className="mcp-kicker"><PlugZap size={15} />项目能力 / MCP</span><h3>连接外部工具</h3><p>登记本地 stdio 程序,探测实际握手后选择工具。{approvalMode === 'full' ? '完全访问权限下,任务中的已启用调用直接执行。' : '外部工具调用由工作台请求批准,提交调用后即可处理。'}</p></div>
<button type="button" className="button secondary" disabled={working} onClick={() => void perform(() => load(), '项目 MCP 状态已重新核对。')}><RefreshCw size={14} className={working ? 'spin' : ''} />刷新</button></header>
<div className="mcp-status-bar"><span><i className="mcp-light" />{view?.registrations.filter(item => item.enabled && item.status === 'verified').length ?? 0} 项已启用</span><span>{view?.registrations.length ?? 0} 项已登记</span><span>协议 {view?.protocolVersion ?? '2025-03-26'}</span><span><ShieldCheck size={14} />调用逐次审批</span></div>
<div className="mcp-status-bar"><span><i className="mcp-light" />{view?.registrations.filter(item => item.enabled && item.status === 'verified').length ?? 0} 项已启用</span><span>{view?.registrations.length ?? 0} 项已登记</span><span>协议 {view?.protocolVersion ?? '2025-03-26'}</span><span><ShieldCheck size={14} />{approvalLabels[approvalMode]} · {approvalMode === 'full' ? '直接执行' : '请求批准'}</span></div>
{error && <p className="mcp-alert" role="alert"><CircleAlert size={16} />{error}</p>}
{notice && <p className="mcp-notice" role="status"><Check size={16} />{notice}</p>}
{busy && <p className="mcp-warning">当前项目正在执行;完成或停止后才能修改 MCP 配置。</p>}
+6
View File
@@ -15,6 +15,12 @@
.mc-capabilities [data-capability="unsupported"] { color: #903c35; background: #fbefed; }
.mc-capabilities [data-capability="verified"] { color: #285c47; background: #eaf5ed; }
.mc-route-rejections { margin: 8px 0 0; color: #7c4c22; font-size: 12px; overflow-wrap: anywhere; }
.mc-routing-decision{margin-top:12px;border-top:1px solid var(--line);padding-top:10px;font-size:12px;line-height:1.7;overflow-wrap:anywhere;color:var(--muted)}
.mc-routing-decision summary{cursor:pointer;color:var(--ink);font-weight:600}
.mc-routing-decision ul{list-style:none;margin:10px 0 0;padding:0;display:grid;gap:10px}
.mc-routing-decision li{border-left:2px solid var(--line);padding-left:10px}
.mc-routing-decision li>span{display:block}
.mc-routing-decision summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
.mc-stream-receipt { border-top: 1px solid var(--border); margin-top: 10px; padding-top: 8px; }
.mc-stream-receipt code { display: block; overflow-wrap: anywhere; font-size: 11px; line-height: 1.7; }
.mc-stream-receipt .button { margin-top: 8px; }
+7 -5
View File
@@ -4,6 +4,7 @@ import { api, downloadArtifact } from './api';
import type { Config, ModelSelection, ModelSnapshot, RuntimeFailure } from './types';
import './ModelCenter.css';
import { ModelIdentityDetails } from './ModelIdentityDetails';
import { ModelRoutingDetails, type RoutingDecision } from './ModelRoutingDetails';
import type { ModelIdentity } from '../shared/contracts/model-identity.mjs';
import { ModelWaitSettings, type WaitSettings } from './ModelWaitSettings';
import { NativeParameters } from './NativeParameters';
@@ -24,7 +25,7 @@ const upstreamCapacity = (value: { model: string; upstreamModel?: CatalogModel }
type Connection = { 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 Attempt = { modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; upstreamResponse?: { requestId?: string | null; requestUrl?: string; responseUrl?: string | null; redirectMode?: string }; 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 Attempt = { routingDecision?: RoutingDecision; modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; upstreamResponse?: { requestId?: string | null; requestUrl?: string; responseUrl?: string | null; redirectMode?: string }; 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 }; waitSettings: WaitSettings; 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 }[];
@@ -150,7 +151,8 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
<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>
<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>
@@ -196,14 +198,14 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
</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>}
{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' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol ? protocolLabel(value.protocol) : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p><code>Run {value.runId}</code>{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}</p><code>原流 SHA256 {value.stream.sha256}</code>{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}</code>}{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.responseArtifactId!, "model-stream-" + value.id + ".sse"); })}>下载已保存的响应</button>}</div>}{value.requestUrl && <p className="mc-request-url">请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <><br />响应地址:{value.upstreamResponse.responseUrl}</>}</p>}{value.reason && <p className="mc-card-warning">{value.reason}</p>}{<ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model} />}{value.diagnostic && <ModelErrorDetails failure={value.diagnostic} />}{!value.diagnostic && value.upstreamResponse?.requestId && <p className="mc-help">上游请求 ID:{value.upstreamResponse.requestId}</p>}{value.requestArtifactId && value.sessionId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.requestArtifactId!, "model-request-" + value.id + ".json"); })}>下载实际请求</button>}{!!value.rejections?.length && <p className="mc-route-rejections">{value.rejections.map(item => item.connectionName + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}</p>}</article>)}</div></>}
{tab === 'attempts' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol ? protocolLabel(value.protocol) : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p><code>Run {value.runId}</code>{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}</p><code>原流 SHA256 {value.stream.sha256}</code>{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}</code>}{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.responseArtifactId!, "model-stream-" + value.id + ".sse"); })}>下载已保存的响应</button>}</div>}{value.requestUrl && <p className="mc-request-url">请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <><br />响应地址:{value.upstreamResponse.responseUrl}</>}</p>}{value.reason && <p className="mc-card-warning">{value.reason}</p>}<ModelRoutingDetails decision={value.routingDecision} /><ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model} />{value.diagnostic && <ModelErrorDetails failure={value.diagnostic} />}{!value.diagnostic && value.upstreamResponse?.requestId && <p className="mc-help">上游请求 ID:{value.upstreamResponse.requestId}</p>}{value.requestArtifactId && value.sessionId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.requestArtifactId!, "model-request-" + value.id + ".json"); })}>下载实际请求</button>}{!!value.rejections?.length && <p className="mc-route-rejections">{value.rejections.map(item => item.connectionName + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}</p>}</article>)}</div></>}
{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>)}
+4 -1
View File
@@ -10,7 +10,10 @@ export function ModelIdentityDetails({ identity, requestedModel }: { identity?:
<summary>{modelIdentityLabel(identity)}</summary>
<dl><dt>请求型号</dt><dd>{identity?.requestedModel ?? requestedModel}</dd>
<dt>上游报告型号</dt><dd>{identity?.reportedModels.length ? identity.reportedModels.join('、') : identity ? '未报告' : '历史记录未核对'}</dd>
<dt>处理方式</dt><dd>{identity?.policy === 'require-match' ? '不一致或无法核对时暂停' : '记录原结果和型号差异'}</dd>
<dt>请求核对策略</dt><dd>{!identity ? '历史记录未保存' : identity.policy === 'require-match' ? '严格核对型号' : '记录请求与返回型号'}</dd>
<dt>实际生效策略</dt><dd>{identity?.effectivePolicy === 'require-match' ? '不一致或无法核对时暂停' : identity?.effectivePolicy === 'record' ? '记录原结果和型号差异'
: '原记录未保存实际策略,请核对原任务结果'}</dd>
{identity?.effectivePolicySource === 'unrestricted-execution' && <><dt>生效依据</dt><dd>完全开放执行:记录型号差异后继续</dd></>}
{identity?.mapping && <><dt>映射依据</dt><dd>{identity.mapping.source}<br /><small>用户登记 · {identity.mapping.models.join('、')}</small></dd></>}
</dl><p>这里只核对接口报告的型号,不能据此认证底层模型。</p>
{source && <><p className="model-identity-hash">原响应 SHA-256 <code>{source.sha256}</code></p>
+30
View File
@@ -0,0 +1,30 @@
export type RoutingDecision = {
schemaVersion: number; mode: string; reason: string; selectedConnectionId: string | null; selectedBy?: string;
candidates: { connectionId: string; connectionName: string; model: string; connectionRevision: number; credentialRevision: number;
disposition: string; tier: string; unavailable?: string | null; requirements: string[];
capabilities: Record<string, { state: string; source: string }>;
reasons: { capability: string; state: string; source: string; reason: string }[];
catalog?: { id: string; fetchedAt: string | null; lifecycle: string | null } }[];
};
const labels: Record<string, string> = { text: '文本', tools: '工具', streaming: '流式', vision: '视觉', audio: '语音',
verified: '已验证', protocol_declared: '连接声明支持', upstream_declared: '上游目录声明支持', unknown: '未验证', unsupported: '明确不支持',
selected: '本次选中', eligible: '适配候选', excluded: '自动选择排除', unavailable: '当时不可用', lower_priority: '保留为未知后备',
'revision-bound-observation': '对应连接及凭据修订的观测', 'connection-declaration': '连接声明', 'upstream-model-list': '相符上游目录' };
const reasons: Record<string, string> = { 'known-capabilities': '自动适配:已知能力满足请求', 'unverified-fallback': '自动适配:未知能力后备尝试(未验证)',
'no-eligible-candidate': '自动适配:没有可用适配成员', 'explicit-selection': '显式选择:按原配置透传', 'restricted-capabilities': '按手动限制模式核对能力' };
export function ModelRoutingDetails({ decision }: { decision?: RoutingDecision }) {
if (!decision) return null;
return <details className="mc-routing-decision"><summary>{reasons[decision.reason] ?? '本次模型选择依据'}</summary>
<p>这是本次请求的选择记录。声明支持与实际验证分别记录;请求发出后的上游错误仍按原结果保留。</p>
<ul>{decision.candidates.map(candidate => <li key={candidate.connectionId}>
<strong>{candidate.connectionName} · {labels[candidate.disposition] ?? candidate.disposition}</strong>
<span>{candidate.model} · 连接修订 {candidate.connectionRevision} / 凭据修订 {candidate.credentialRevision}</span>
{candidate.requirements.map(key => <span key={key}>{labels[key] ?? key}:{labels[candidate.capabilities[key]?.state] ?? candidate.capabilities[key]?.state}
{' · '}{labels[candidate.capabilities[key]?.source] ?? candidate.capabilities[key]?.source}</span>)}
{candidate.reasons.map(reason => <span key={reason.capability}>{reason.reason} · {labels[reason.capability] ?? reason.capability}</span>)}
{candidate.unavailable && <span>{candidate.unavailable === 'previous-attempt' ? '本轮先前已尝试' : '连接停用、修订变化或当时不可用'}</span>}
{candidate.catalog && <span>目录型号 {candidate.catalog.id} · 获取于 {candidate.catalog.fetchedAt ?? '原目录未记录时间'}{candidate.catalog.lifecycle ? ' · ' + candidate.catalog.lifecycle : ''}</span>}
</li>)}</ul>
</details>;
}