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
+2
View File
@@ -1,5 +1,7 @@
# Agent Workbench项目执行规范
Q已实现所属连接DNS/TCP/TLS有界诊断,1.24.6准备独立发行。69相关、11宿主、14安装/旧版升级和补强4热升级回归通过,新UI9组/历史五类26组通过并回看截图;正式初始61项目77会话/6167记录/13115事件/outbox基线已保存,原PID36552/Provider和Key保持,原生窗口已关闭。诊断无凭据/HTTP/模型调用,只证明端点直连,不认证代理API路线或模型能力。按docs/QA-NETWORK-DIAGNOSTICS-Q.md完成不可变独立重建、安装、正式升级/全原状态、原生入口、封存后再新有界Node,不重跑旧失败。无子代理、不推送。
P已完成新的jojocode5b4/Chat JSON独立实测:预检1请求/112报告tokens/0工具/strict matched;新Node首请求UND_ERR_CONNECT_TIMEOUT,0工具/修改/检查/交付,1未知预留10141,未重试切池或续跑旧Task。两轮12次无HTTP TLS握手11成功/1固定IPv6超时,仅证明观察波动,不是唯一根因或API稳定性证明。正式仍1.24.5/source676103c4/PID36552/原Provider,未改产品或重打包。原59公开项目75导出/3605工件/207原尝试及原行、预算/高性能池按声明核对保持;当前61项目77会话/6167记录/13115事件/outbox/3610工件,新增均归属P。目标连接3→4→5/凭据1,原缺省身份三字段显式恢复record/[]/空串规范化单列;全局/legacy展示修订61→65,9229关闭。75份/55891232字节证据离线通过,见docs/QA-LIVE-DELIVERY-P.md及回顾。下一先所属连接DNS/TCP/TLS诊断开发和独立验证,再新有界Node;不能为通过强制IPv4/关闭证书/扩大预算。真实Node、React/Python、原版Purge收益仍未验收,1.25和更新性能保持计划。不委派子代理、不重启正式进程、不提取/复制/重存Key,不推送。
O已本地交付:1.24.5/source676103c4/候选20261103133956264,重复goal和计划诊断回声定向修复,105相关/25升级安装、552输入独立重建22/22、三归档/便携、三载荷16K回放、源码25历史UI、12实际安装及16+9安装文件流程通过。正式保留PID36552/Provider,原58项目74会话与全部原行/导出/工件/模型中心在网页/原生回看后再次精确保持,9229关闭。新同预算Node2请求/4838报告tokens/1未知预留11095,第二上游502/Retry-After60,0修改/检查/交付,旧失败不续跑;原74导出/3596工件/205尝试与声明原状态恢复通过,凭据1、连接3→4→5。315份/140408882字节证据离线通过,本轮合计5请求/16227报告tokens/1未知,Purge收益未测试,见docs/QA-LIVE-CONTEXT-O.md及回顾。保持当前用户高性能池jojocode+93d,不恢复过期N池或启用旧09b。原旧Node metadata registry逆算未匹配的限制保持;新恢复不倒推旧结果。正式更新677958ms重复核验单列性能,下一先新预检/Node闭环,再React/Python/Purge,1.25仍计划。
+7
View File
@@ -1,5 +1,12 @@
# Agent Workbench 更新记录
## 1.24.6 · 所属连接网络诊断(发行验收中)
- 模型中心新增“连接诊断”,连接卡可直接进入;显示 DNS、TCP、TLS 耗时、地址族和证书结果。
- 绑定原连接修订,最多约12秒,一次一项;可停止、刷新、重新打开并查看最近30条历史,重启中断不重放。
- 无需模型Key,不发送HTTP或模型请求;代理存在时明确只检查端点直连,不更改模型选线、预算、健康或能力结论。
- 诊断纳入宿主停止和升级活动控制,保留证书校验与现有运输参数,不强制IPv4。真实工程交付和Purge收益保持独立验收。
## 1.24.5 · 真实任务上下文去重(已本地交付)
- 完整任务目标在系统请求视图只保留一次,原合同、追加要求、限制与验收条件仍完整保存。
+24
View File
@@ -0,0 +1,24 @@
# Q:模型连接诊断与交付验收
本阶段接续 P 的连接超时实测,先让连接故障可以按阶段核对,再开展新的真实工程实验。原 P/O 失败与用量不改写,错误配置已由用户确认的历史不重新推断为 Claude 线路故障。
## 本次能力
模型中心提供“连接诊断”和连接卡直接入口。检查绑定连接 ID、原修订、端点和当时安全运输参数;冻结 DNS 地址,分别检查自动选择、固定 IPv4 和 IPv6 的 TCP/TLS,保留阶段耗时、错误码和证书校验结果。一次一项,约 12 秒总上限;显式停止等待所属套接字关闭,刷新和重新打开可查看原检查。历史最多 30 条,重启中的任务记中断,不重放。
不访问模型凭据,不发送 HTTP 或模型请求。检查端点直连路径;环境代理、NO_PROXY 或自定义运输存在时明确说明实际 API 路线尚未核验。CONNECT 本身属于 HTTP,本阶段不绕过此范围承诺。握手通过不改变模型健康、能力、选线、预算或模型尝试账本。不强制 IPv4,不关闭证书校验,不修改操作系统网络设置。
## 已完成验证
- 11 项核心专项和 69 项相关回归通过:DNS 失败/停顿、TCP 拒绝、受信任与未受信任证书、TLS 停顿、取消与关闭、双栈回退、代理范围、修订、历史、中断、API 权限与活动控制。
- 11 项宿主相关、14 项安装/启动/旧版升级通过;补强后的 4 项热升级回归通过,空闲诊断管理器保留、原型更新和失败恢复有断言。
- TypeScript/Vite/移动与服务/桌面构建通过。新界面 9 组桌面/390px 流程通过,已查看实际截图;5 类历史模型界面共 26 组通过。
- 正式初始只读基线为 1.24.5 / PID36552,61 项目、77 会话、6167 记录、13115 事件及 outbox。全部原表行、导出和工件 SHA 已记录,未读取 Key 值。原生窗口回看后关闭,原宿主保持。
首 npm 构建因子进程使用系统 Node16 失败,修正本轮 PATH 后通过;不改用户全局 Node。首 UI patch 上下文拒绝,未部分应用。截图回查发现验收器可能读到上一修订“通过”,已改为等待新修订和活动结束,原结果保持。首次原生未前置窗口的遮挡截图不算正式工作台目视证据。
## 发行状态
1.24.6 进入不可变候选的独立源码重建、归档、便携和实际安装验收。正式升级、升级后全原状态核对、实际入口回看与封存以随后收据为准,未完成项目不提前记通过。
本阶段配置模型请求为 0。新 Node 完整交付、React/Python 及原版 Purge 收益仍按后续独立预算验收。
+15
View File
@@ -0,0 +1,15 @@
# Q 回顾与后续顺序
P 的单次连接超时不能仅凭若干 TLS 成功或一个 IPv6 失败判定唯一根因。Q 将 DNS、TCP、TLS 的可核对结果接到所属连接,保留失败阶段与原修订;API、协议、Key、型号及工程能力继续分别判断。
开发验收已通过核心、相关模型/宿主/升级回归,以及新界面和五类旧界面。回查截图修正了验收器等待旧结果的竞态,避免“测试通过但没有核对当前结果”。正式基线、不可变构建身份、安装与最终全原状态收据需要完整绑定后才交付。
后续按以下顺序执行:
1. 完成 Q 发行、正式原 PID/Provider 升级、原状态复核、网页/原生入口和离线证据核验,本地 Git 收尾。
2. 明确选择已启用连接,先运行所属诊断;代理存在时直连结果只作为范围有限的观察。另建单次有界身份预检,保留请求/返回与用量,不续跑 P/O 旧任务。
3. 新 Node 工程保持原九测试与 16K/2048 配置、最多 8 请求/90000 tokens;检查完整修改、测试、审查和 Git 闭环。失败保留,未知用量不补造,不自动增加预算或切池。
4. Node 通过再分别做 React/Python,最后执行原版 Purge 的独立 AB/BA。原版已加载与是否带来收益分别判定,停止或失败不记作节省。
5. 1.25 的其余能力和完整目录重复核验性能保持计划。先量化更新耗时,不以取消完整性或防篡改校验换取快。
本阶段不发送配置模型请求;不更改用户当前高性能池或重新启用旧连接,不提取、复制、重存 Key,不推送远端。
+10
View File
@@ -1,5 +1,13 @@
# 汇总发现
## Q:所属连接诊断的实现边界
已比较卡片内展开与独立诊断分类两种结构:卡片内嵌会把DNS/多路径/历史挤入每条连接,选择沿用模型中心分类页,连接条目提供直达按钮;主区域展示所选连接的DNS和三种地址族路径,旁边保留近期历史,窄屏顺序折叠。界面不增加全屏仪表盘。核心实现记录有界元数据,获取历史不创建新元数据;停止等待所属socket真正关闭,宿主停止/升级门禁包含活动诊断,重启仅标记中断而不重放。
当前ModelTransport使用undici7.30.1与autoSelectFamily/250ms,连接超时10000ms;配置环境代理时使用EnvHttpProxyAgent。P独立tls.connect默认模式并不经过HTTP代理,不能把它等同实际代理路线。诊断必须绑定所选连接和运输快照,零HTTP/Key,代理配置存在时准确说明实际API代理路线尚未通过此握手核验。
本轮UI保留现有模型中心与中文工作流:连接条目为入口,选中一条展开阶段记录和取消操作,不另建全屏仪表盘。开始→运行→完成/失败/取消→刷新/关闭后重开可回看;结果不修改模型能力或用户默认号池。具体阶段/持久性与宿主活动契约待源码核对。
## P:新的固定连接与验收范围
两轮只读DNS/TLS12次握手,11成功/1固定IPv6超时,证书校验始终启用、0HTTP/0模型;默认地址族选择四次均通过,不能据此认定原超时唯一原因或API稳定。最终核对原59公开项目/75导出/3605工件/207原尝试和声明原行保持,当前61项目77会话/6167记录/13115事件与outbox/3610工件。首最终核对误比legacy展示修订61→65,原驱动/日志和冻结快照保留,按全局configRevision精确声明后只读核对通过。75份/55891232字节P材料封存,manifest c2ea37b5c3e34ae76e0e9283c937eb0d4082aaceedae06ecab355c8c6eb5d0aa;独立离线原字节/身份/预算/用量/恢复/Git基线核验通过。无产品源码变化,正式仍1.24.5;具体下一诊断开发见RETROSPECTIVE-LIVE-DELIVERY-P。
@@ -1076,3 +1084,5 @@ M 首23专项22通过/1失败:真实 JSON/SSE 两轮原工具与缓存用量
M最终实证:1.24.4正式保持原宿主完成本地升级;Messages原生路径https://api.apikey.fan/v1/messages与请求体已真实使用,原message_start.message.model仍是gpt-6.1-sol,请求claude-opus-5-5。221报告tokens、一次无工具/重试/切池的完整SSE并被严格暂停。这排除了本样本由legacy调用/池内切换或客户端默认GPT回填解释;仅补协议不能解决原线路。供应商映射、Key分组和底层权重未知,不添加无依据别名,不宣称Claude已恢复或工程/Purge收益成立。
发布与证据目录契约不同:源码归档只携带构建输入,编译输出应从已验便携载荷取证并和冻结/独立重建逐项SHA绑定。首封存误取sourceRoot的编译路径明确失败;保留原件后修正取证路径,不修改产品或重复真实调用。745份原字节离线核对通过仅证明证据一致,不能将身份拒绝样本记为成功。
Q验收复核:测试必须等待新修订的结果,不能只等待“通过”字样,以免误认旧历史;最终新UI会等待修订2/active=0后封图。实际390px三路径表/历史可操作,无页面溢出;正式基线61项目77会话不新增模型尝试。原生首次未激活截图显示遮挡内容,只用于定位,不封存为正式工作台画面;前置后实际窗口已核对。
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "local-agent-workbench",
"version": "1.24.5",
"version": "1.24.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "local-agent-workbench",
"version": "1.24.5",
"version": "1.24.6",
"dependencies": {
"@babel/parser": "7.29.11",
"@peculiar/x509": "3.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "local-agent-workbench",
"version": "1.24.5",
"version": "1.24.6",
"private": true,
"type": "module",
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
+8
View File
@@ -1,5 +1,13 @@
# 统一执行进度
## Q:模型连接诊断开发
69相关回归、11宿主相关和14安装/旧版升级回归全部通过;五类历史UI共26组通过,新UI9组桌面/390px流程已实测并查看原截图。新修订验收器先等原修订通过的竞态已修正,原截图/结果保留;最终需等待新修订和active=0。正式初始只读快照61项目/77会话/6167记录/13115事件及outbox,全部原行、导出与工件SHA已记录。原生1.24.5回看,窗口已关闭,PID36552保持。最后源码审查补充空闲诊断管理器热升级/回滚对象保留断言。准备冻结与独立发行,真实模型调用0。
核心11专项首轮通过:真实本机TCP/TLS/证书、双栈回退、DNS失败/超时/取消、代理范围、历史/中断、API权限/宿主活动/升级停止。UI首多文件patch因预算组件上下文不匹配被原子拒绝,未产生部分新文件,按实际行重新应用。首npm构建被子进程PATH中的系统Node16拦下(显式npm本体是Node24但子命令仍旧Node),原日志保留;修正仅本轮命令PATH,继续构建,不改用户系统Node。
接续P实测/回顾,建立feat/connection-diagnostics-q。开始实现上一轮明确的连接诊断切片,已读取规划及产品UI/UX、frontend-design技能。保持现有产品结构,不委派、不重放真实失败任务;正式宿主和凭据保持,先完成隔离实现与验收再独立发行。
## P:新的连接预检与工程闭环
最终Git索引含清单76份/55904611字节与75份封存原件逐SHA一致,离线核验与diff检查通过。全局*.log导致首次索引漏收,本目录精确例外和原字节属性已补齐,首次日志独立保留。报告、回顾、下一诊断开发切片和规划按本轮范围本地保存;没有产品新发行、远端推送或额外模型调用。
+1
View File
@@ -23,6 +23,7 @@ const prefixes = Object.freeze({
'1.24.2': 'delivery-integrity',
'1.24.3': 'model-selection',
'1.24.5': 'live-context-o',
'1.24.6': 'network-q',
});
export function releaseEvidencePrefix(version) {
const prefix = prefixes[version];
+1 -1
View File
@@ -64,7 +64,7 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo
if (!fs.existsSync(originalScript) || !fs.existsSync(upgradeScript) || !fs.existsSync(path.join(next, 'dist-client', 'index.html'))) throw new Error('Upgrade bundles are incomplete.');
if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error('Invalid target process.');
const before = await readUpgradeJson(origin + '/api/bootstrap', 5000, 'Read original Workbench');
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.20.2', '1.20.3', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.20.2', '1.20.3', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
if (before.sessions.some(session => ['running', 'awaiting_approval', 'stopping'].includes(session.status))) throw new Error('Wait for existing tasks and approvals before upgrading.');
let protocol, socket, enabledHere = false, paused = false;
const breakpoints = [];
+20 -20
View File
@@ -9,36 +9,36 @@ import { randomUUID } from 'node:crypto';
if (process.argv.slice(2).some(value => value !== '--help')) throw new Error('Unsupported argument; use --help.');
if (process.argv.includes('--help')) { console.log('node scripts/verify-all-ui.mjs - run serial desktop/390px checks in independent local hosts; use explicit QA Python/Harness/Purge source paths for 1.15.'); process.exit(0); }
const version = JSON.parse(fs.readFileSync('package.json', 'utf8')).version;
assert.ok(['1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version), 'Review evidence paths when introducing the next release.');
assert.ok(['1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version), 'Review evidence paths when introducing the next release.');
const prefix = releaseEvidencePrefix(version), resultFile = `.qa/${prefix}-all-ui-validation.json`, results = [];
const qaEnvironment = Object.fromEntries(['AGENT_WORKBENCH_TEST_PYTHON', 'AGENT_WORKBENCH_DEEPSEEK_ROOT', 'AGENT_WORKBENCH_PURGE_178_ROOT', 'AGENT_WORKBENCH_PURGE_181_ROOT']
.filter(name => process.env[name]).map(name => [name, process.env[name]]));
for (const [name, value] of Object.entries(qaEnvironment)) assert.ok(path.isAbsolute(value) && fs.existsSync(value), 'Use an existing absolute QA runtime/source path: ' + name);
const cases = [
...(['1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-file-results-ui.mjs', null]] : []),
...(['1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-release-efficiency-ui.mjs', null]] : []),
...(['1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-local-files.mjs', null]] : []),
...(['1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version)?[['verify-embedded-browser.mjs',null]]:[]),
...(['1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version)?[['verify-environment-ui.mjs',null],['verify-model-fidelity-ui.mjs',null],['verify-model-wait-ui.mjs',null],['verify-task-control-ui.mjs',null]]:[]),
...(['1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-evaluations-ui.mjs', null]] : []),
...(['1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-project-cache-ui.mjs', null]] : []),
...(['1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-vision-ui.mjs', null]] : []),
...(['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-model-protocols-ui.mjs', null]] : []),
...(['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-companion-ui.mjs', null]] : []),
...(['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-controlled-ui.mjs', null], ['verify-purge-ui.mjs', null]] : []),
...(['1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-workers-ui.mjs', null]] : []),
...(['1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-task-plans-ui.mjs', `docs/${prefix}-task-ui-validation.json`]] : []),
...(['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-browser-ui.mjs', `docs/${prefix}-browser-ui-validation.json`]] : []),
...(['1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-file-results-ui.mjs', null]] : []),
...(['1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-release-efficiency-ui.mjs', null]] : []),
...(['1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-local-files.mjs', null]] : []),
...(['1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version)?[['verify-embedded-browser.mjs',null]]:[]),
...(['1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version)?[['verify-environment-ui.mjs',null],['verify-model-fidelity-ui.mjs',null],['verify-model-wait-ui.mjs',null],['verify-task-control-ui.mjs',null]]:[]),
...(['1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-evaluations-ui.mjs', null]] : []),
...(['1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-project-cache-ui.mjs', null]] : []),
...(['1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-vision-ui.mjs', null]] : []),
...(['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-model-protocols-ui.mjs', null]] : []),
...(['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-companion-ui.mjs', null]] : []),
...(['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-controlled-ui.mjs', null], ['verify-purge-ui.mjs', null]] : []),
...(['1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-workers-ui.mjs', null]] : []),
...(['1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-task-plans-ui.mjs', `docs/${prefix}-task-ui-validation.json`]] : []),
...(['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-browser-ui.mjs', `docs/${prefix}-browser-ui-validation.json`]] : []),
['verify-ui.mjs', '.qa/ui-validation.json'], ['verify-diagnostics-ui.mjs', '.qa/diagnostics-ui-validation.json'],
['verify-execution-ui.mjs', '.qa/execution-ui-validation.json'], ['verify-delivery-ui.mjs', '.qa/delivery-ui-validation.json'],
['verify-index-ui.mjs', '.qa/index-ui-result.json'], ['verify-change-sets-ui.mjs', `docs/${prefix}-batch-ui-validation.json`],
['verify-context-ui.mjs', `.qa/${version === '1.6.0' ? 'workspaces-context' : prefix}-ui-validation.json`],
['verify-workspaces-ui.mjs', `docs/${prefix === 'workspaces' ? prefix : prefix + '-workspaces'}-ui-validation.json`],
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-python-ui.mjs', `docs/${prefix}-python-ui-validation.json`]] : []),
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-react-delivery.mjs', version === '1.7.0' ? 'docs/react-engine-delivery-validation.json' : `docs/${prefix}-react-delivery-validation.json`]] : []),
...(['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-research-ui.mjs', `docs/${prefix}-research-ui-validation.json`]] : []),
...(['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? [['verify-engines-ui.mjs', version === '1.9.0' ? 'docs/engines-ui-validation.json' : `docs/${prefix}-engines-ui-validation.json`]] : []),
...(['1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version) ? ['model-center', 'project-memory', 'task-checkpoints', 'skills', 'mcp', 'mcp-recovery'].map(name => [`verify-${name}-ui.mjs`, null]) : []),
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-python-ui.mjs', `docs/${prefix}-python-ui-validation.json`]] : []),
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-react-delivery.mjs', version === '1.7.0' ? 'docs/react-engine-delivery-validation.json' : `docs/${prefix}-react-delivery-validation.json`]] : []),
...(['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-research-ui.mjs', `docs/${prefix}-research-ui-validation.json`]] : []),
...(['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? [['verify-engines-ui.mjs', version === '1.9.0' ? 'docs/engines-ui-validation.json' : `docs/${prefix}-engines-ui-validation.json`]] : []),
...(['1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version) ? ['model-center', 'project-memory', 'task-checkpoints', 'skills', 'mcp', 'mcp-recovery'].map(name => [`verify-${name}-ui.mjs`, null]) : []),
];
fs.mkdirSync('.qa', { recursive: true });
const externalHost = new Set(['verify-ui.mjs', 'verify-diagnostics-ui.mjs', 'verify-execution-ui.mjs', 'verify-index-ui.mjs']);
+1 -1
View File
@@ -22,7 +22,7 @@ export async function verifyControlledApi({ api, url, token, directory, appRoot,
const origin = new URL(url);
assert.equal(origin.hostname, '127.0.0.1'); assert.notEqual(origin.port, '4318');
const expectedVersion = JSON.parse(fs.readFileSync(path.join(appRoot, fs.existsSync(path.join(appRoot, 'MANIFEST.json')) ? 'MANIFEST.json' : 'package.json'), 'utf8')).version;
assert.ok(['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.20.2', '1.20.3', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(expectedVersion));
assert.ok(['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.20.2', '1.20.3', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(expectedVersion));
const bootstrap = await api('/bootstrap'); assert.equal(bootstrap.version, expectedVersion);
assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const root = path.join(directory, 'compiled-controlled-node'), hooks = path.join(directory, 'disabled-hooks');
+1 -1
View File
@@ -149,7 +149,7 @@ try {
const beforeRestart = snapshotPersistentData(dataRoot); await controller.stop(); const restarted = (await controller.start()).identity;
assert.notEqual(restarted.pid, original.pid); assert.deepEqual(snapshotPersistentData(dataRoot), beforeRestart);
await controller.api('/model-center/probe', { method: 'POST', input: { id: connectionId } }); assert.equal(authenticated, 3); record(stage, { originalPid: original.pid, restartedPid: restarted.pid, authenticatedRequests: authenticated });
if (['1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(version)) {
if (['1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(version)) {
stage = 'actual installed current results and saved HTML user paths';
const pointer = JSON.parse(fs.readFileSync(path.join(installRoot, 'current.json')));
const installedRoot = fs.realpathSync.native(path.join(installRoot, 'versions', pointer.active.directory)), proofs = [];
+102
View File
@@ -0,0 +1,102 @@
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { chromium, expect } from 'playwright/test';
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
if (process.argv.includes('--help')) { console.log('node scripts/verify-network-diagnostics-ui.mjs [--app-root ABSOLUTE_ROOT] — owned TCP/TLS-only diagnostics, stop/reload/revision/proxy scopes, desktop and 390px. Zero configured-model calls.'); process.exit(0); }
const args = process.argv.slice(2); assert.ok(!args.length || args.length === 2 && args[0] === '--app-root' && path.isAbsolute(args[1]));
const appRoot = args.length ? fs.realpathSync.native(args[1]) : process.cwd();
const targetVersion = JSON.parse(fs.readFileSync(path.join(appRoot, fs.existsSync(path.join(appRoot, 'MANIFEST.json')) ? 'MANIFEST.json' : 'package.json'))).version;
const root = path.resolve('.qa', 'network-q-ui-' + randomUUID()); fs.mkdirSync(root);
const disposers = [], f = fixture({ after: action => disposers.push(action) }), checks = [], screenshots = [], errors = [], traffic = [];
const sockets = new Set(); let plainBytes = 0, tlsOpen = 0;
const listen = async server => { server.on('connection', socket => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); return server.address().port; };
const plain = net.createServer(socket => socket.on('data', chunk => { plainBytes += chunk.length; }));
const stalled = net.createServer(socket => { tlsOpen++; socket.on('data', chunk => { traffic.push({ bytes: chunk.length, tls: chunk[0] === 22 }); }); socket.on('close', () => tlsOpen--); });
const plainPort = await listen(plain), tlsPort = await listen(stalled), refused = net.createServer(), refusedPort = await listen(refused);
await new Promise(resolve => refused.close(resolve));
const provider = new Provider(), hub = provider.modelHub(f.store);
const add = (name, scheme, port) => hub.upsert({ name, model: 'owned-no-model', baseUrl: scheme + '://127.0.0.1:' + port + '/v1', requiresKey: true });
const good = add('本机 TCP · 不需要模型凭据', 'http', plainPort), bad = add('本机拒绝连接 · 失败样例', 'https', refusedPort), waiting = add('本机 TLS 等待 · 可停止样例', 'https', tlsPort);
const initialConfig = structuredClone(f.store.config), initialCenter = hub.view(); f.store.close();
const nodePath = fs.existsSync(path.join(appRoot, 'runtime/node.exe')) ? path.join(appRoot, 'runtime/node.exe') : process.execPath;
const host = await launchWorkbench({ after: action => disposers.push(action) }, f.data,
{ HTTPS_PROXY: 'http://owned-proxy-user:owned-proxy-secret@127.0.0.1:9', NO_PROXY: '127.0.0.1' }, { appRoot, nodePath });
assert.notEqual(new URL(host.url).port, '4318');
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.on('pageerror', error => errors.push(error.message));
let result;
const mark = value => { checks.push(value); console.log('PASS ' + value); };
const capture = async name => { const file = path.join(root, name + '.png'); await page.screenshot({ path: file, fullPage: true }); screenshots.push(file); };
const open = async () => { await page.getByRole('button', { name: '打开模型中心', exact: true }).click(); const dialog = page.getByRole('dialog', { name: '模型中心', exact: true }); await expect(dialog).toBeVisible(); return dialog; };
const tab = dialog => dialog.getByRole('navigation', { name: '模型中心分类' }).getByRole('button', { name: '连接诊断', exact: true });
const panel = () => page.getByRole('region', { name: '模型连接诊断', exact: true });
const start = async () => { await panel().getByRole('button', { name: '开始直连检查', exact: true }).click(); };
try {
await page.goto(host.url); await page.waitForLoadState('networkidle'); let dialog = await open();
const card = dialog.locator('.mc-connection').filter({ hasText: good.name }); await card.getByRole('button', { name: '连接诊断', exact: true }).click();
await expect(panel().getByLabel('诊断连接', { exact: true })).toHaveValue(good.id); await expect(panel()).toContainText('这条连接还没有检查记录');
await expect(panel().getByRole('button', { name: '开始直连检查', exact: true })).toBeEnabled(); await capture('empty-desktop');
mark('connection-card entry binds the exact saved target, works without a Key and shows an honest empty state');
await start(); await expect(panel().getByRole('status')).toContainText('直连握手通过', { timeout: 10000 });
await expect(panel()).toContainText('HTTP 端点无需 TLS'); await expect(panel()).toContainText('DNS 未返回此地址族');
await expect(panel()).toContainText('实际 API 路线尚未核验'); await panel().getByText('查看原诊断范围与运输参数', { exact: true }).click();
await expect(panel()).toContainText('未请求;能力与连接健康结论保持原记录'); await capture('passed-desktop');
mark('real loopback TCP success separates missing IPv6, HTTPS proxy scope and untested model API capability');
let view = await host.api('/model-center/network-diagnostics'); const goodId = view.jobs[0].id;
await page.reload(); dialog = await open(); await tab(dialog).click();
await panel().getByLabel('诊断连接', { exact: true }).selectOption(good.id);
await expect(panel().getByRole('status')).toContainText('直连握手通过');
assert.equal((await host.api('/model-center/network-diagnostics')).jobs[0].id, goodId); mark('refresh restores the original saved result without repeating network work');
await panel().getByLabel('诊断连接', { exact: true }).selectOption(bad.id); await start();
await expect(panel().getByRole('status')).toContainText('未通过', { timeout: 10000 }); await expect(panel()).toContainText('ECONNREFUSED'); await capture('refused-desktop');
mark('connection failure stays attached to the selected endpoint and shows its real TCP error code');
await panel().getByLabel('诊断连接', { exact: true }).selectOption(waiting.id); await start();
await expect(panel()).toContainText('TLS 握手中'); await expect(panel().getByRole('button', { name: '开始直连检查', exact: true })).toBeDisabled();
assert.equal((await host.api('/host/status')).activity.counts.networkDiagnostics, 1);
await panel().getByRole('button', { name: '停止诊断', exact: true }).click(); await expect(panel().getByRole('status')).toContainText('已停止'); await until(() => tlsOpen === 0);
mark('running TLS check disables duplicate start and explicit stop closes owned sockets before reporting stopped');
await start(); await expect(panel()).toContainText('TLS 握手中'); view = await host.api('/model-center/network-diagnostics'); const runningId = view.jobs[0].id;
await dialog.locator('.modal-heading .icon-button').click(); dialog = await open(); await tab(dialog).click();
await expect(panel()).toContainText('正在检查'); await panel().getByRole('button', { name: '查看正在运行的诊断', exact: true }).click();
await panel().getByRole('button', { name: '停止诊断', exact: true }).click(); await expect(panel().getByRole('status')).toContainText('已停止');
assert.equal((await host.api('/model-center/network-diagnostics')).jobs[0].id, runningId); mark('closing and reopening the model center recovers the same active check and retains explicit stop');
await host.api('/model-center/toggle', { id: good.id, enabled: false }); await panel().getByLabel('诊断连接', { exact: true }).selectOption(good.id);
await panel().getByRole('button', { name: '刷新连接诊断', exact: true }).click(); await expect(panel()).toContainText('连接配置已变化');
await start(); await expect(panel().getByRole('alert')).toContainText('连接已变化');
await dialog.getByRole('button', { name: '刷新模型中心', exact: true }).click();
await start();
await expect(panel().locator('.mn-result-heading .mn-revision')).toHaveText('修订 2');
await expect(panel().getByRole('status')).toContainText('直连握手通过');
await until(async () => (await host.api('/model-center/network-diagnostics')).active === 0);
mark('old revisions remain visible, stale starts reject before any socket, and refreshing permits a new bounded check');
await page.setViewportSize({ width: 390, height: 844 }); await capture('passed-390');
await panel().locator('.mn-result-heading').scrollIntoViewIfNeeded(); await capture('passed-result-390');
await panel().locator('.mn-paths').scrollIntoViewIfNeeded(); await capture('passed-paths-390');
await panel().getByRole('complementary', { name: '连接诊断历史' }).scrollIntoViewIfNeeded(); await capture('history-390');
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
assert.ok(await panel().evaluate(element => element.scrollWidth <= element.clientWidth + 1));
const startBox = await panel().getByRole('button', { name: '开始直连检查', exact: true }).boundingBox(); assert.ok(startBox.height >= 44);
await panel().getByLabel('诊断连接', { exact: true }).selectOption(bad.id); await expect(panel()).toContainText('ECONNREFUSED');
await panel().locator('.mn-result-heading').scrollIntoViewIfNeeded(); await capture('refused-390');
mark('390px success and failure states fit without page or panel overflow and retain touch-sized actions');
view = await host.api('/model-center/network-diagnostics'); const center = await host.api('/model-center'), boot = await host.api('/bootstrap');
assert.deepEqual(center.selected, initialCenter.selected); assert.deepEqual(center.pools, initialCenter.pools); assert.deepEqual(boot.config, { ...initialConfig, hasKey: false });
assert.deepEqual(center.attempts, []); assert.ok(center.connections.every(value => Object.values(value.capabilities).every(state => state !== 'verified')));
assert.equal(plainBytes, 0); assert.ok(traffic.length > 0 && traffic.every(value => value.tls)); assert.equal(JSON.stringify(view).includes('owned-proxy-secret'), false);
assert.equal((await page.locator('body').innerText()).includes('owned-proxy-secret'), false); assert.deepEqual(errors, []);
mark('original routing, budgets, model ledger and capability results remain unchanged; no HTTP or credential text is sent');
result = { success: true, appRoot, targetVersion, checks, screenshots, errors, httpRequests: 0, realModelRequests: 0,
plainBytes, tlsFrames: traffic.length, jobs: view.jobs, originalSelectionPreserved: true, originalBudgetsPreserved: true };
} catch (error) { await capture('failure').catch(() => {}); result = { success: false, error: error.stack, checks, screenshots, errors, realModelRequests: 0 }; throw error; }
finally {
fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(result, null, 2)); console.log(JSON.stringify({ success: result.success, root, checks: checks.length }));
await browser.close(); for (const socket of sockets) socket.destroy();
for (const server of [plain, stalled]) await new Promise(resolve => server.close(resolve));
for (const dispose of disposers.reverse()) await dispose();
}
+7 -7
View File
@@ -34,7 +34,7 @@ for (const name of Object.keys(env)) if (name.toLowerCase() === 'path') delete e
const windowsRoot = process.env.SystemRoot || 'C:\\Windows';
env.PATH = [windowsRoot, path.join(windowsRoot, 'System32'), path.join(windowsRoot, 'System32', 'WindowsPowerShell', 'v1.0')].join(path.delimiter);
let externalGit = null;
if (['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(manifest.version)) {
if (['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(manifest.version)) {
// The controlled project requires external Git. Preserve its observed binary
// directory while keeping system Node/npm unavailable to the packaged host.
const binary = fs.realpathSync.native(execFileSync('where.exe', ['git.exe'], { env: gitEnvironment(), encoding: 'utf8', windowsHide: true, timeout: 10000 }).trim().split(/\r?\n/)[0]);
@@ -88,7 +88,7 @@ try {
console.log((await launch()).trim());
assert.equal(JSON.parse(fs.readFileSync(path.join(data, 'service-info.json'), 'utf8')).pid, firstInfo.pid);
const example = bootstrap.projects.find(project => project.id === bootstrap.exampleProjectId);
if (['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(manifest.version)) {
if (['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(manifest.version)) {
assert.equal(path.resolve(example.root).toLowerCase(), path.join(data, 'projects', 'starter-project').toLowerCase());
const compareTemplate = relative => { for (const entry of fs.readdirSync(path.join(appRoot, 'examples/starter-project', relative), { withFileTypes: true })) {
const next = path.join(relative, entry.name); if (entry.isDirectory()) compareTemplate(next);
@@ -114,7 +114,7 @@ try {
const checkLog = await api('/artifacts/' + checked.results[0].logArtifactId + '?session=' + session.id); assert.match(checkLog.content, /tests 4/);
assert.ok(fs.existsSync(path.join(appRoot, 'runtime/node_modules/npm/bin/npm-cli.js')));
const actualRea = [];
if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(manifest.version)) {
if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(manifest.version)) {
const installation = await api('/research/availability'); assert.equal(installation.status, 'available'); assert.equal(installation.version, '6.8.0');
assert.equal(fs.realpathSync.native(installation.packageRoot), fs.realpathSync.native(path.join(appRoot, 'runtime/node_modules/rea-agents')));
assert.equal(fs.realpathSync.native(installation.node.path), fs.realpathSync.native(path.join(appRoot, 'runtime/node.exe')));
@@ -146,7 +146,7 @@ try {
console.log('PASS actual contained REA: ASAR, PE imports and PE resources; zero target execution/model requests');
}
let actualEngine = null;
if (['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(manifest.version) && process.argv.includes('--native-engines')) {
if (['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(manifest.version) && process.argv.includes('--native-engines')) {
const installation = await api('/engines/deepseek/availability'); assert.equal(installation.status, 'available', installation.message);
assert.equal(fs.realpathSync.native(installation.node.path), fs.realpathSync.native(path.join(appRoot, 'runtime/node.exe')));
const engineRoot = path.join(data, 'engine-project'); fs.mkdirSync(engineRoot); fs.writeFileSync(path.join(engineRoot, 'README.md'), '# Owned portable engine connection\n');
@@ -166,8 +166,8 @@ try {
assert.equal((await api('/research')).length, 4);
const page = await fetch(url); assert.equal(page.status, 200);
assert.match(await page.text(), /Agent Workbench/);
const actualBrowser = ['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(manifest.version) ? await verifyBrowserApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
const actualControlled = ['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(manifest.version) ? await verifyControlledApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
const actualBrowser = ['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(manifest.version) ? await verifyBrowserApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
const actualControlled = ['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(manifest.version) ? await verifyControlledApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
console.log((await stop()).trim()); started = false;
await until(async () => { try { await fetch(url + '/api/health'); return false; } catch { return true; } });
for (const file of manifest.files) {
@@ -176,7 +176,7 @@ try {
}
const result = { success: true, date: new Date().toISOString(), appRoot, version: manifest.version, nodeVersion: manifest.nodeVersion,
verifiedFiles: manifest.files.length, url, reusedPid: firstInfo.pid, checks: { jobId, status: checked.status, tests: checked.results[0].tests }, actualRea, actualEngine, actualBrowser, actualControlled, externalGit,
steps: ['manifest hashes', 'bundled Node launch', 'same-service reuse', 'packaged example and static page', ...(['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5'].includes(manifest.version) ? ['starter project copied to owned user data; original template bytes matched'] : []), 'explicit command consent', 'actual bundled Node version', 'actual bundled npm check without system Node/npm', 'check log artifact', ...(actualRea.length ? ['contained REA installation and Node identity', 'actual ASAR/imports/resources', 'original Bundle and target hash binding', 'verified reuse without producer replay'] : []), 'report availability', 'graceful stop', 'every original packaged file remains unchanged'], realModel: false };
steps: ['manifest hashes', 'bundled Node launch', 'same-service reuse', 'packaged example and static page', ...(['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6'].includes(manifest.version) ? ['starter project copied to owned user data; original template bytes matched'] : []), 'explicit command consent', 'actual bundled Node version', 'actual bundled npm check without system Node/npm', 'check log artifact', ...(actualRea.length ? ['contained REA installation and Node identity', 'actual ASAR/imports/resources', 'original Bundle and target hash binding', 'verified reuse without producer replay'] : []), 'report availability', 'graceful stop', 'every original packaged file remains unchanged'], realModel: false };
fs.writeFileSync('.qa/release-validation.json', JSON.stringify(result, null, 2));
console.log(JSON.stringify(result, null, 2));
} finally { if (started) { try { await stop(); } catch {} } }
+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);
+10
View File
@@ -1,5 +1,15 @@
# Agent Workbench:核心代理能力研究与产品计划
## 当前 Q:模型中心的有界连接诊断
接续dca6cbdb,用户要求全量推进并回顾。使用planning-with-files、product-ui-ux和frontend-design,不委派。开发无Key/无HTTP的所属连接DNS/TCP/TLS诊断;保留原请求、真实能力与健康结论。正式1.24.5/PID36552/Provider及原凭据、用户池不重启/改写,实验使用隔离宿主。
1. [complete] 核对运输/模型中心/宿主活动和升级契约;冻结诊断目标、路由说明与UI结构,记录正式当前基线。
2. [complete] 实现连接修订绑定、阶段耗时/地址族/证书结果、有界取消/并发/停止/重启结果;零HTTP/凭据读取,代理检查与直连明确区分。
3. [complete] 模型中心入口、结果/历史及取消流程,桌面与窄屏实际验证;握手通过不写模型能力已验证,不影响默认选线。
4. [complete] 本地DNS/TCP/TLS/证书/取消/并发/生命周期场景和相关模型/升级回归,修复实际失败并回顾;不强制IPv4或关证书。
5. [in_progress] 范围提交后冻结不可变候选,独立源码/归档/便携/安装及正式保留PID/Provider升级;原状态核对、实际入口回看、证据封存/离线核验/本地Git。真实模型与Purge另立后续预算,不重放P失败。
## 当前 P:另一已配置连接的独立真实交付验收
用户已明确继续全量推进并回顾总结。接续9d549a71,不委派子代理;保持正式1.24.5/PID36552/Provider与凭据、当前高性能池和旧09b停用。O的两次Node失败封存不续跑。本轮固定现有启用jojocode/5b4daed9(GPT/Chat JSON、16K/2048、凭据1、连接3),先新单次严格身份预检,再新Node原九测试。预检最多1请求/16000tokens/256输出;Node最多8请求/90000tokens、16K/2048,监督不提供实现,不在失败后补预算或自动切池。
+165
View File
@@ -0,0 +1,165 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import net from 'node:net';
import tls from 'node:tls';
import { fixture, until, workspace } from './helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { ModelTransport } from '../src/core/models/transport.mjs';
import { NetworkDiagnostics } from '../src/core/models/network-diagnostics.mjs';
import { CompanionTLS } from '../src/core/companion/tls-authority.mjs';
import { createRequestHandler } from '../src/server/app.mjs';
import { hostAuthority } from '../src/core/desktop/host-authority.mjs';
import { installUpgrade } from '../src/server/hot-upgrade.mjs';
async function listener(f, server) {
const sockets = new Set(); server.on('connection', socket => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
f.onCleanup(async () => { for (const socket of sockets) socket.destroy(); await new Promise(resolve => server.close(resolve)); });
return server.address().port;
}
function setup(t, options = {}) {
const f = fixture(t), provider = new Provider({ transport: options.transport ?? new ModelTransport({ environment: {} }) });
const hub = provider.modelHub(f.store); hub.networkChecks = new NetworkDiagnostics(hub, options);
f.onCleanup(() => provider.abortRequests());
const add = baseUrl => hub.upsert({ name: 'Owned network check', model: 'owned-no-model', baseUrl, requiresKey: true });
const run = async connection => { const { job } = hub.networkChecks.start({ id: connection.id, revision: connection.revision });
await hub.networkChecks.active.get(job.id).promise; return hub.networkChecks.view().jobs.find(row => row.id === job.id); };
return { ...f, provider, hub, add, run, manager: hub.networkChecks };
}
async function material() {
const state = { gatewayId: 'owned-network-test' }, registry = { binding: 'owned-network-test', read: () => state, mutate: action => action(state) };
return new CompanionTLS(registry, { protect: value => Buffer.from(value), unprotect: value => Buffer.from(value) }).material('127.0.0.1');
}
test('plain endpoint checks only TCP, records family coverage and never reads model credentials or writes routing/health/attempts', async t => {
const f = setup(t); let bytes = 0;
const port = await listener(f, net.createServer(socket => socket.on('data', chunk => { bytes += chunk.length; })));
const connection = f.add('http://127.0.0.1:' + port + '/v1'), state = structuredClone(f.hub.state), config = structuredClone(f.store.config);
f.hub.credential = () => { throw Error('Credential access forbidden.'); };
f.provider.redact = () => { throw Error('Redaction must not enumerate saved keys.'); };
const job = await f.run(connection);
assert.equal(job.status, 'passed'); assert.equal(job.stages.dns.status, 'passed');
assert.equal(job.trials[0].tls, 'not_applicable'); assert.equal(job.trials[2].status, 'skipped');
assert.equal(job.trials[2].code, 'ADDRESS_FAMILY_UNAVAILABLE');
assert.equal(bytes, 0); assert.deepEqual(f.hub.state, state); assert.deepEqual(f.store.config, config);
assert.deepEqual(f.hub.attempts, []); assert.equal(f.hub.health.size, 0); assert.equal(job.credentialAccess, false);
assert.equal(job.httpRequests, 0); assert.equal(job.modelRequests, 0);
});
test('local DNS failure is separate from TCP/TLS and arbitrary input, stale revision and TLS overrides are rejected', async t => {
let lookups = 0;
const f = setup(t, { lookup: (_name, _options, callback) => { lookups++; callback(Object.assign(new Error('owned lookup'), { code: 'ENOTFOUND' })); } });
const connection = f.add('https://owned-dns.invalid/v1');
for (const extra of [{ revision: 99 }, { rejectUnauthorized: false }, { apiKey: 'must-not-read' }, { port: 1 }]) assert.throws(() => f.manager.start({ id: connection.id, revision: connection.revision, ...extra }));
const job = await f.run(connection); assert.equal(lookups, 1); assert.equal(job.status, 'failed');
assert.equal(job.stages.dns.code, 'ENOTFOUND'); assert.ok(job.trials.every(row => row.status === 'skipped'));
assert.equal(job.target.host, 'owned-dns.invalid');
});
test('refused TCP socket preserves its stage and cannot masquerade as a TLS or API response', async t => {
const f = setup(t), server = net.createServer(), port = await listener(f, server);
await new Promise(resolve => server.close(resolve));
const job = await f.run(f.add('https://127.0.0.1:' + port + '/v1'));
assert.equal(job.status, 'failed'); assert.equal(job.trials[0].stage, 'tcp'); assert.equal(job.trials[0].code, 'ECONNREFUSED');
assert.equal(job.trials[0].tlsProtocol, undefined); assert.equal(job.modelRequests, 0);
});
test('TLS validation succeeds for a trusted owned certificate and rejects the same untrusted certificate', async t => {
const cert = await material(), f = setup(t, { ca: cert.ca });
const server = tls.createServer(cert); server.on('tlsClientError', () => {});
const port = await listener(f, server), connection = f.add('https://127.0.0.1:' + port + '/v1');
const good = await f.run(connection); assert.equal(good.status, 'passed'); assert.equal(good.trials[0].certificateAuthorized, true);
assert.ok(good.trials[0].certificateFingerprint256); assert.ok(good.trials[0].tlsMs >= 0);
delete f.manager.options.ca;
const bad = await f.run(connection); assert.equal(bad.status, 'failed'); assert.equal(bad.trials[0].stage, 'tls');
assert.ok(['SELF_SIGNED_CERT_IN_CHAIN', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'].includes(bad.trials[0].code), bad.trials[0].code);
assert.notEqual(bad.trials[0].certificateAuthorized, true);
});
test('a TCP peer that never answers TLS is bounded, and cancellation waits for owned sockets to close', async t => {
let open = 0; const f = setup(t, { stageTimeoutMs: 80 });
const server = net.createServer(socket => { open++; socket.on('data', () => {}); socket.on('close', () => open--); });
const port = await listener(f, server), connection = f.add('https://127.0.0.1:' + port + '/v1');
const timed = await f.run(connection); assert.equal(timed.trials[0].stage, 'tls'); assert.equal(timed.trials[0].code, 'TLS_HANDSHAKE_TIMEOUT');
await until(() => open === 0); f.manager.options.stageTimeoutMs = 10000;
const { job } = f.manager.start({ id: connection.id, revision: connection.revision }); await until(() => open > 0);
assert.throws(() => f.manager.start({ id: connection.id, revision: connection.revision }), /等待/);
const stopped = await f.manager.stop(job.id, {}); assert.equal(stopped.job.status, 'cancelled'); assert.equal(f.manager.active.size, 0);
await until(() => open === 0); const repeated = await f.manager.stop(job.id, {}); assert.deepEqual(repeated, stopped);
});
test('a stalled lookup is cancellable and the overall deadline bounds DNS without late socket work', async t => {
let callback; const f = setup(t, { budgetMs: 65, lookup: (_name, _options, done) => { callback = done; } });
const connection = f.add('https://owned-stalled.invalid/v1'), job = await f.run(connection);
assert.equal(job.status, 'failed'); assert.equal(job.code, 'DIAGNOSTIC_DEADLINE'); assert.equal(job.stages.dns.status, 'cancelled');
const frozen = JSON.stringify(f.manager.view()); callback(null, [{ address: '127.0.0.1', family: 4 }]);
await new Promise(resolve => setImmediate(resolve)); assert.equal(JSON.stringify(f.manager.view()), frozen); assert.equal(f.manager.active.size, 0);
});
test('dual-stack fallback and explicit family results remain separate and never change global DNS defaults', async t => {
const lookup = (_name, options, callback) => callback(null, [{ address: '::1', family: 6 }, { address: '127.0.0.1', family: 4 }]);
const f = setup(t, { transport: new ModelTransport({ environment: {}, lookup }) });
const port = await listener(f, net.createServer()), previous = net.getDefaultAutoSelectFamily();
const job = await f.run(f.add('http://owned-dual.invalid:' + port + '/v1'));
assert.equal(job.status, 'partial'); assert.equal(job.trials[0].status, 'passed'); assert.equal(job.trials[0].family, 'IPv4');
assert.equal(job.trials[2].status, 'failed'); assert.equal(job.trials[2].code, 'ECONNREFUSED');
assert.equal(net.getDefaultAutoSelectFamily(), previous); assert.equal(f.hub.attempts.length, 0);
});
test('proxy settings are reported as scope only; diagnostics do not contact the proxy or leak its credentials', async t => {
let contacts = 0; const f = setup(t), proxy = net.createServer(() => { contacts++; }), proxyPort = await listener(f, proxy);
f.provider.transport = new ModelTransport({ environment: { HTTPS_PROXY: 'http://owned-user:owned-secret@127.0.0.1:' + proxyPort, NO_PROXY: '127.0.0.1' } });
const port = await listener(f, net.createServer()), job = await f.run(f.add('http://127.0.0.1:' + port + '/v1'));
assert.equal(job.route.proxyConfigured, true); assert.equal(job.route.noProxyConfigured, true); assert.equal(job.route.kind, 'direct-endpoint-only');
assert.equal(job.route.modelApiRouteVerified, false); assert.equal(contacts, 0); assert.equal(JSON.stringify(job).includes('owned-secret'), false);
});
test('history is bounded, survives reopening, marks interrupted work and reports changed revisions without rewriting frozen targets', async t => {
const f = setup(t), connection = f.add('http://127.0.0.1:9/v1');
assert.equal(f.store.storage.meta('modelNetworkDiagnostics', null), null, 'Reading an empty history does not create metadata.');
const job = await f.run(connection); f.hub.toggle(connection.id, false);
assert.equal(f.manager.view().jobs[0].stale, true); assert.equal(job.connectionRevision, connection.revision);
const rows = f.store.storage.meta('modelNetworkDiagnostics', []); rows[0].status = 'running'; rows[0].stages.dns.status = 'running';
f.store.storage.setMeta('modelNetworkDiagnostics', rows); const reopened = new NetworkDiagnostics(f.hub);
assert.equal(reopened.view().jobs[0].status, 'interrupted'); assert.equal(reopened.active.size, 0);
assert.equal(reopened.view().jobs[0].stages.dns.status, 'interrupted');
reopened.jobs = Array.from({ length: 30 }, (_, index) => ({ ...job, id: 'retained-' + index })); f.hub.networkChecks = reopened;
const next = f.hub.connection(connection.id); const result = reopened.start({ id: next.id, revision: next.revision });
await reopened.active.get(result.job.id).promise; assert.equal(reopened.view().jobs.length, 30); assert.equal(reopened.view().jobs.at(-1).id, 'retained-1');
});
test('HTTP API, host activity, configuration edits, model start and upgrade honor the same active diagnostic and stop operation', async t => {
const f = setup(t), port = await listener(f, net.createServer(socket => socket.on('data', () => {})));
const connection = f.add('https://127.0.0.1:' + port + '/v1'), runtime = new Runtime(f.store, f.provider), server = http.createServer();
await listener(f, server); const token = 'owned-network-token';
const context = { appDirectory: workspace, server, store: f.store, provider: f.provider, runtime, token, clients: new Set(), started: Date.now(),
getPort: () => server.address().port, exampleProject: f.project, shutdown: () => {} };
server.on('request', createRequestHandler(context));
const api = async (route, input, auth = token) => { const response = await fetch('http://127.0.0.1:' + server.address().port + '/api' + route,
{ method: input === undefined ? 'GET' : 'POST', headers: { 'X-Workbench-Token': auth, 'Content-Type': 'application/json', Connection: 'close' },
...(input === undefined ? {} : { body: JSON.stringify(input) }) }); return { status: response.status, value: await response.json() }; };
assert.equal((await api('/model-center/network-diagnostics', undefined, '')).status, 403);
const started = await api('/model-center/network-diagnostics', { id: connection.id, revision: connection.revision }); assert.equal(started.status, 201);
assert.equal(runtime.hasActivity(), true); assert.equal(hostAuthority(context).activity().counts.networkDiagnostics, 1);
assert.equal((await api('/model-center/connections', { name: 'blocked' })).status, 409);
assert.equal((await api('/sessions/' + f.session.id + '/messages', { content: 'Do not start.' })).status, 409);
assert.throws(() => installUpgrade(context, { appDirectory: workspace, updateServiceInfo: false }), /connection diagnostics/);
const stopped = await api('/model-center/network-diagnostics/' + started.value.job.id + '/stop', {}); assert.equal(stopped.value.job.status, 'cancelled');
assert.equal(runtime.hasActivity(), false); assert.equal(hostAuthority(context).activity().active, false);
const network = f.hub.networkChecks, before = JSON.stringify(network.jobs);
installUpgrade(context, { appDirectory: workspace, updateServiceInfo: false }); assert.equal(f.hub.networkChecks, network); assert.equal(JSON.stringify(network.jobs), before);
assert.equal((await api('/model-center/network-diagnostics')).value.jobs[0].id, started.value.job.id);
});
test('provider shutdown cancels diagnostics and permits explicit reuse after a failed host stop', async t => {
const f = setup(t), port = await listener(f, net.createServer(socket => socket.on('data', () => {}))), connection = f.add('https://127.0.0.1:' + port + '/v1');
const { job } = f.manager.start({ id: connection.id, revision: connection.revision });
await until(() => f.manager.jobs[0].trials.some(row => row.stage === 'tls'));
await f.provider.abortRequests(); assert.equal(f.manager.active.size, 0); assert.equal(f.manager.view().jobs[0].status, 'cancelled');
assert.equal(f.manager.view().jobs[0].id, job.id); assert.throws(() => f.manager.start({ id: connection.id, revision: connection.revision }), /停止/);
f.provider.resumeRequests(); const next = f.manager.start({ id: connection.id, revision: connection.revision });
await f.manager.stop(next.job.id, {}); assert.equal(f.manager.view().jobs[0].status, 'cancelled');
});
+8
View File
@@ -8,6 +8,7 @@ import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { ModelHub } from '../src/core/models/model-hub.mjs';
import { ConfigImporter } from '../src/core/models/config-import.mjs';
import { NetworkDiagnostics } from '../src/core/models/network-diagnostics.mjs';
import { installUpgrade } from '../src/server/hot-upgrade.mjs';
async function setup(t) {
@@ -51,6 +52,8 @@ test('failed adoption restores the original virtual data-root name and original
test('hot upgrade refreshes retained model and importer methods while preserving credential and routing objects', async t => {
const f = await setup(t), credentials = f.provider.credentials, state = f.hub.state;
const network = f.hub.networkDiagnostics(), networkView = network.view(), oldNetwork = Object.create(NetworkDiagnostics.prototype);
Object.setPrototypeOf(network, oldNetwork);
const oldHub = Object.create(ModelHub.prototype), oldImporter = Object.create(ConfigImporter.prototype);
Object.setPrototypeOf(f.hub, oldHub); Object.setPrototypeOf(f.hub.importer, oldImporter);
f.hub.importer.previews.set('owned-preview', { created: Date.now() });
@@ -61,12 +64,16 @@ test('hot upgrade refreshes retained model and importer methods while preserving
assert.equal(f.hub.importer, importer); assert.equal(f.hub.importer.previews.has('owned-preview'), true);
assert.equal(Object.getPrototypeOf(f.hub), ModelHub.prototype);
assert.equal(Object.getPrototypeOf(f.hub.importer), ConfigImporter.prototype);
assert.equal(f.hub.networkChecks, network); assert.equal(Object.getPrototypeOf(network), NetworkDiagnostics.prototype);
assert.deepEqual(network.view(), networkView);
const response = await fetch('http://127.0.0.1:' + f.server.address().port + '/api/health');
assert.equal((await response.json()).ready, true);
});
test('hot upgrade refuses active probes and restores retained model methods if installation fails', async t => {
const f = await setup(t), handler = f.server.listeners('request')[0];
const network = f.hub.networkDiagnostics(), oldNetwork = Object.create(NetworkDiagnostics.prototype);
Object.setPrototypeOf(network, oldNetwork);
for (const [set, clear] of [
[() => { f.provider.activeRequests = 1; }, () => { f.provider.activeRequests = 0; }],
[() => { f.hub.waiting = 1; }, () => { f.hub.waiting = 0; }],
@@ -81,5 +88,6 @@ test('hot upgrade refuses active probes and restores retained model methods if i
assert.throws(() => installUpgrade(f.context, { appDirectory: workspace, updateServiceInfo: false }), /fixture installation failure/);
assert.equal(f.server.listeners('request')[0], handler);
assert.equal(Object.getPrototypeOf(f.hub), oldHub); assert.equal(Object.getPrototypeOf(f.hub.importer), oldImporter);
assert.equal(f.hub.networkChecks, network); assert.equal(Object.getPrototypeOf(network), oldNetwork);
assert.equal(f.provider.apiKey, 'owned-upgrade-fixture');
});