feat: add bounded connection network diagnostics

This commit is contained in:
Agent Workbench Dev
2026-11-03 23:11:33 +08:00
parent dca6cbdb2c
commit 54dbe3d6fc
30 changed files with 683 additions and 40 deletions
+5 -1
View File
@@ -10,6 +10,7 @@ import { NativeParameters } from './NativeParameters';
import { ModelErrorDetails } from './ModelErrorDetails';
import { ModelBudgetSettings } from './ModelBudgetSettings';
import { modelRequestUrl, protocolLabel } from '../shared/contracts/model-endpoint.mjs';
import { ModelNetworkDiagnostics } from './ModelNetworkDiagnostics';
const previewUrl = (value: { protocol: string; baseUrl: string }) => { try { return modelRequestUrl(value); } catch { return '请填写有效的接口根地址'; } };
@@ -42,6 +43,7 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
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);
@@ -87,7 +89,7 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
const locked = working || busy;
return <section className="model-center" aria-label="模型控制台" aria-busy={working}>
<div className="mc-overview"><div><span className="mc-eyebrow">MODEL CONTROL</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], ['pools', '模型池', Layers3], ['budgets', '运行预算', Settings2], ['waits', '等待时限', Settings2], ['attempts', '请求账本', Route], ['imports', '配置导入', Settings2], ['credentials', '凭据保存', KeyRound], ['operations', '运行巡检', Activity]].map(([id, title, Icon]) => {
<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>}
@@ -117,6 +119,7 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
{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 }); })}>{selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
<button className="button secondary" disabled={locked} onClick={() => { if (value.id === 'legacy-default') { onLegacy(); return; } setDraft({ ...initial, ...value, modelIdentityAliasesText: (value.modelIdentityAliases ?? []).join(', '), streaming: value.streaming === true, capabilityDeclarations: { ...initial.capabilityDeclarations, ...value.capabilityDeclarations } }); setKey(''); setPersistKey(false); setEditing(true); }}>编辑</button>
<button className="button secondary" onClick={() => { setNetworkTarget(value.id); setTab('network'); }}>连接诊断</button>
{value.id !== 'legacy-default' && <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>
@@ -147,6 +150,7 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
<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={view.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> : <>
+3
View File
@@ -0,0 +1,3 @@
.mc-network{min-width:0}.mn-controls{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap}.mn-controls label{display:grid;gap:7px;min-width:220px;flex:1;max-width:470px;font-weight:600;color:#304b65}.mn-controls select{width:100%;min-height:40px;border:1px solid #adbdcd;border-radius:5px;background:#fff;padding:7px 10px;color:#17314a;font:inherit}.mn-controls .button{min-height:40px}.mn-endpoint{overflow-wrap:anywhere;margin:12px 0 8px;font-family:Consolas,monospace;font-size:12px;color:#304b65;line-height:1.7}.mn-endpoint span{color:#53647c}.mn-scope{display:flex;gap:9px;align-items:flex-start;color:#435b73;line-height:1.8;margin:10px 0 18px;font-size:13px}.mn-scope svg{flex-shrink:0;margin-top:4px}.mn-link{padding:0;border:0;text-decoration:underline;color:#174c78;background:none;font:inherit;cursor:pointer}.mn-error,.mn-warning{padding:12px 14px;border-left:3px solid #ac6a20;background:#fff5e7;color:#75420f;line-height:1.8;overflow-wrap:anywhere}.mn-error{color:#942e29;border-color:#b43c34;background:#fff0ed}.mn-workspace{display:grid;grid-template-columns:minmax(0,1fr) 230px;border:1px solid #c3d0dc;border-radius:6px;background:white;overflow:hidden}.mn-result{min-width:0;padding:20px}.mn-result-heading{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;border-bottom:1px solid #d2dce5;padding-bottom:15px}.mn-result-heading p{font-size:12px;color:#53647c;margin:9px 0 0;line-height:1.8}.mn-revision{font-size:12px;color:#53647c;white-space:nowrap}.mn-status{display:inline-block;font-size:12px;line-height:1.7;font-weight:600;color:#435b73}.mn-result-heading .mn-status{font-size:16px}.mn-status-passed{color:#246348}.mn-status-failed{color:#9d352d}.mn-status-partial{color:#80500e}.mn-status-running{color:#195d94}.mn-dns{padding:18px 0}.mn-dns h4{font-size:13px;margin:0;color:#1c354e}.mn-dns h4 span{font-size:12px;color:#53647c;font-weight:400;margin-left:8px}.mn-dns p{color:#94382e;overflow-wrap:anywhere;line-height:1.8}.mn-dns ul{list-style:none;margin:10px 0 0;padding:0;display:grid;gap:6px}.mn-dns li{display:flex;gap:12px;font-size:12px;align-items:flex-start;line-height:1.7}.mn-dns li>span{color:#53647c;white-space:nowrap}.mn-dns code{color:#25445d;overflow-wrap:anywhere}.mn-paths{border-collapse:collapse;width:100%;table-layout:fixed;color:#28425a;font-size:12px}.mn-paths caption{text-align:left;color:#1c354e;font-weight:600;margin:0 0 10px;font-size:13px}.mn-paths th,.mn-paths td{text-align:left;vertical-align:top;padding:12px 7px;border-bottom:1px solid #d6e0e9;overflow-wrap:anywhere;line-height:1.8}.mn-paths thead th{background:#edf2f6;font-weight:500;color:#4b6277}.mn-paths th:first-child{width:27%}.mn-paths th:nth-child(2){width:16%}.mn-paths th:nth-child(3){width:25%}.mn-paths code,.mn-paths small{display:block;font-size:12px;font-weight:400;line-height:1.8;color:#53647c;margin-top:5px;overflow-wrap:anywhere}.mn-paths small svg{vertical-align:middle;color:#246348;margin-right:3px}.mn-outcome{color:#80500e;line-height:1.8}.mn-transport{margin-top:18px;font-size:12px;color:#435b73}.mn-transport summary{cursor:pointer;padding:8px 0;color:#244e72;font-size:13px}.mn-transport dl{display:grid;grid-template-columns:105px minmax(0,1fr);gap:9px;line-height:1.7}.mn-transport dt{color:#53647c}.mn-transport dd{margin:0;overflow-wrap:anywhere}.mn-history{background:#f5f8fa;border-left:1px solid #d2dce5;padding:18px 14px;min-width:0}.mn-history h4{display:flex;align-items:center;gap:7px;font-size:13px;color:#304b65;margin:0 0 10px}.mn-history p{color:#53647c;font-size:12px;line-height:1.8}.mn-history button{display:grid;gap:4px;padding:12px 10px;width:100%;margin-top:8px;text-align:left;background:transparent;border:1px solid transparent;border-radius:4px;cursor:pointer;color:#304b65;font:inherit}.mn-history button[aria-pressed=true]{border-color:#9eb6ca;background:#fff}.mn-history button:hover{background:#e8eff5}.mn-history button span,.mn-history button small{font-size:12px;line-height:1.7;color:#53647c}.mn-history button strong{font-size:13px;line-height:1.7;font-weight:600}.mn-empty{padding:28px 4px;min-height:210px;color:#486580}.mn-empty h4{color:#25445d;font-size:15px;margin:14px 0 8px}.mn-empty p{max-width:520px;line-height:1.9;margin:0;color:#53647c}.mc-network button:focus-visible,.mc-network select:focus-visible,.mc-network summary:focus-visible{outline:2px solid #256c9e;outline-offset:3px}
@media(max-width:900px){.mn-workspace{grid-template-columns:minmax(0,1fr)}.mn-history{border-left:0;border-top:1px solid #d2dce5}.mn-history button{max-width:100%}.mn-result{padding:16px}.mn-history{max-height:300px;overflow:auto}}
@media(max-width:620px){.mn-controls label{min-width:100%;max-width:none}.mn-controls .button{min-height:44px;flex:1;justify-content:center}.mn-result{padding:13px 10px}.mn-result-heading{flex-wrap:wrap}.mn-paths th,.mn-paths td{padding:10px 4px}.mn-paths th:first-child{width:24%}.mn-paths th:nth-child(2){width:18%}.mn-paths th:nth-child(3){width:25%}.mn-transport dl{grid-template-columns:85px minmax(0,1fr)}.mn-history button{min-height:44px}.mn-dns h4 span{display:block;margin:7px 0 0}}
+98
View File
@@ -0,0 +1,98 @@
import { useEffect, useRef, useState } from 'react';
import { Check, CircleHelp, History, Play, RefreshCw, Square, Wifi } from 'lucide-react';
import { api } from './api';
import './ModelNetworkDiagnostics.css';
type Connection = { id: string; name: string; baseUrl: string; revision: number };
type Trial = { mode: string; status: string; stage: string; address?: string; family?: string; code?: string; tcpMs?: number; tlsMs?: number;
tls?: string; tlsProtocol?: string; certificateAuthorized?: boolean; attempts: { address: string; code?: string }[] };
type Job = { id: string; connectionId: string; connectionRevision: number; connectionName: string; status: string; startedAt: string; finishedAt: string | null;
stale: boolean; code?: string; elapsedMs: number; budgetMs: number; target: { endpoint: string; host: string; port: number; scheme: string };
transport: { autoSelectFamily: boolean; familyAttemptTimeoutMs: number; connectTimeoutMs: number };
route: { proxyConfigured: boolean; noProxyConfigured: boolean; customTransport: boolean };
stages: { dns?: { status: string; elapsedMs?: number; code?: string; addresses?: { address: string; family: number }[] } }; trials: Trial[] };
type View = { jobs: Job[]; active: number; retained: number };
const labels: Record<string, string> = { passed: '通过', partial: '部分路径可连接', failed: '未通过', running: '检查中', pending: '等待',
cancelled: '已停止', interrupted: '已中断', skipped: '未检查' };
const reasons: Record<string, string> = { ENOTFOUND: '域名没有解析结果', EAI_AGAIN: 'DNS 暂时不可用', DNS_NO_ADDRESSES: '没有可用的 IP 地址',
ECONNREFUSED: '目标拒绝连接', ENETUNREACH: '目标网络不可达', EHOSTUNREACH: '目标主机不可达', TCP_CONNECT_TIMEOUT: '建立 TCP 连接超时',
TLS_HANDSHAKE_TIMEOUT: '等待 TLS 握手超时', SELF_SIGNED_CERT_IN_CHAIN: '证书链未受信任', DEPTH_ZERO_SELF_SIGNED_CERT: '证书未受信任',
UNABLE_TO_VERIFY_LEAF_SIGNATURE: '无法核验证书链', ERR_TLS_CERT_ALTNAME_INVALID: '证书与域名不匹配', CERT_HAS_EXPIRED: '证书已过期',
ADDRESS_FAMILY_UNAVAILABLE: 'DNS 未返回此地址族', DNS_NOT_COMPLETED: 'DNS 尚未通过', DIAGNOSTIC_DEADLINE: '已到达诊断时间上限',
DIAGNOSTIC_CANCELLED: '用户停止了本次诊断', HOST_STOPPED: '执行宿主停止了诊断', HOST_RESTARTED: '宿主重启,原诊断未重放',
DIAGNOSTIC_INTERNAL_ERROR: '诊断未能完整保存,请核对宿主状态' };
const detail = (code?: string) => code ? (reasons[code] ?? '连接检查未完成') + ' · ' + code : '';
const duration = (value?: number) => value === undefined ? '—' : value.toLocaleString() + ' ms';
export function ModelNetworkDiagnostics({ connections, initialId, disabled }: { connections: Connection[]; initialId?: string; disabled: boolean }) {
const fallback = connections.find(value => value.id === initialId) ?? connections.find(value => value.id !== 'legacy-default') ?? connections[0];
const [connectionId, setConnectionId] = useState(fallback?.id ?? '');
const [view, setView] = useState<View | null>(null), [focused, setFocused] = useState('');
const [working, setWorking] = useState(false), [error, setError] = useState('');
const mounted = useRef(true), generation = useRef(0);
const selected = connections.find(value => value.id === connectionId);
const jobs = view?.jobs.filter(value => value.connectionId === connectionId) ?? [];
const job = jobs.find(value => value.id === focused) ?? jobs[0];
const activeJob = view?.jobs.find(value => value.status === 'running');
async function load() {
const marker = ++generation.current, result = await api<View>('/model-center/network-diagnostics');
if (mounted.current && generation.current === marker) setView(result);
}
useEffect(() => { mounted.current = true; void load().catch(cause => { if (mounted.current) setError(cause.message); });
return () => { mounted.current = false; generation.current++; }; }, []);
useEffect(() => {
if (!view?.active) return;
const timer = window.setInterval(() => { void load().catch(cause => { if (mounted.current) setError(cause.message); }); }, 600);
return () => window.clearInterval(timer);
}, [view?.active]);
useEffect(() => { if (!selected && fallback) { setConnectionId(fallback.id); setFocused(''); } }, [selected, fallback?.id]);
async function act(operation: () => Promise<void>) {
setWorking(true); setError('');
try { await operation(); if (mounted.current) await load(); }
catch (cause) { if (mounted.current) { setError(cause instanceof Error ? cause.message : '操作未完成,请刷新核对原记录。'); void load().catch(() => {}); } }
finally { if (mounted.current) setWorking(false); }
}
return <section className="mc-network" aria-label="模型连接诊断">
<div className="mc-section-title"><div><h3>连接诊断</h3><p>检查端点的 DNS、TCP 和 TLS。无需 Key,不发送模型请求。</p></div>
<button className="button secondary" aria-label="刷新连接诊断" disabled={working} onClick={() => void act(load)}><RefreshCw size={15} />刷新</button></div>
<div className="mn-controls"><label>诊断连接<select aria-label="诊断连接" value={connectionId} disabled={working} onChange={event => { setConnectionId(event.target.value); setFocused(''); setError(''); }}>
{connections.map(value => <option key={value.id} value={value.id}>{value.name}</option>)}</select></label>
<button className="button primary" disabled={disabled || working || !selected || !view || !!view.active} onClick={() => void act(async () => {
const result = await api<{ job: Job }>('/model-center/network-diagnostics', { id: selected!.id, revision: selected!.revision });
if (mounted.current) setFocused(result.job.id);
})}><Play size={15} />开始直连检查</button>
{activeJob && <button className="button secondary" disabled={working} onClick={() => void act(async () => {
await api('/model-center/network-diagnostics/' + activeJob.id + '/stop', {});
})}><Square size={14} />停止诊断</button>}
</div>
{selected && <p className="mn-endpoint">{selected.baseUrl} <span>· 配置修订 {selected.revision}</span></p>}
<p className="mn-scope"><CircleHelp size={16} /><span>本次只检查端点直连路径,保留证书校验;握手通过不能证明 Key、型号或模型能力可用。检查最多约 12 秒,离开后结果保留。</span></p>
{error && <p className="mn-error" role="alert">{error}</p>}
{activeJob && activeJob.connectionId !== connectionId && <p className="mn-scope">{activeJob.connectionName} 正在检查。<button type="button" className="mn-link" onClick={() => { setConnectionId(activeJob.connectionId); setFocused(activeJob.id); }}>查看正在运行的诊断</button></p>}
{!view ? <p className="mc-empty">正在读取诊断记录…</p> : <div className="mn-workspace">
<div className="mn-result" aria-label="本次连接诊断结果">
{!job ? <div className="mn-empty"><Wifi size={24} /><h4>先检查连接,再判断问题阶段</h4><p>选择已保存的连接并开始检查。这里会保留解析地址、连接耗时和证书核对结果,原任务不会被重新执行。</p></div> : <>
<header className="mn-result-heading"><div><span className={'mn-status mn-status-' + job.status} role="status">{job.status === 'passed' ? '直连握手通过' : labels[job.status] ?? job.status}</span>
<p>{job.connectionName} · {new Date(job.startedAt).toLocaleString()} · {duration(job.elapsedMs)}</p></div><span className="mn-revision">修订 {job.connectionRevision}</span></header>
{job.stale && <p className="mn-warning">连接配置已变化。下方是原修订 {job.connectionRevision} 的记录,请重新检查当前连接。</p>}
{(job.route.proxyConfigured || job.route.customTransport) && <p className="mn-warning">{job.route.customTransport ? '此宿主使用自定义模型运输。' : '宿主已配置环境代理' + (job.route.noProxyConfigured ? '及 NO_PROXY 规则。' : '。')}本次未发送代理 CONNECT 或模型 HTTP 请求,实际 API 路线尚未核验。</p>}
<div className="mn-dns"><h4>DNS 地址解析 <span>{labels[job.stages.dns?.status ?? 'pending']} · {duration(job.stages.dns?.elapsedMs)}</span></h4>
{job.stages.dns?.code && <p>{detail(job.stages.dns.code)}</p>}
{!!job.stages.dns?.addresses?.length && <ul>{job.stages.dns.addresses.map((value, index) => <li key={value.address + index}><span>IPv{value.family}</span><code>{value.address}</code></li>)}</ul>}
</div>
<table className="mn-paths"><caption>直连路径与握手阶段</caption><thead><tr><th>路径</th><th>TCP</th><th>TLS</th><th>结果</th></tr></thead>
<tbody>{job.trials.map(trial => <tr key={trial.mode}><th scope="row">{({ auto: '自动选择', ipv4: '固定 IPv4', ipv6: '固定 IPv6' } as Record<string, string>)[trial.mode] ?? trial.mode}
{trial.address && <code>{trial.address}</code>}</th><td>{duration(trial.tcpMs)}</td><td>{trial.tls === 'not_applicable' ? 'HTTP 端点无需 TLS' : trial.tlsProtocol ?? duration(trial.tlsMs)}
{trial.certificateAuthorized && <small><Check size={12} />证书已核对 · {duration(trial.tlsMs)}</small>}</td><td><span className={'mn-status mn-status-' + trial.status}>{trial.status === 'running' ? (trial.stage === 'tls' ? 'TLS 握手中' : 'TCP 连接中') : labels[trial.status] ?? trial.status}</span>
{trial.code && <small>{detail(trial.code)}</small>}{trial.attempts.some(value => value.code) && <small>候选地址失败:{trial.attempts.filter(value => value.code).map(value => value.address + ' · ' + value.code).join(';')}</small>}</td></tr>)}</tbody></table>
{job.code && <p className="mn-outcome">{detail(job.code)}</p>}
<details className="mn-transport"><summary>查看原诊断范围与运输参数</summary><dl><dt>原端点</dt><dd>{job.target.endpoint}</dd><dt>检查目标</dt><dd>{job.target.host}:{job.target.port}</dd>
<dt>自动地址族</dt><dd>{job.transport.autoSelectFamily ? '开启' : '关闭'} · 候选间隔 {job.transport.familyAttemptTimeoutMs} ms</dd><dt>连接 / 总时限</dt><dd>{job.transport.connectTimeoutMs} / {job.budgetMs} ms</dd>
<dt>模型 API</dt><dd>未请求;能力与连接健康结论保持原记录</dd><dt>记录</dt><dd>{job.id}</dd></dl></details>
</>}
</div>
<aside className="mn-history" aria-label="连接诊断历史"><h4><History size={16} />近期检查</h4><p>保存最近 {view.retained} 条;点击查看原记录。</p>
{!jobs.length && <p>这条连接还没有检查记录。</p>}{jobs.map(value => <button key={value.id} type="button" aria-pressed={job?.id === value.id} onClick={() => setFocused(value.id)}><span>{new Date(value.startedAt).toLocaleString()}</span><strong>{labels[value.status] ?? value.status}{value.stale ? ' · 旧配置' : ''}</strong><small>修订 {value.connectionRevision} · {duration(value.elapsedMs)}</small></button>)}
</aside>
</div>}
</section>;
}
+1 -1
View File
@@ -76,7 +76,7 @@ export class HostAuthority {
deliveries: runtime.deliveries?.active.size ?? 0, fileBatches: runtime.changeSets?.projects.size ?? 0,
workspaces: (runtime.workspaces?.projects.size ?? 0) + (runtime.workspaces?.pending.size ?? 0),
research: runtime.research?.active.size ?? 0, engines: runtime.engines?.active.size ?? 0, browsers: runtime.browser?.active.size ?? 0,
plans: runtime.taskPlans?.active.size ?? 0, modelRequests: provider.activeRequests ?? 0, modelQueue: provider.hub?.waiting ?? 0,
plans: runtime.taskPlans?.active.size ?? 0, networkDiagnostics: provider.hub?.networkChecks?.active.size ?? 0, modelRequests: provider.activeRequests ?? 0, modelQueue: provider.hub?.waiting ?? 0,
modelLeases: [...(provider.hub?.leases.values() ?? [])].reduce((sum, value) => sum + value, 0) };
const unresolved = [...store.core.tool.values()].filter(value => value.requiresVerification).map(value => ({ id: value.id, sessionId: value.sessionId, taskId: value.taskId, runId: value.runId }));
return { counts, active: Object.values(counts).some(value => value > 0), unresolvedTools: unresolved.length,
+2
View File
@@ -10,6 +10,7 @@ import { modelWaitSettings } from './request-deadline.mjs';
import { sanitizeModelText } from './upstream-error.mjs';
import { nativeParameterSettings } from '../../shared/contracts/native-parameters.mjs';
import { modelIdentitySettings } from '../../shared/contracts/model-identity.mjs';
import { NetworkDiagnostics } from './network-diagnostics.mjs';
const legacyId = 'legacy-default';
const stamp = () => new Date().toISOString();
@@ -129,6 +130,7 @@ export class ModelHub {
: this.connections().find(value => value.id === selected.id)?.name;
return { ...selected, name: name ?? '原模型连接' };
}
networkDiagnostics() { return this.networkChecks ??= new NetworkDiagnostics(this); }
connection(id) { const value = this.connections().find(item => item.id === id); if (!value) throw error('模型连接不存在。', 404); return value; }
async probe(id, scope = 'text') {
if (!['text', 'tools', 'streaming', 'vision'].includes(scope)) throw error('请选择文本、工具调用、流式或图像检测。');
+81
View File
@@ -0,0 +1,81 @@
import { randomUUID } from 'node:crypto';
import { ModelTransport } from './transport.mjs';
import { probeNetwork } from './network-probe.mjs';
const problem = (message, status = 409) => Object.assign(new Error(message), { status });
const terminal = new Set(['passed', 'partial', 'failed', 'cancelled', 'interrupted']);
export class NetworkDiagnostics {
constructor(hub, options = {}) {
this.hub = hub; this.options = options; this.active = new Map();
this.jobs = structuredClone(hub.store.storage.meta('modelNetworkDiagnostics', []));
let changed = false;
for (const job of this.jobs) if (!terminal.has(job.status)) {
job.status = 'interrupted'; job.finishedAt = new Date().toISOString(); job.code = 'HOST_RESTARTED';
for (const trial of job.trials) if (['running', 'pending'].includes(trial.status)) trial.status = 'interrupted';
if (job.stages.dns?.status === 'running') job.stages.dns.status = 'interrupted';
changed = true;
}
if (changed) this.save();
}
save() { this.hub.store.storage.transaction(() => this.hub.store.storage.setMeta('modelNetworkDiagnostics', this.jobs)); }
view() {
return { jobs: this.jobs.map(job => {
const connection = this.hub.connections().find(row => row.id === job.connectionId);
return { ...structuredClone(job), stale: !connection || connection.revision !== job.connectionRevision,
currentConnectionRevision: connection?.revision ?? null };
}).reverse(), active: this.active.size, retained: 30, httpRequests: 0, modelRequests: 0 };
}
start(input) {
if (!input || Object.keys(input).length !== 2 || Object.keys(input).some(key => !['id', 'revision'].includes(key)) || !Number.isSafeInteger(input.revision)) throw problem('连接诊断需要所选连接及其原修订。', 400);
if (this.closing || this.hub.provider.requestsClosing) throw problem('执行宿主正在停止连接诊断。');
if (this.active.size || this.hub.probing || this.hub.provider.activeRequests) throw problem('请等待正在执行的模型请求或连接诊断结束。');
const connection = this.hub.connection(input.id);
if (connection.revision !== input.revision) throw problem('连接已变化,请刷新后重新选择诊断。');
const url = new URL(connection.baseUrl);
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw problem('连接地址无法用于网络诊断。', 400);
const provider = this.hub.provider, customTransport = !!provider.fetcher;
const transport = provider.transport ??= new ModelTransport();
const profile = structuredClone(transport.profile);
const target = { endpoint: connection.baseUrl, origin: url.origin, host: url.hostname.replace(/^\[|\]$/g, ''),
port: Number(url.port || (url.protocol === 'https:' ? 443 : 80)), scheme: url.protocol };
const budgetMs = this.options.budgetMs ?? Math.min(12000, profile.connectTimeoutMs + 2000);
const job = { schemaVersion: 1, id: randomUUID(), connectionId: connection.id, connectionRevision: connection.revision,
connectionName: connection.name, status: 'running', startedAt: new Date().toISOString(), finishedAt: null,
target, transport: profile, route: { kind: 'direct-endpoint-only', proxyConfigured: profile.httpProxyConfigured || profile.httpsProxyConfigured,
noProxyConfigured: profile.noProxyConfigured, customTransport, modelApiRouteVerified: false },
budgetMs, stages: {}, trials: [], elapsedMs: 0, httpRequests: 0, modelRequests: 0, credentialAccess: false };
const previous = this.jobs;
this.jobs = [...this.jobs.slice(-29), job];
try { this.save(); } catch (error) { this.jobs = previous; throw error; }
const controller = new AbortController(), operation = { job, controller, promise: null };
this.active.set(job.id, operation);
const timer = setTimeout(() => controller.abort({ code: 'DIAGNOSTIC_DEADLINE' }), budgetMs);
operation.promise = Promise.resolve().then(async () => {
const result = await probeNetwork(target, profile, { ...this.options,
...(transport.connect?.lookup ? { lookup: transport.connect.lookup } : {}), signal: controller.signal,
update: result => { Object.assign(job, result); this.save(); } });
Object.assign(job, result);
if (controller.signal.aborted) { job.status = controller.signal.reason?.code === 'DIAGNOSTIC_DEADLINE' ? 'failed' : 'cancelled'; job.code = controller.signal.reason?.code; }
else { const trials = job.trials.filter(row => row.status !== 'skipped'); const passed = trials.filter(row => row.status === 'passed').length;
job.status = job.stages.dns.status !== 'passed' || !passed ? 'failed' : passed === trials.length ? 'passed' : 'partial'; }
}).catch(() => { job.status = 'failed'; job.code = 'DIAGNOSTIC_INTERNAL_ERROR'; }).finally(() => {
clearTimeout(timer); job.finishedAt = new Date().toISOString();
try { this.save(); } finally { this.active.delete(job.id); }
});
operation.promise.catch(() => {});
return { job: this.view().jobs.find(row => row.id === job.id) };
}
async stop(id, input) {
if (!input || Object.keys(input).length) throw problem('停止诊断不接受额外参数。', 400);
const job = this.jobs.find(row => row.id === id); if (!job) throw problem('连接诊断记录不存在。', 404);
const operation = this.active.get(id);
operation?.controller.abort({ code: 'DIAGNOSTIC_CANCELLED' }); await operation?.promise;
return { job: this.view().jobs.find(row => row.id === id) };
}
async stopAll() {
this.closing = true;
const operations = [...this.active.values()];
for (const operation of operations) operation.controller.abort({ code: 'HOST_STOPPED' });
await Promise.all(operations.map(operation => operation.promise));
}
}
+89
View File
@@ -0,0 +1,89 @@
import dns from 'node:dns';
import net from 'node:net';
import tls from 'node:tls';
import { performance } from 'node:perf_hooks';
const elapsed = start => Math.max(0, Math.round(performance.now() - start));
const code = error => /^[A-Z0-9_]{1,80}$/.test(error?.code ?? '') ? error.code : 'NETWORK_CHECK_FAILED';
const cancelled = signal => Object.assign(new Error('连接诊断已停止。'), { code: signal.reason?.code ?? 'DIAGNOSTIC_CANCELLED' });
export async function probeNetwork(target, profile, { signal, update, lookup = dns.lookup, ca, stageTimeoutMs = profile.connectTimeoutMs } = {}) {
const started = performance.now(), stages = { dns: { status: 'running', startedAt: new Date().toISOString() } };
const trials = ['auto', 'ipv4', 'ipv6'].map(mode => ({ mode, status: 'pending', stage: 'dns', attempts: [] }));
let updateError;
const publish = () => { try { update?.(structuredClone({ stages, trials, elapsedMs: elapsed(started) })); } catch (error) { updateError ??= error; } };
const lookupStart = performance.now(); let addresses;
publish();
try {
addresses = await new Promise((resolve, reject) => {
let done = false;
const finish = (error, value) => { if (done) return; done = true; signal?.removeEventListener('abort', abort); error ? reject(error) : resolve(value); };
const abort = () => finish(cancelled(signal));
if (signal?.aborted) { abort(); return; }
signal?.addEventListener('abort', abort, { once: true });
const family = net.isIP(target.host);
if (family) { finish(null, [{ address: target.host, family }]); return; }
try { lookup(target.host, { all: true, verbatim: true }, (error, rows) => finish(error, rows)); }
catch (error) { finish(error); }
});
addresses = addresses.filter(row => [4, 6].includes(row.family) && net.isIP(row.address) === row.family).slice(0, 32);
if (!addresses.length) throw Object.assign(new Error('没有可用地址。'), { code: 'DNS_NO_ADDRESSES' });
stages.dns = { ...stages.dns, status: 'passed', elapsedMs: elapsed(lookupStart), addresses };
} catch (error) {
stages.dns = { ...stages.dns, status: signal?.aborted ? 'cancelled' : 'failed', elapsedMs: elapsed(lookupStart), code: code(error) };
for (const trial of trials) { trial.status = signal?.aborted ? 'cancelled' : 'skipped'; trial.code = 'DNS_NOT_COMPLETED'; }
publish(); return { stages, trials, elapsedMs: elapsed(started) };
}
publish();
if (updateError) throw updateError;
await Promise.all(trials.map(trial => new Promise(resolve => {
const candidates = trial.mode === 'auto' ? addresses : addresses.filter(row => row.family === (trial.mode === 'ipv4' ? 4 : 6));
if (!candidates.length) { trial.status = 'skipped'; trial.code = 'ADDRESS_FAMILY_UNAVAILABLE'; publish(); resolve(); return; }
const began = performance.now(); let tcp, secure, timer, finished = false, tcpConnected = false, tlsStarted;
const finish = (status, error) => {
if (finished) return; finished = true; clearTimeout(timer); signal?.removeEventListener('abort', abort);
if (trial.stage === 'tcp') trial.tcpMs = elapsed(began); else if (tlsStarted !== undefined) trial.tlsMs = elapsed(tlsStarted);
trial.status = status; trial.elapsedMs = elapsed(began); if (error) trial.code = code(error);
const sockets = [...new Set([secure, tcp].filter(Boolean))];
for (const socket of sockets) socket.destroy();
// A final state means owned sockets have actually closed, including cancellation.
Promise.all(sockets.map(socket => socket.closed ? null : new Promise(done => socket.once('close', done))))
.then(() => { publish(); resolve(); });
};
const abort = () => finish('cancelled', cancelled(signal));
if (signal?.aborted) { abort(); return; }
signal?.addEventListener('abort', abort, { once: true });
trial.status = 'running'; trial.stage = 'tcp'; publish();
timer = setTimeout(() => finish('failed', { code: trial.stage === 'tcp' ? 'TCP_CONNECT_TIMEOUT' : 'TLS_HANDSHAKE_TIMEOUT' }), stageTimeoutMs);
const frozenLookup = (_host, options, callback) => options.all ? callback(null, candidates)
: callback(null, candidates[0].address, candidates[0].family);
try {
tcp = net.createConnection({ host: target.host, port: target.port, lookup: frozenLookup,
autoSelectFamily: profile.autoSelectFamily, autoSelectFamilyAttemptTimeout: profile.familyAttemptTimeoutMs });
tcp.on('error', error => finish('failed', error));
tcp.on('connectionAttempt', (address, port, family) => { if (trial.attempts.length < 32) trial.attempts.push({ address, port, family }); });
tcp.on('connectionAttemptFailed', (address, _port, _family, error) => {
const attempt = trial.attempts.findLast(row => row.address === address); if (attempt) attempt.code = code(error);
});
tcp.once('connect', () => {
if (finished) return; tcpConnected = true;
trial.tcpMs = elapsed(began); trial.address = tcp.remoteAddress; trial.family = tcp.remoteFamily;
if (target.scheme === 'http:') { trial.tls = 'not_applicable'; finish('passed'); return; }
trial.stage = 'tls'; tlsStarted = performance.now(); publish();
try {
secure = tls.connect({ socket: tcp, host: target.host, servername: net.isIP(target.host) ? undefined : target.host,
rejectUnauthorized: true, ...(ca ? { ca } : {}) });
secure.on('error', error => finish('failed', error));
secure.once('secureConnect', () => {
trial.certificateAuthorized = secure.authorized === true; trial.tlsProtocol = secure.getProtocol();
trial.certificateFingerprint256 = secure.getPeerCertificate().fingerprint256;
finish(secure.authorized ? 'passed' : 'failed', secure.authorized ? null : { code: 'TLS_CERTIFICATE_REJECTED' });
});
} catch (error) { finish('failed', error); }
});
tcp.once('close', () => { if (!finished) finish('failed', { code: tcpConnected ? 'TLS_CONNECTION_CLOSED' : 'TCP_CONNECTION_CLOSED' }); });
} catch (error) { finish('failed', error); }
})));
if (updateError) throw updateError;
return { stages, trials, elapsedMs: elapsed(started) };
}
+8 -1
View File
@@ -187,6 +187,13 @@ return async (request, response) => {
const hub = provider.modelHub(store);
const importer = () => hub.importer ??= new ConfigImporter(hub);
if (method === 'GET' && route === '/api/model-center') return json(response, hub.view());
if (method === 'GET' && route === '/api/model-center/network-diagnostics') return json(response, hub.networkDiagnostics().view());
const networkStop = route.match(/^\/api\/model-center\/network-diagnostics\/([a-f0-9-]{36})\/stop$/i);
if (method === 'POST' && networkStop) return json(response, await hub.networkDiagnostics().stop(networkStop[1], await body(request)));
if (method === 'POST' && route === '/api/model-center/network-diagnostics') {
if (runtime.hasActivity()) throw Object.assign(new Error('请等待当前任务或诊断结束,再开始新的连接诊断。'), { status: 409 });
return json(response, hub.networkDiagnostics().start(await body(request)), 201);
}
if (method === 'GET' && route === '/api/model-center/selection') return json(response, {
config: { ...store.config, hasKey: provider.hasKey() }, modelSelection: hub.selectionView(),
});
@@ -195,7 +202,7 @@ return async (request, response) => {
if (method === 'POST') {
const input = await body(request);
if (route === '/api/model-center/toggle') return json(response, hub.toggle(input.id, input.enabled));
if (runtime.hasActivity()) throw Object.assign(new Error('请先停止正在运行的任务,再修改或测试模型配置。'), { status: 409 });
if (runtime.hasActivity() || hub.networkChecks?.active.size) throw Object.assign(new Error('请等待正在运行的任务或连接诊断结束,再修改或测试模型配置。'), { status: 409 });
if (route === '/api/model-center/runtime-budgets') {
store.saveConfig(validateRuntimeBudgets(input));
return json(response, { config: { ...store.config, hasKey: provider.hasKey() }, modelSelection: hub.selectionView() });
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.24.5';
export const APP_VERSION = '1.24.6';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+6 -1
View File
@@ -10,6 +10,7 @@ import { createRequestHandler, createSessionPublisher } from './app.mjs';
import { APP_VERSION } from './diagnostics.mjs';
import { hostAuthority } from '../core/desktop/host-authority.mjs';
import { CredentialVault } from '../core/models/credential-vault.mjs';
import { NetworkDiagnostics } from '../core/models/network-diagnostics.mjs';
// Keep the existing objects and their in-memory connection. No credential is
// extracted, transferred, returned, or persisted by this operation.
@@ -22,6 +23,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
if (runtime.filePreviews?.active.size || runtime.filePreviews?.pending) throw new Error('Close local HTML previews before upgrading.');
if (runtime.browsing?.active.size || runtime.previews?.active.size || runtime.evaluations?.active.size || runtime.environments?.active.size || runtime.active.size || runtime.waiters.size || runtime.workers?.active.size || runtime.controlledEngines?.drivers.size || runtime.mcp?.active.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size || runtime.research?.active.size || runtime.engines?.active.size || runtime.browser?.active.size || runtime.taskPlans?.active.size) throw new Error('Wait for active evaluations, environments, tasks, workers, controlled engines, MCP operations, checks, Git deliveries, file batches, workspaces, research, engines, browsers, task plans and approvals to finish before upgrading.');
if (provider.activeRequests || provider.hub?.waiting || [...(provider.hub?.leases.values() ?? [])].some(count => count > 0)) throw new Error('Wait for active model requests and probes before upgrading.');
if (provider.hub?.networkChecks?.active.size) throw new Error('Wait for active connection diagnostics before upgrading.');
const root = fs.realpathSync.native(path.resolve(appDirectory));
if (!fs.existsSync(path.join(root, 'dist-client', 'index.html'))) throw new Error('The new client bundle is missing.');
const oldHandlers = server.listeners('request');
@@ -31,7 +33,8 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
const oldModelPrototypes = { hub: provider.hub ? Object.getPrototypeOf(provider.hub) : null,
importer: provider.hub?.importer ? Object.getPrototypeOf(provider.hub.importer) : null,
vault: provider.hub?.credentialVault ? Object.getPrototypeOf(provider.hub.credentialVault) : null };
vault: provider.hub?.credentialVault ? Object.getPrototypeOf(provider.hub.credentialVault) : null,
network: provider.hub?.networkChecks ? Object.getPrototypeOf(provider.hub.networkChecks) : null };
const oldStoreProperties = { ...store };
const oldRuntimeProperties = { filePreviews: runtime.filePreviews, browsing: runtime.browsing, previews: runtime.previews, evaluations:runtime.evaluations, environments: runtime.environments, appDirectory: runtime.appDirectory, workers: runtime.workers, controlledEngines: runtime.controlledEngines, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser, taskPlans: runtime.taskPlans, projectMemories: runtime.projectMemories, taskCheckpoints: runtime.taskCheckpoints, skills: runtime.skills, mcp: runtime.mcp };
const oldUpdates = store.listeners('update');
@@ -49,6 +52,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
Object.setPrototypeOf(provider.hub, ModelHub.prototype);
if (provider.hub.importer) Object.setPrototypeOf(provider.hub.importer, ConfigImporter.prototype);
if (provider.hub.credentialVault) Object.setPrototypeOf(provider.hub.credentialVault, CredentialVault.prototype);
if (provider.hub.networkChecks) Object.setPrototypeOf(provider.hub.networkChecks, NetworkDiagnostics.prototype);
}
runtime.filePreviews = null; runtime.appDirectory = root; runtime.previews = null; runtime.browsing = null; runtime.evaluations = null; runtime.environments = null; runtime.workers = null; runtime.controlledEngines = null; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null; runtime.projectMemories = null; runtime.taskCheckpoints = null; runtime.skills = null; runtime.mcp = null;
delete server.workbenchCompanion;
@@ -93,6 +97,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
if (oldModelPrototypes.hub) Object.setPrototypeOf(provider.hub, oldModelPrototypes.hub);
if (oldModelPrototypes.importer) Object.setPrototypeOf(provider.hub.importer, oldModelPrototypes.importer);
if (oldModelPrototypes.vault) Object.setPrototypeOf(provider.hub.credentialVault, oldModelPrototypes.vault);
if (oldModelPrototypes.network) Object.setPrototypeOf(provider.hub.networkChecks, oldModelPrototypes.network);
store.removeAllListeners('update'); for (const observer of oldUpdates) store.on('update', observer);
server.removeAllListeners('request'); for (const previous of oldHandlers) server.on('request', previous);
throw error;
+2 -1
View File
@@ -130,12 +130,13 @@ export class Provider {
}
async abortRequests() {
this.requestsClosing = true;
await this.hub?.networkChecks?.stopAll();
const operations = [...(this.requestControllers ?? [])];
for (const operation of operations) operation.controller.abort(new Error('用户停止执行宿主。'));
await Promise.all(operations.map(operation => operation.done));
const transport=this.transport;this.transport=null;await transport?.close();
}
resumeRequests() { this.requestsClosing = false; }
resumeRequests() { this.requestsClosing = false; if (this.hub?.networkChecks) this.hub.networkChecks.closing = false; }
modelHub(store) { return this.hub ??= new ModelHub(store, this); }
prepareConfig(config, store) { return this.modelHub(store).prepare(config); }
redact(value, key = this.apiKey) {
+2 -1
View File
@@ -133,7 +133,7 @@ export class Runtime {
this.active = new Map(); this.waiters = new Map();
}
isActive(id) { return !!this.browsing?.isActive(id) || !!this.previews?.isActive(id) || !!this.environments?.isActive(id) || !!this.evaluations?.isActive(id) || this.active.has(id) || !!this.workers?.isActive(id) || !!this.controlledEngines?.isActive(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id) || !!this.workspaces?.isActive(id) || !!this.research?.isActive(id) || !!this.engines?.isActive(id) || !!this.browser?.isActive(id) || !!this.taskPlans?.isActive(id); }
hasActivity() { return (this.browsing?.active.size ?? 0) > 0 || (this.previews?.active.size ?? 0) > 0 || (this.environments?.active.size ?? 0) > 0 || (this.evaluations?.active.size ?? 0) > 0 || (this.provider.activeRequests ?? 0) > 0 || (this.provider.hub?.waiting ?? 0) > 0 || this.active.size > 0 || (this.workers?.active.size ?? 0) > 0 || (this.controlledEngines?.drivers.size ?? 0) > 0 || (this.mcp?.active.size ?? 0) > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0 || (this.research?.active.size ?? 0) > 0 || (this.engines?.active.size ?? 0) > 0 || (this.browser?.active.size ?? 0) > 0 || (this.taskPlans?.active.size ?? 0) > 0; }
hasActivity() { return (this.provider.hub?.networkChecks?.active.size ?? 0) > 0 || (this.browsing?.active.size ?? 0) > 0 || (this.previews?.active.size ?? 0) > 0 || (this.environments?.active.size ?? 0) > 0 || (this.evaluations?.active.size ?? 0) > 0 || (this.provider.activeRequests ?? 0) > 0 || (this.provider.hub?.waiting ?? 0) > 0 || this.active.size > 0 || (this.workers?.active.size ?? 0) > 0 || (this.controlledEngines?.drivers.size ?? 0) > 0 || (this.mcp?.active.size ?? 0) > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0 || (this.research?.active.size ?? 0) > 0 || (this.engines?.active.size ?? 0) > 0 || (this.browser?.active.size ?? 0) > 0 || (this.taskPlans?.active.size ?? 0) > 0; }
evaluationManager() { return this.evaluations ??= new EvaluationManager(this.store, this); }
workerManager() { return this.workers ??= new WorkerManager(this.store, this); }
projectIndexer() { return this.codeIndex ??= new ProjectIndex({ cacheDirectory: path.join(this.store.directory, 'cache', 'project-index') }); }
@@ -231,6 +231,7 @@ export class Runtime {
return this.start(session.id, worker.goal, true, { workerAuthorization: workerAuthority, worker, workerConfig: config });
}
start(id, content, resume = false, { instructionSource = null, workerAuthorization = null, worker = null, workerConfig = null, attachmentIds=[],resumePlan=null } = {}) {
if (this.provider.hub?.networkChecks?.active.size) throw Object.assign(new Error('连接诊断正在执行,请等待结束或在模型中心停止诊断,再开始任务。'), { status: 409 });
const session = this.store.session(id);
assertWorkersResolved(this.store, session.projectId);
const boundWorker = workerForSession(this.store, session);