diff --git a/CHANGELOG.md b/CHANGELOG.md index 10cb3fc1..de5b50d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Agent Workbench 更新记录 +## 1.23.0(发行验收中) + +- 运行包保留离线帮助、原研究报告及必要运行时,完整历史证据按原路径/SHA独立分发;源码仍完整。 +- 安装器、网页与桌面可核对所属更新阶段、真实文件/字节、原失败及收据,支持最近操作回看。 +- 浏览器、MCP、依赖和检查审批显示对应类别,手机保留原绑定;失联安装结果显示待核对。 +- 保留发布前完整校验、原宿主连接、原数据和回退门槛;实际发行见docs/QA-1.23.md。 + ## 1.22.1 · 项目选择与 HTML 文件预览 - 网页端打开项目可浏览本机文件夹、常用位置和盘符,保留完整路径输入;选择/取消、加载和错误均有明确反馈。 diff --git a/docs/PLAN-1.23.md b/docs/PLAN-1.23.md index 3c17eb42..4b4d8e2d 100644 --- a/docs/PLAN-1.23.md +++ b/docs/PLAN-1.23.md @@ -2,7 +2,7 @@ 1.22冻结载荷`20261101225201840`的只读清单盘点:20,961文件、1,968,516,148字节,其中docs为10,174文件、1,320,028,962字节。清单SHA-256为`02737d1e0fac80334f0ff28a42868066b9ac5b339ca3a3fc443cecc915a36265`。这是同载荷独立源码、便携与实际安装通过后的候选体积,盘点时正式推广仍在进行;最终状态另见1.22发行身份。下一阶段先建立必需运行/帮助清单及引用闭包,将完整历史证据按来源和SHA单独分发;当前未实施拆分,也不能把文件体积直接换算成时间收益。 -本文件记录下一阶段,尚未实现。[1.22 内置浏览器验收](QA-1.22.md)、正式升级及回顾现已完成;本阶段在该固定来源和原测量基础上开始实施,每个切片独立验证、回顾和本地Git提交。 +本阶段已经启动;下方原调研文字保留当时含义,实际实现/验收进度见文末。[1.22 内置浏览器验收](QA-1.22.md)、正式升级及回顾现已完成;本阶段在该固定来源和原测量基础上开始实施,每个切片独立验证、回顾和本地Git提交。 实际问题是安装、启动与激活核对越来越慢,用户难以判断等待是否正常。1.21 不可变载荷为 19,965 文件、1,844,462,298 字节,其中 docs 为 9,178 文件、1,196,144,080 字节;stage 1095.822 秒、activate 751.765 秒。这些是历史原始测量,不能直接归因为某个目录,也不能先承诺优化比例。 @@ -43,3 +43,11 @@ 拆分前建立明确的运行必需文件及帮助链接闭包,特别保留4份直接研究报告、初始示例、REA/浏览器/桌面运行时、第三方许可证与使用说明。将历史原件另存不可变归档并记录原路径映射/SHA/来源;源码交付仍包含完整来源与验收工具。先实测相同输入下的收益,再决定是否复用校验;任何复用必须证明候选替换、并发写入、链接及原指针变化仍会拒绝。 1.22 的两次候选拒绝说明验收工具也要保留来源:桌面preload入口按版本严格核对;异步工程准备应等待真实操作结束并立即断言终态;生成器应同时检查语法和原收据读写归属。后续继续沿用这些修复,保留原失败,不通过扩大测试期限或沿用局部成功来重新判定失败轮。此处未实施1.23,也未修改冻结中的1.22运行代码。 + +## 本轮 A–D 实施及门槛(接续397099b) + +同一原1.22.1载荷的一次validateInstalledVersion实测176075.2562ms,20962文件/1968554008字节,manifest为be8bf7d15907d9fea79b64ab1bbdc3f2cf29221105f660f934e800393fe5a6c6。这是单次完整核对,不是总安装/激活时间;不能和历史722.096秒直接算收益。原测量位于.qa/release-efficiency-baseline.json。 + +B已实现运行帮助/四份研究报告与独立完整证据分发,完整源码仍保留全部docs;原件清单绑定冻结commit/原路径/字节/SHA。C已实现所属操作ID、候选原清单、阶段/文件/字节及终态,Inno从原进程stdout读取,桌面/网页从原进度文件读取。未知进程结果明确待核对,不自动续跑;准备取消不发布版本。审批标题与拒绝反馈按原工具类别派生,手机只增加类别,原审批指纹保持。 + +D审查后保留发布前所有完整复验。当前没有可证明覆盖并发写入的完整性缓存,不引入跳过校验的复用。分发减少后再实测,不能先承诺收益。E尚待最终冻结来源、独立源码/归档/真实安装/用户基础流程及保留状态部署,开发轮通过不替代这些门槛。 diff --git a/docs/QA-1.23.md b/docs/QA-1.23.md new file mode 100644 index 00000000..d5ff6360 --- /dev/null +++ b/docs/QA-1.23.md @@ -0,0 +1,13 @@ +# 1.23 发行效率与更新进度验收 + +开发及发行验收进行中,正式仍为1.22.1;最终状态以本文件后续实际收据为准。接续397099b,分支feat/release-efficiency-1.23。原用户工程、原宿主/Provider、历史失败保持;研发仅使用独立数据和自有HTTP夹具,真实配置模型请求0。 + +本次实现运行帮助与完整历史证据分发拆分、所属安装操作/阶段/真实文件字节计数、原始失败和收据、安装器日志回调及网页/桌面状态入口。审批标题/范围/拒绝文案按原工具类别派生;手机只增加类别,原绑定和审批参数保持。 + +原1.22.1载荷20962文件、1968554008字节,原manifest为be8bf7d15907d9fea79b64ab1bbdc3f2cf29221105f660f934e800393fe5a6c6。单次原validateInstalledVersion实测176075.2562ms;这是全文件字节、目录范围和窄宿主身份核对总和,不与历史722.096秒激活流程直接计算收益。 + +开发轮22/22新契约与既有安装测试通过。原npm路径错误、Inno GetTickCount不兼容、未同步服务版本号和UI夹具/移动时序失败均原样保留;修复后固定Node24构建及固定Inno6.3.1实际编译通过。首轮状态UI7组通过,截图回看又修正小字节显示和390px截图过早,并增加最近操作切换,正在重验最终开发输入。 + +最终冻结来源、独立源码完整测试、三份ZIP、同载荷安装升级卸载、用户目录/HTML基础流程及保留状态正式部署仍需分别验收。开发结果不计作这些阶段完成。 + +最终开发输入:相关51/51通过(含浏览、手机投影和新安装进度契约)、独占原宿主升级2/2通过、更新状态Edge/Electron7组通过。实际安装开发轮五组后因升级白名单缺项拒绝,原轮失败保留;冻结后对完整候选重跑安装全流程。宽屏/390px截图已回看,字节单位和历史操作选择已补齐;这些仍不是正式部署结论。 diff --git a/docs/RELEASE-EFFICIENCY.md b/docs/RELEASE-EFFICIENCY.md new file mode 100644 index 00000000..d7babcde --- /dev/null +++ b/docs/RELEASE-EFFICIENCY.md @@ -0,0 +1,13 @@ +# 版本、安装进度与证据包 + +从工作台左下角版本号打开「版本与更新」,查看正在运行的版本、已登记版本及最近五次安装操作。网页与桌面共用原安装记录;源码/便携目录会明确显示其运行方式。 + +每次操作有独立编号和递增序号。核对原版本、新候选、会话与工件、保持宿主、发布及回退分别记录;文件数、字节数和进度条只表示当前核对范围。安装器写入文件使用其本身的复制进度;写入结束后还需要实际激活,不能根据窗口关闭或文件已出现判断更新完成。 + +准备预检通过后,取消安装只结束本次准备。核对、发布与回退时须保持安装器打开,该阶段不开放中途取消。原进程丢失时显示「结果待核对」,保留原进度和收据,不自动重新执行原任务。失败时查看原始原因、已登记版本及回退收据;有新操作后仍可切换查看最近失败。 + +安装与便携发行保留运行所需 Node/npm、REA、浏览器和桌面运行时、初始示例、帮助、许可证和四份原研究报告。完整历史验收原件移至配套 `Agent-Workbench-<版本>-evidence-<编号>.zip`;源码包仍含完整来源和历史资料。运行包的 `DOCUMENTATION.json` 和 `docs/EVIDENCE-CATALOG.md` 提供来源 commit、原路径、字节数、SHA-256及证据归档身份。 + +请把证据包解压到独立目录,按原 `docs/` 路径查看。不要解压到受完整性核对的程序目录。四份研究报告保持原字节,其中历史链接可通过目录映射查找原件;原本不在源码中的旧链接明确登记为历史缺失,不补造文件。缺少证据包不会影响正常运行。 + +本次没有降低发行完整性门槛:所有运行载荷仍逐文件核对,发布前再次检查原指针、原启动器、原数据和候选文件;没有引入跳过全量核对的缓存。实际效果见 [1.23 验收](QA-1.23.md)。 diff --git a/docs/RETROSPECTIVE-1.23.md b/docs/RETROSPECTIVE-1.23.md new file mode 100644 index 00000000..01cd9079 --- /dev/null +++ b/docs/RETROSPECTIVE-1.23.md @@ -0,0 +1,11 @@ +# 1.23 回顾 + +本轮围绕安装长时间无反馈和运行分发膨胀,先固定原清单和测量,再拆分分发、接原进程计数,并以失败和并发边界审查实现。完整历史原件仍独立分发,源码保持完整;四份报告不改写原字节,帮助派生链接有SHA映射。 + +审查发现两处产品问题并修正:浏览器/MCP操作复用了终端审批标题,手机确认也写成原命令;更新进度的最终写入故障可能把已发布结果误标失败。现在审批依据实际字段派生类别,远程不增加原工具输入;发布结果以原激活收据为准,进度写入异常明确返回警告,不伪造回退。 + +完整性校验的多次调用保护不同时间边界。本轮没有证据证明缓存可防止并发变化,因此保留完整校验,以减少运行分发改善耗时。176秒是单次原载荷核对;历史722秒是完整激活,不能混作同一测量。新载荷的实际数字和流程耗时待最终发行收据补充。 + +开发验收也暴露工具问题:npm入口路径错误、Inno6.3.1不支持GetTickCount、服务版本未随package同步、移动侧栏切换时序及截图过早。每次失败保留来源,针对原因修正,不扩大期限或把前一轮局部成功写成最终整轮通过。 + +后续回顾继续以用户最基本的打开项目、浏览文件、查看已保存HTML和错误恢复为必验路径;复杂代理测试通过不代替这些实际操作。真实模型自主工程、Purge收益、新iPhone浏览观察和其它供应商多模态接入继续单列,不能用发行优化替代能力交付。 diff --git a/findings.md b/findings.md index a35e2809..3df3dadd 100644 --- a/findings.md +++ b/findings.md @@ -844,3 +844,11 @@ B独立管线已运行,受门控的推广等待独立源码/便携/同载荷 # 当前现场:两条基本操作缺口 正式服务实际 1.22.0,URL 的旧 release 参数不代表实际版本。网页的选择文件夹按钮被 desktop 条件隐藏;选中 pelican-bicycle.html 后只有源码且无预览入口。文件包含内联 SVG/JS 动画;现有任务浏览能力要求 Vite/桌面,不适用于直接打开普通 HTML。本次用已认证的本机一层目录浏览补网页选择;HTML 以独立 loopback 源、受限静态资源和 sandbox 渲染,不把项目脚本放进工作台 API 同源。 + +## 1.23 开始前回顾 + +1.22.1已在397099b封存,本轮起点干净。1.23原计划已明确A–E:运行/帮助引用闭包、历史证据独立分发、真实更新阶段、谨慎核对复用及独立发行。正式上一轮载荷20962文件/1968554008字节,activate722.096秒;时间收益需本轮相同作用域实测,不由docs体积直接推算。源码交付保持完整,运行拆分不能丢失4份研究报告、初始示例、REA/浏览/桌面运行时、帮助和许可证。完整性检查分布在不同时间边界,不因重复而直接删除。 + +源码初查:package.mjs整树复制docs/research到便携与源码,运行服务只有4份固定报告入口;研究报告缺失目前返回占位文案,验收需改为原字节核对。InstallationManager.current/candidate各做完整清单、实际目录范围及窄宿主身份核对,activate在发布指针前再次验证;这些时点保护变化,保留完整重验。现有CLI只有最终JSON,Inno同步隐藏等待且给通用失败,准备阶段在写操作收据之前,需将真实进度提前覆盖失败预检。读取时Windows通配文件路径被rg拒绝,另一次猜测native-launcher.cs不存在;已改用rg --files清单定位,不影响产品或正式状态。 + +1.23接续审查:上轮build失败是调用了仓库内不存在的npm-cli路径;原失败日志保留,改用Node24发行版旁npm后build通过。审批实际字段为browsingTabId/MCP/环境/页面/检查,已按原字段派生文案;手机投影只增加类别,不透出原浏览输入,原指纹绑定保持。Windows两次猜测runtime路径检索失败已改用rg实际定位src/server/runtime.mjs。 diff --git a/package-lock.json b/package-lock.json index e5769ee3..61a97587 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "local-agent-workbench", - "version": "1.22.1", + "version": "1.23.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "local-agent-workbench", - "version": "1.22.1", + "version": "1.23.0", "dependencies": { "@babel/parser": "7.29.11", "@peculiar/x509": "3.1.0", diff --git a/package.json b/package.json index a4cb7d8e..b6f7165c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "local-agent-workbench", - "version": "1.22.1", + "version": "1.23.0", "private": true, "type": "module", "description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.", diff --git a/progress.md b/progress.md index 5bcc0b95..ff179e56 100644 --- a/progress.md +++ b/progress.md @@ -1243,6 +1243,10 @@ A–C首实现已写入:只读Node/npm/Python/pytest诊断、锁定npm ci、 2026-11-01核对未提交实现和原始验收。环境专项原13/13、UI实际7组通过,迁移补登记后升级2/2通过;真实工程原轮仍失败,不能认定D完成。定位Vite空临时目录误判后修正身份逻辑,保留目录预算和外部链接拒绝,新增空目录与实际代码变化的行为验证。当前串行环境/评测专项运行中,后续重跑原React/Python并完成冻结发行。正式1.20.3/PID36552、Provider与用户项目未修改,真实模型请求0。 # 项目选择 / HTML 预览修复接续 +## 下一阶段启动:1.23 + +用户授权继续1.22之后全量开发与回顾。已核对397099b干净基线,创建feat/release-efficiency-1.23;阅读现有PLAN-1.23、规范和计划,继续文件计划及既有UI工作流。当前从运行/帮助引用闭包、完整性与安装状态契约开始,不重放1.22.1升级或原用户任务。正式服务保持1.22.1,实际PID/数据在部署前重新核对;历史数字不当作本轮验证。 + 实现提交 70ac4c40b5a60b5e8ebb08b05bf29fa59d5ea8c7。新不可变候选 C:/Users/wangy/AppData/Local/Programs/AgentWorkbench/versions/Agent-Workbench-1.22.1-local-patch-20261102005525565:20962文件、1968554008字节、所有复制字节逐项核对;实际安装候选Edge/Electron九组核心流程再次通过。正式升级、激活及最终verify均成功,安装指针revision13,原PID36552/Provider保持。整包激活722.096秒已记入1.23性能计划;这是本地安装补丁,未制作独立下载安装包。第一次升级被已打开的旧桌面窗口保护门槛拒绝、未执行,原收据保留;确认空闲且输入为空后正常关闭旧窗口再升级。成功阶段禁止重放。 正式网页实际pelican-bicycle.html的SVG和暂停/播放按钮验证通过,原SHA256 d7ee72b89cb7a45dc1fdb2d77ca2129d0005193915c61ea5c22069c1e9fe1008保持;用户IAB已停留在1.22.1实际预览并保留交付标签。安装根AgentWorkbench.exe重新打开成功,原生窗口8460560恢复原已完成会话和空输入;点击现有pelican-cycle.html直接显示SVG页面,真实暂停点击将按钮由「暂停动画」改为「继续骑行」,原文件13412字节及SHA256 28ea36dc77ddcda3a48138b93f98942dbab2dafa9c403a67ac70bcb5d7cdceff保持。原生首次AX点击缺少坐标几何,回看截图并仅提升工作台窗口后使用已观察坐标成功;未操作无关窗口。 @@ -1254,3 +1258,7 @@ A–C首实现已写入:只读Node/npm/Python/pytest诊断、锁定npm ci、 初轮构建修正桌面桥可选对象的 TS 空值收窄后通过。定向 39 项首轮 38 通过;一项失败来自夹具把 junction 指回项目内部并错误期望它被当作越界。改为真实项目外 HTML 来验证边界,保留初轮失败记录,不改 safePath 既有语义。接续实际浏览器脚本/相对模块/样式/图片与桌面流程验收。补丁版本 1.22.1。 已核对 bfd2f21 干净工作树并创建 fix/project-picker-html-preview。现场两项缺陷已复现。使用 product-ui-ux 与 frontend-design,保留既有界面,只补核心操作流程。正式服务、用户 HTML、会话和 Provider 尚未修改。历史完整回归只作为历史证据,不计作本补丁新执行。 + +1.23开发回顾:固定Node24构建通过;新契约+既有安装共22/22通过。原构建路径错误、Inno GetTickCount不兼容及两轮UI夹具/移动时序失败均保留。Inno改用独立临时目录+时间SHA后实际6.3.1编译通过。首个UI轮还发现服务APP_VERSION未同步,已修正为1.23.0,原自有测试宿主经原接口正常关闭;正式4318不动。正在继续真实界面和生命周期验证。 + +1.23最终开发相关51/51、更新状态实际Edge/Electron7组通过。实际安装开发轮在原宿主回退测试发现upgrade-running版本白名单缺少1.23.0,原轮保留失败(前五组不算完整通过),已补受支持版本;接着独占升级验收和冻结完整载荷安装复验。 diff --git a/scripts/build-installer.mjs b/scripts/build-installer.mjs index 112e5196..abd6498d 100644 --- a/scripts/build-installer.mjs +++ b/scripts/build-installer.mjs @@ -25,7 +25,8 @@ export function buildWindowsInstaller({ root, portableRoot, outputRoot, name = n if (qaFixture.fault === 'corrupt-installed-candidate') template = template.replace("if CurStep = ssPostInstall then begin", "if CurStep = ssPostInstall then begin\n { Explicit owned QA fault, never included by the product packaging CLI. }\n if not SaveStringToFile(ExpandConstant('{app}\\versions\\{#VersionDirectory}\\dist-client\\index.html'), 'owned-candidate-corruption', True) then RaiseException('QA fault injection failed');"); } const literal = value => String(value).replaceAll('"', '""'); - const prefix = [['PortableRoot', portableRoot], ['OutputRoot', outputRoot], ['OutputName', outputName], ['Version', manifest.version], ['VersionDirectory', path.basename(portableRoot)]] + const manifestSha256 = createHash('sha256').update(fs.readFileSync(path.join(portableRoot, 'MANIFEST.json'))).digest('hex'); + const prefix = [['PortableRoot', portableRoot], ['OutputRoot', outputRoot], ['OutputName', outputName], ['Version', manifest.version], ['VersionDirectory', path.basename(portableRoot)], ['ManifestSha256', manifestSha256]] .map(([key, value]) => '#define ' + key + ' "' + literal(value) + '"').join('\n') + '\n'; const source = path.join(directory, 'installer.iss'); fs.writeFileSync(source, '\uFEFF' + prefix + template, 'utf8'); let output; diff --git a/scripts/documentation-bundle.mjs b/scripts/documentation-bundle.mjs new file mode 100644 index 00000000..741b17fc --- /dev/null +++ b/scripts/documentation-bundle.mjs @@ -0,0 +1,75 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { createHash } from 'node:crypto'; + +export const REQUIRED_REPORTS = Object.freeze(['docs/RESEARCH.md', 'docs/research/CURSOR-MECHANISMS.md', 'docs/research/CONTEXT-RECOVERY.md', 'docs/research/TOOL-LOOP.md']); +const hash = bytes => createHash('sha256').update(bytes).digest('hex'); +const simple = value => value.replaceAll('\\', '/'); + +export function createDocumentationBundle({ root, portableRoot, evidenceRoot, archiveName, sourceCommit }) { + if (!/^[a-f0-9]{40}$/.test(sourceCommit) || !/^[A-Za-z0-9._-]+\.zip$/.test(archiveName)) throw new Error('Documentation needs the fixed source commit and separate archive name.'); + if (fs.existsSync(evidenceRoot)) throw new Error('Historical evidence output must be a new directory.'); + const entries = []; + const walk = relative => { + for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true })) { + const next = path.posix.join(relative, entry.name); + if (entry.isSymbolicLink()) throw new Error('Documentation source cannot contain links: ' + next); + if (entry.isDirectory()) walk(next); + else if (entry.isFile()) { + const bytes = fs.readFileSync(path.join(root, next)); + entries.push({ path: next, bytes: bytes.length, sha256: hash(bytes) }); + } else throw new Error('Documentation source must contain regular files: ' + next); + } + }; + walk('docs'); entries.sort((a, b) => a.path.localeCompare(b.path)); + const byPath = new Map(entries.map(row => [row.path, row])); + for (const file of REQUIRED_REPORTS) if (!byPath.has(file)) throw new Error('Required original research report missing: ' + file); + // Text guides and original research remain offline. Large historical raw + // receipts/screenshots are independently shipped with their original paths. + const selected = new Set(entries.filter(row => /^docs\/[^/]+\.md$/.test(row.path) || /^docs\/research\/[^/]+\.(?:md|json)$/.test(row.path)).map(row => row.path)); + const references = [], shipped = []; + fs.mkdirSync(evidenceRoot, { recursive: true }); + for (const row of entries) { + const target = path.join(evidenceRoot, row.path); fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.copyFileSync(path.join(root, row.path), target); + if (hash(fs.readFileSync(target)) !== row.sha256) throw new Error('Original evidence copy differs: ' + row.path); + } + const evidenceManifest = { schema: 1, app: 'agent-workbench-evidence', sourceCommit, scope: 'Original docs tree, including all successful/failed historical evidence. No runtime execution dependency.', files: entries }; + const evidenceBytes = Buffer.from(JSON.stringify(evidenceManifest, null, 2) + '\n'); + fs.writeFileSync(path.join(evidenceRoot, 'MANIFEST.json'), evidenceBytes, { flag: 'wx' }); + const rewrite = (file, original) => original.replace(/\]\(([^)]+)\)/g, (whole, raw) => { + const [target] = raw.split('#'); + if (!target || /^[a-z]+:/i.test(target) || target.startsWith('/')) return whole; + let decoded; + try { decoded = decodeURI(target); } catch { references.push({ from: file, target, disposition: 'malformed-historical-reference' }); return whole; } + const resolved = simple(path.posix.normalize(path.posix.join(path.posix.dirname(file), decoded))); + if (!resolved.startsWith('docs/')) return whole; + const source = byPath.get(resolved); + if (!source) { + references.push({ from: file, target, disposition: 'historical-source-not-in-repository' }); + return whole; + } + if (selected.has(resolved)) return whole; + references.push({ from: file, target: resolved, sha256: source.sha256, disposition: REQUIRED_REPORTS.includes(file) ? 'original-report-reference-in-evidence-archive' : 'evidence-catalog-link' }); + if (REQUIRED_REPORTS.includes(file)) return whole; // Preserve all four original report bytes exactly. + const catalogue = path.posix.relative(path.posix.dirname(file), 'docs/EVIDENCE-CATALOG.md'); + return '](' + catalogue + '#e-' + source.sha256.slice(0, 16) + ')'; + }); + for (const file of [...selected, 'README.md']) { + const original = fs.readFileSync(path.join(root, file)); + const content = Buffer.from(rewrite(file, original.toString('utf8'))); + const destination = path.join(portableRoot, file); fs.mkdirSync(path.dirname(destination), { recursive: true }); + fs.writeFileSync(destination, content); + shipped.push({ path: file, bytes: content.length, sha256: hash(content), sourceSha256: hash(original), originalBytesPreserved: content.equals(original) }); + } + const linked = new Map(references.filter(row => row.sha256).map(row => [row.target, byPath.get(row.target)])); + const catalogue = ['# 历史验收资料', '', '运行包保留离线使用说明和四份原研究报告。完整历史原件另存于配套证据包,包含原路径、SHA-256、成功与失败记录;源码包也保留完整资料。', '', + `配套归档:\`${archiveName}\``, '', `原件清单 SHA-256:\`${hash(evidenceBytes)}\``, '', + '请将证据包解压到单独目录,按其中的原 docs/ 路径查看。不要解压到受完整性核对的程序目录。缺少证据包不影响运行工作台。', '']; + for (const [file, row] of [...linked].sort(([a], [b]) => a.localeCompare(b))) catalogue.push(``, `## ${file}`, '', `原件:\`${file}\` · ${row.bytes} 字节`, '', `SHA-256:\`${row.sha256}\``, ''); + fs.writeFileSync(path.join(portableRoot, 'docs/EVIDENCE-CATALOG.md'), catalogue.join('\n')); + const result = { schema: 1, sourceCommit, archiveName, evidenceManifestSha256: hash(evidenceBytes), originalFiles: entries.length, originalBytes: entries.reduce((sum, row) => sum + row.bytes, 0), + shipped, references, originalReports: REQUIRED_REPORTS.map(file => byPath.get(file)), evidenceEntries: entries }; + fs.writeFileSync(path.join(portableRoot, 'DOCUMENTATION.json'), JSON.stringify(result, null, 2) + '\n'); + return { ...result, evidenceRoot }; +} diff --git a/scripts/package.mjs b/scripts/package.mjs index e342d242..e76eb5c2 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -6,11 +6,13 @@ import { planReaBundle, copyReaBundle } from './bundle-rea.mjs'; import { planBrowserBundle, copyBrowserBundle } from './bundle-browser.mjs'; import { planDesktopBundle, buildNativeLauncher, copyDesktopBundle } from './bundle-desktop.mjs'; import { buildWindowsInstaller } from './build-installer.mjs'; +import { createDocumentationBundle } from './documentation-bundle.mjs'; const args = process.argv.slice(2); if (args.some(value => !['--help', '--immutable'].includes(value))) throw new Error('Unsupported argument; use --help.'); if (args.includes('--help')) { console.log('node scripts/package.mjs [--immutable] - create new portable/source releases and archives; existing release folders are never refreshed.'); process.exit(0); } const root = process.cwd(); +if (execFileSync('git', ['status', '--porcelain', '--untracked-files=all'], { cwd: root, encoding: 'utf8', windowsHide: true }).trim()) throw new Error('Commit the reviewed release inputs before packaging; sourceCommit must identify the actual shipped sources.'); const meta = JSON.parse(fs.readFileSync('package.json', 'utf8')); const lock = JSON.parse(fs.readFileSync('package-lock.json', 'utf8')); const reaPlan = planReaBundle(root); @@ -22,12 +24,13 @@ const baseName = 'Agent-Workbench-' + meta.version; const buildSuffix = args.includes('--immutable') || fs.existsSync(path.join(releases, baseName + '-win-x64')) ? '-' + new Date().toISOString().replace(/[-:TZ.]/g, '') : ''; const portableRoot = path.join(releases, baseName + '-win-x64' + buildSuffix); const sourceRoot = path.join(releases, baseName + '-source' + buildSuffix); +const evidenceRoot = path.join(releases, baseName + '-evidence' + buildSuffix); for (const target of [portableRoot, sourceRoot]) { if (!path.resolve(target).startsWith(releases + path.sep) || fs.existsSync(target)) throw new Error('Release output must be a new folder under releases.'); fs.mkdirSync(target, { recursive: true }); } -const portableFiles = ['dist-client', 'dist-server', 'dist-desktop', 'public', 'docs', 'examples', 'benchmarks', 'research', 'README.md', 'CHANGELOG.md', 'DESIGN.md', 'AGENTS.md', 'Start-Workbench.cmd', 'Stop-Workbench.cmd', 'Start-Desktop.cmd']; +const portableFiles = ['dist-client', 'dist-server', 'dist-desktop', 'public', 'examples', 'benchmarks', 'research', 'CHANGELOG.md', 'DESIGN.md', 'AGENTS.md', 'Start-Workbench.cmd', 'Stop-Workbench.cmd', 'Start-Desktop.cmd']; const sourceFiles = ['src', 'public', 'scripts', 'tests', 'docs', 'examples', 'benchmarks', 'research', 'package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'index.html', 'mobile.html', '.gitignore', '.gitattributes', 'README.md', 'CHANGELOG.md', 'DESIGN.md', 'AGENTS.md', 'task_plan.md', 'findings.md', 'progress.md', 'Start-Workbench.cmd', 'Stop-Workbench.cmd', 'Start-Desktop.cmd']; const copyTree = (source, destination) => fs.cpSync(source, destination, { recursive: true, filter: (from, to) => { if (!fs.statSync(from).isFile() || !fs.existsSync(to)) return true; @@ -37,6 +40,8 @@ for (const name of portableFiles) copyTree(path.join(root, name), path.join(port fs.mkdirSync(path.join(portableRoot, 'scripts'), { recursive: true }); for (const name of ['Start-Workbench.ps1', 'Stop-Workbench.ps1', 'Start-Desktop.ps1', 'upgrade-running.mjs', 'python-check-runner.py']) fs.copyFileSync(path.join(root, 'scripts', name), path.join(portableRoot, 'scripts', name)); for (const name of sourceFiles) copyTree(path.join(root, name), path.join(sourceRoot, name)); +const sourceCommit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', windowsHide: true }).trim(); +const documentation = createDocumentationBundle({ root, portableRoot, evidenceRoot, archiveName: path.basename(evidenceRoot) + '.zip', sourceCommit }); const preferredNode = path.resolve(root, '..', 'tools', 'node-v24.22.1-win-x64', 'node.exe'); const nodeBinary = process.env.AGENT_WORKBENCH_NODE_PATH || (fs.existsSync(preferredNode) ? preferredNode : process.execPath); @@ -131,7 +136,7 @@ function archive(directory) { execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], { windowsHide: true, stdio: 'pipe' }); return { path: destination, bytes: fs.statSync(destination).size, sha256: createHash('sha256').update(fs.readFileSync(destination)).digest('hex') }; } -const result = { portableRoot, sourceRoot, portable: archive(portableRoot), source: archive(sourceRoot), installer, desktopRuntime, nativeLauncher, nodeVersion, reaRuntime, portableFiles: portableManifest.files.length, licenseTexts: licenseCount + 2 }; +const result = { portableRoot, sourceRoot, evidenceRoot, portable: archive(portableRoot), source: archive(sourceRoot), evidence: archive(evidenceRoot), documentation: { sourceCommit, originalFiles: documentation.originalFiles, originalBytes: documentation.originalBytes, shippedFiles: documentation.shipped.length, shippedBytes: documentation.shipped.reduce((sum, row) => sum + row.bytes, 0), evidenceManifestSha256: documentation.evidenceManifestSha256 }, installer, desktopRuntime, nativeLauncher, nodeVersion, reaRuntime, portableFiles: portableManifest.files.length, licenseTexts: licenseCount + 2 }; result.browserRuntime = { playwrightVersion: browserRuntime.playwrightVersion, packages: browserRuntime.packages.map(pkg => ({ name: pkg.name, version: pkg.version, files: pkg.files.length })) }; fs.writeFileSync(path.join(releases, 'latest.json'), JSON.stringify(result, null, 2)); console.log(JSON.stringify(result, null, 2)); diff --git a/scripts/qa-evidence.mjs b/scripts/qa-evidence.mjs index 19c076eb..b15e6a82 100644 --- a/scripts/qa-evidence.mjs +++ b/scripts/qa-evidence.mjs @@ -17,6 +17,7 @@ const prefixes = Object.freeze({ '1.21.0': 'reproducible-env', '1.22.0': 'embedded-browser', '1.22.1': 'local-files', + '1.23.0': 'release-efficiency', }); export function releaseEvidencePrefix(version) { const prefix = prefixes[version]; diff --git a/scripts/upgrade-running.mjs b/scripts/upgrade-running.mjs index 67178471..dd2889cb 100644 --- a/scripts/upgrade-running.mjs +++ b/scripts/upgrade-running.mjs @@ -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'].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'].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 = []; diff --git a/scripts/verify-all-ui.mjs b/scripts/verify-all-ui.mjs index 3fc5321b..2332ea9d 100644 --- a/scripts/verify-all-ui.mjs +++ b/scripts/verify-all-ui.mjs @@ -9,34 +9,35 @@ 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'].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'].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 = [ - ...(version === '1.22.1' ? [['verify-local-files.mjs', null]] : []), - ...(['1.22.0', '1.22.1'].includes(version)?[['verify-embedded-browser.mjs',null]]:[]), - ...(['1.21.0', '1.22.0', '1.22.1'].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'].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'].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'].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'].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'].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'].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'].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'].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'].includes(version) ? [['verify-browser-ui.mjs', `docs/${prefix}-browser-ui-validation.json`]] : []), + ...(version === '1.23.0' ? [['verify-release-efficiency-ui.mjs', null]] : []), + ...(['1.22.1', '1.23.0'].includes(version) ? [['verify-local-files.mjs', null]] : []), + ...(['1.22.0', '1.22.1', '1.23.0'].includes(version)?[['verify-embedded-browser.mjs',null]]:[]), + ...(['1.21.0', '1.22.0', '1.22.1', '1.23.0'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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']); diff --git a/scripts/verify-archives.py b/scripts/verify-archives.py index 8aaf83c1..4d350068 100644 --- a/scripts/verify-archives.py +++ b/scripts/verify-archives.py @@ -40,7 +40,7 @@ def extract_archive(bundle, root): with bundle.open(entry, 'r') as source, open(filesystem_path(target), 'wb') as destination: shutil.copyfileobj(source, destination) -for kind, root_key in [('portable', 'portableRoot'), ('source', 'sourceRoot')]: +for kind, root_key in [('portable', 'portableRoot'), ('source', 'sourceRoot')] + ([('evidence', 'evidenceRoot')] if 'evidenceRoot' in release else []): root = Path(release[root_key]).resolve() archive = Path(release[kind]['path']).resolve() assert root.is_relative_to(release_dir) and archive.is_relative_to(release_dir) @@ -49,7 +49,12 @@ for kind, root_key in [('portable', 'portableRoot'), ('source', 'sourceRoot')]: assert hashlib.sha256(archive_bytes).hexdigest() == release[kind]['sha256'] manifest = json.loads((root / 'MANIFEST.json').read_text(encoding='utf-8')) version = version or manifest['version'] - assert manifest['version'] == version and manifest['kind'] == kind + if kind == 'evidence': + assert manifest['app'] == 'agent-workbench-evidence' + assert manifest['sourceCommit'] == release['documentation']['sourceCommit'] + assert hashlib.sha256((root / 'MANIFEST.json').read_bytes()).hexdigest() == release['documentation']['evidenceManifestSha256'] + else: + assert manifest['version'] == version and manifest['kind'] == kind expected = {entry['path']: entry for entry in manifest['files']} assert len(expected) == len(manifest['files']) with zipfile.ZipFile(archive) as bundle: diff --git a/scripts/verify-controlled-release.mjs b/scripts/verify-controlled-release.mjs index c0c2622e..0f2529a0 100644 --- a/scripts/verify-controlled-release.mjs +++ b/scripts/verify-controlled-release.mjs @@ -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'].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'].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'); diff --git a/scripts/verify-desktop-install.mjs b/scripts/verify-desktop-install.mjs index 17f7bea7..68afdb4c 100644 --- a/scripts/verify-desktop-install.mjs +++ b/scripts/verify-desktop-install.mjs @@ -17,6 +17,7 @@ import { projectEnvironment } from '../src/core/process-environment.mjs'; if (process.argv.includes('--help')) { console.log('node scripts/verify-desktop-install.mjs — isolated actual user-level setup/update/uninstall, full data retention, owned DPAPI/HTTP fixture, active-window and request guards, fault rollback and original PID retention. No configured-model credentials.'); process.exit(0); } assert.equal(process.argv.length, 2); const appRoot = process.cwd(), root = path.resolve('.qa', 'desktop-install-' + randomUUID()), installRoot = path.join(root, 'program'), dataRoot = path.join(root, 'user-data'); +const packagedSource = process.env.AGENT_WORKBENCH_QA_APP_ROOT ? fs.realpathSync.native(process.env.AGENT_WORKBENCH_QA_APP_ROOT) : null; const version = JSON.parse(fs.readFileSync('package.json')).version, results = [], appId = randomUUID(), hash = value => createHash('sha256').update(value).digest('hex'); fs.mkdirSync(root, { recursive: true }); const reserved = net.createServer(); await new Promise(resolve => reserved.listen(0, '127.0.0.1', resolve)); const port = reserved.address().port; await new Promise(resolve => reserved.close(resolve)); @@ -27,11 +28,19 @@ let stage = 'prepare owned full releases', controller, application, ownedModel, const launcher = path.resolve('.qa/native-launcher/AgentWorkbench.exe'); buildNativeLauncher(appRoot, launcher); const desktop = planDesktopBundle(appRoot); function payload(name) { const directory = path.join(root, name); fs.mkdirSync(directory); + if (packagedSource) { + const original = JSON.parse(fs.readFileSync(path.join(packagedSource, 'MANIFEST.json'))); + assert.equal(original.kind, 'portable'); assert.equal(original.version, version); + for (const entry of original.files) { const file = path.join(packagedSource, entry.path); assert.equal(hash(fs.readFileSync(file)), entry.sha256, entry.path); } + fs.cpSync(packagedSource, directory, { recursive: true }); fs.unlinkSync(path.join(directory, 'MANIFEST.json')); + } else { for (const item of ['dist-client', 'dist-server', 'dist-desktop', 'public', 'examples']) fs.cpSync(path.join(appRoot, item), path.join(directory, item), { recursive: true }); fs.mkdirSync(path.join(directory, 'scripts')); fs.copyFileSync('scripts/python-check-runner.py', path.join(directory, 'scripts/python-check-runner.py')); fs.mkdirSync(path.join(directory, 'runtime')); fs.copyFileSync(process.execPath, path.join(directory, 'runtime/node.exe')); fs.cpSync(path.join(path.dirname(process.execPath), 'node_modules/npm'), path.join(directory, 'runtime/node_modules/npm'), { recursive: true }); - copyDesktopBundle(appRoot, directory, desktop, { launcher }); fs.writeFileSync(path.join(directory, 'owned-release.txt'), name + '\n'); + copyDesktopBundle(appRoot, directory, desktop, { launcher }); + } + fs.writeFileSync(path.join(directory, 'owned-release.txt'), name + '\n'); // A valid PE overlay explicitly models a future owned native bootstrap with // different bytes. The updated root entry must follow it and roll back with it. if (name.startsWith('owned-b-')) fs.appendFileSync(path.join(directory, 'AgentWorkbench.exe'), '\nowned-native-bootstrap-update-fixture\n'); @@ -47,6 +56,10 @@ async function setup(installer, label, expected = 0) { catch (error) { code = typeof error.code === 'number' ? error.code : -1; output = String(error.stdout ?? '') + String(error.stderr ?? ''); } fs.writeFileSync(path.join(root, label + '-process.txt'), output); if (expected === 0) assert.equal(code, 0, 'Actual installer failed; inspect ' + log); else assert.notEqual(code, 0, 'Actual installer unexpectedly accepted the rejected condition.'); + const logText = fs.readFileSync(log, 'utf8'); assert.match(logText, /AWBPROGRESS /, 'Actual installer must receive original stage output.'); + const records = fs.readdirSync(path.join(installRoot, '.installation')).filter(name => /^progress-.*\.json$/.test(name)).map(name => JSON.parse(fs.readFileSync(path.join(installRoot, '.installation', name)))).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + assert.equal(records[0].state, expected === 0 ? 'completed' : 'failed'); + if (expected === 0) { assert.ok(records[0].history.some(row => row.stage === 'verify-candidate' && row.scope === 'full-manifest' && row.counts.completedFiles === row.counts.totalFiles)); assert.match(logText, /AWBFILES \d+\/\d+/); } return { code, log, sha256: hash(fs.readFileSync(log)) }; } async function launchElectron() { @@ -135,7 +148,7 @@ try { await run(path.join(installRoot, 'unins000.exe'), ['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/LOG=' + uninstallLog], { windowsHide: true, timeout: 180000, env }); assert.equal(observeWindowsProcess(restarted.pid), null); assert.deepEqual(snapshotPersistentData(dataRoot), uninstallSnapshot); assert.equal(fs.existsSync(path.join(installRoot, 'AgentWorkbench.exe')), false); assert.equal(fs.existsSync(path.join(installRoot, 'current.json')), false); record(stage, { log: uninstallLog, originalDataRoot: dataRoot, data: uninstallSnapshot }); - report = { success: true, version, root, installRoot, dataRoot, port, appId, results, realModelRequests: 0, scope: 'Actual isolated user-level Windows installers and shipped Electron/Node runtimes; own credentials and HTTP fixture only. QA appId, corruption, pointer-fault and crash fixtures explicitly recorded.' }; + report = { success: true, version, root, installRoot, dataRoot, port, appId, packagedSource, results, realModelRequests: 0, scope: 'Actual isolated user-level Windows installers and shipped Electron/Node runtimes; own credentials and HTTP fixture only. QA appId, corruption, pointer-fault and crash fixtures explicitly recorded.' }; } catch (error) { report = { success: false, version, root, installRoot, dataRoot, port, stage, error: error.stack, results, realModelRequests: 0 }; throw error; } finally { releaseRequest?.(); await application?.close().catch(() => {}); diff --git a/scripts/verify-release-efficiency-ui.mjs b/scripts/verify-release-efficiency-ui.mjs new file mode 100644 index 00000000..0cdfdd45 --- /dev/null +++ b/scripts/verify-release-efficiency-ui.mjs @@ -0,0 +1,81 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import net from 'node:net'; +import assert from 'node:assert/strict'; +import { randomUUID, createHash } from 'node:crypto'; +import { chromium, _electron, expect } from 'playwright/test'; +import { HostController } from '../src/core/desktop/host-controller.mjs'; +import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs'; +import { InstallationProgress } from '../src/core/desktop/installation-progress.mjs'; +import { writeState } from '../src/core/desktop/file-state.mjs'; +import { projectEnvironment } from '../src/core/process-environment.mjs'; +import { REQUIRED_REPORTS } from './documentation-bundle.mjs'; + +if (process.argv.includes('--help')) { console.log('node scripts/verify-release-efficiency-ui.mjs — isolated actual Edge/Electron state UI using explicitly owned installation-progress fixtures; real installer acceptance is separate.'); process.exit(0); } +assert.equal(process.argv.length, 2); +const source = path.resolve(process.env.AGENT_WORKBENCH_QA_APP_ROOT || '.'), root = path.resolve('.qa', 'release-efficiency-ui-' + randomUUID()); +const appRoot = path.join(root, '程序 含中文长路径', 'versions', 'owned-ui'), installRoot = path.dirname(path.dirname(appRoot)), dataRoot = path.join(root, 'data'); +const version = JSON.parse(fs.readFileSync(path.join(source, fs.existsSync(path.join(source, 'MANIFEST.json')) ? 'MANIFEST.json' : 'package.json'))).version; +const results = [], screenshots = [], errors = [], hash = bytes => createHash('sha256').update(bytes).digest('hex'); +fs.mkdirSync(appRoot, { recursive: true }); +for (const file of ['dist-client', 'dist-server', 'dist-desktop', 'public', 'examples']) fs.cpSync(path.join(source, file), path.join(appRoot, file), { recursive: true }); +for (const file of REQUIRED_REPORTS) { const target = path.join(appRoot, file); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.copyFileSync(path.join(source, file), target); } +fs.writeFileSync(path.join(appRoot, 'package.json'), JSON.stringify({ version })); +const executable = desktopExecutableIdentity(source).path, packaged = path.basename(executable).toLowerCase() === 'agentworkbench.exe'; +const electronRoot = path.join(appRoot, packaged ? 'desktop' : 'runtime/electron'); +fs.cpSync(path.dirname(executable), electronRoot, { recursive: true }); +const electron = path.join(electronRoot, path.basename(executable)); +const server = net.createServer(); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); const port = server.address().port; await new Promise(resolve => server.close(resolve)); +const stateRoot = path.join(installRoot, '.installation'); fs.mkdirSync(stateRoot, { recursive: true }); +// Explicit UI fixtures only; none of these records claims a real package install. +writeState(path.join(installRoot, 'current.json'), { schema: 1, app: 'agent-workbench-installation', installId: randomUUID(), revision: 1, dataRoot, port, active: { directory: 'owned-ui', version }, previous: null }); +const progress = command => new InstallationProgress({ stateRoot, installRoot, dataRoot, command, expectedManifestSha256: 'a'.repeat(64) }); +const controller = new HostController({ appRoot, dataRoot, port, nodePath: process.execPath }); +let browser, application, page, stage = 'start'; +const record = name => { results.push({ name, passed: true }); console.log('PASS ' + name); }; +const capture = async name => { const file = path.join(root, name + '.png'); await page.screenshot({ path: file }); screenshots.push({ file, sha256: hash(fs.readFileSync(file)) }); }; +const open = async () => { const version = page.getByRole('button', { name: '版本与更新', exact: true }); if (await page.evaluate(() => innerWidth <= 620) || !await version.isVisible()) await page.getByRole('button', { name: '展开项目栏', exact: true }).click(); await expect(version).toBeVisible(); await version.click(); }; +const refresh = async () => { await page.getByRole('button', { name: '刷新状态', exact: true }).click(); }; +const close = async () => { await page.getByRole('dialog').getByRole('button', { name: '关闭窗口', exact: true }).click(); }; +const overflow = async () => assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); +try { + const original = await controller.start(); browser = await chromium.launch({ channel: 'msedge', headless: true }); + page = await browser.newPage({ viewport: { width: 1440, height: 960 } }); page.on('pageerror', error => errors.push(error.message)); + await page.goto(controller.url); await page.locator('.connection.connected').waitFor(); await open(); + await expect(page.getByText('还没有新版安装进度记录。', { exact: false })).toBeVisible(); record('actual authenticated status endpoint: registered version and legacy empty progress'); + stage = 'original reports'; + for (const [kind, file] of [['research', REQUIRED_REPORTS[0]], ['cursor', REQUIRED_REPORTS[1]], ['context', REQUIRED_REPORTS[2]], ['tools', REQUIRED_REPORTS[3]]]) { + // Follow the server's fixed public report names, not a substitute placeholder. + const name = ({ research: 'overview', cursor: 'cursor', context: 'context', tools: 'tools' })[kind]; + const response = await controller.api('/research/' + name); const bytes = fs.readFileSync(path.join(appRoot, file)); + assert.equal(response.content, bytes.toString('utf8')); assert.equal(response.sha256, hash(bytes)); + } + record('four runtime report APIs return original source text and SHA'); + stage = 'running progress'; const running = progress('preflight'); running.phase('verify-current'); + running.count('verify-current', { scope: 'full-manifest', root: appRoot, completedFiles: 17, totalFiles: 100, completedBytes: 2048, totalBytes: 12000, currentPath: 'docs/中文长路径/当前核对的原文件.json' }); running.save(); + await refresh(); await expect(page.getByText('17 / 100 文件', { exact: true })).toBeVisible(); + await expect(page.getByRole('progressbar', { name: '当前核对范围' })).toHaveAttribute('value', '17'); await capture('web-running-wide'); await overflow(); record('actual persisted progress shows current range and real counts with no invented total percentage'); + running.finish('ready-to-copy'); await page.reload(); await open(); await expect(page.getByText('预检已通过,写入进度由安装器显示;新版本尚未激活。')).toBeVisible(); record('reload restores original ready preparation without replaying it'); + stage = 'failure and mobile'; const failed = progress('activate'); failed.finish('failed', { error: { code: 'OWNED_UI_FAILURE', message: '自有验收夹具:新候选原字节已变化,请保留原记录。' }, receiptFile: path.join(stateRoot, 'owned-receipt.json') }); + await refresh(); await expect(page.getByText('OWNED_UI_FAILURE', { exact: true })).toBeVisible(); await capture('web-failure-wide'); + await close(); await page.setViewportSize({ width: 390, height: 844 }); await open(); await expect(page.getByText('OWNED_UI_FAILURE', { exact: true })).toBeVisible(); await overflow(); await capture('web-failure-390'); record('390px Chinese paths, original failure and recovery guidance remain usable'); + stage = 'unknown and offline'; const unknown = progress('activate'), value = JSON.parse(fs.readFileSync(unknown.file)); value.process.createdAt = 'owned-lost-process-fixture'; fs.writeFileSync(unknown.file, JSON.stringify(value)); + await refresh(); await expect(page.getByText('原安装进程已结束,结果待核对', { exact: true })).toBeVisible(); + await page.context().setOffline(true); await expect(page.getByRole('alert').filter({ hasText: '以下保留上次读取结果' })).toBeVisible({ timeout: 10000 }); + await page.context().setOffline(false); await expect(page.getByRole('alert').filter({ hasText: '以下保留上次读取结果' })).toHaveCount(0, { timeout: 10000 }); await capture('web-unknown-390'); record('lost process is unknown; offline retains explicitly stale progress and reconnect refreshes'); + await page.getByRole('combobox', { name: '查看安装操作' }).selectOption(failed.value.id); await expect(page.getByText('OWNED_UI_FAILURE', { exact: true })).toBeVisible(); + await page.getByRole('combobox', { name: '查看安装操作' }).selectOption(''); await expect(page.getByText('原安装进程已结束,结果待核对', { exact: true })).toBeVisible(); + stage = 'actual Electron'; await browser.close(); browser = null; + application = await _electron.launch({ executablePath: electron, args: [...(packaged ? [] : [path.join(appRoot, 'dist-desktop/main.cjs')]), '--app-root', appRoot, '--data-root', dataRoot, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 }); + page = await application.firstWindow(); page.on('pageerror', error => errors.push(error.message)); + const native = await application.browserWindow(page); await native.evaluate(window => { window.showInactive(); window.setContentSize(1440, 960); }); + await page.locator('.connection.connected').waitFor(); await open(); await expect(page.getByText('原安装进程已结束,结果待核对', { exact: true })).toBeVisible(); await capture('electron-unknown-wide'); await overflow(); + await close(); await native.evaluate(window => window.setContentSize(390, 844)); await expect.poll(() => page.evaluate(() => innerWidth)).toBe(390); await open(); await expect(page.getByText('原安装进程已结束,结果待核对', { exact: true })).toBeVisible(); await overflow(); await capture('electron-unknown-390'); + record('actual Electron wide and 390px display original update state; window close retains host'); + await application.close(); application = null; assert.equal((await controller.health()).pid, original.identity.pid); assert.deepEqual(errors, []); stage = 'complete'; + fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify({ passed: true, success: true, version, source, root, stage, results, screenshots, fixtureScope: 'Owned progress fixtures through real authenticated API and actual Edge/Electron; installer process acceptance is separate.', modelRequests: 0 }, null, 2)); + console.log('EVIDENCE ' + root); console.log(JSON.stringify({ passed: true, root, groups: results.length })); +} catch (error) { + if (page) await capture('original-failure').catch(() => {}); + fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify({ passed: false, version, source, root, stage, results, screenshots, error: error.stack }, null, 2)); console.error(JSON.stringify({ passed: false, root, stage, error: error.message })); process.exitCode = 1; +} finally { if (browser) await browser.close().catch(() => {}); if (application) await application.close().catch(() => {}); if (await controller.health()) await controller.stop(); } diff --git a/scripts/verify-release.mjs b/scripts/verify-release.mjs index b49b0110..b91fa828 100644 --- a/scripts/verify-release.mjs +++ b/scripts/verify-release.mjs @@ -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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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'].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 {} } } diff --git a/scripts/verify-source-package.mjs b/scripts/verify-source-package.mjs index 3f913d74..138c7b10 100644 --- a/scripts/verify-source-package.mjs +++ b/scripts/verify-source-package.mjs @@ -19,7 +19,7 @@ assert.ok(fs.existsSync(npmCli), 'Use Node with its bundled npm.'); const files = (root, relative = '') => fs.readdirSync(path.join(root, relative), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)) .flatMap(entry => entry.isDirectory() ? files(root, path.join(relative, entry.name)) : [path.join(relative, entry.name)]); const digest = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex'); -const buildFolders = ['dist-client', 'dist-server', ...(['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'].includes(evidence.version) ? ['dist-desktop'] : [])]; +const buildFolders = ['dist-client', 'dist-server', ...(['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.23.0'].includes(evidence.version) ? ['dist-desktop'] : [])]; const expected = Object.fromEntries(buildFolders.flatMap(folder => files(path.join(workspace, folder)).map(relative => [path.join(folder, relative), digest(path.join(workspace, folder, relative))]))); const allowedEnv = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|homedrive|homepath|home|appdata|localappdata|programfiles(?:\(x86\))?|commonprogramfiles(?:\(x86\))?|lang|lc_all|AGENT_WORKBENCH_TEST_PYTHON|AGENT_WORKBENCH_DEEPSEEK_ROOT|AGENT_WORKBENCH_PURGE_ROOT)$/i; const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => allowedEnv.test(key))); @@ -30,7 +30,7 @@ const directory = path.join(sourceRoot, '.qa', 'package-validation-' + randomUUI fs.mkdirSync(directory, { recursive: true }); const inputFolders = ['src', 'tests', 'scripts', ...['benchmarks', 'public', 'examples', 'research'].filter(folder => fs.existsSync(path.join(sourceRoot, folder)))]; const inputNames = [...inputFolders.flatMap(folder => files(path.join(sourceRoot, folder)).map(relative => path.join(folder, relative))), - 'package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'index.html', ...(['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0'].includes(evidence.version) ? ['mobile.html'] : []), ...['.gitattributes', '.gitignore', 'Start-Desktop.cmd', 'Start-Workbench.cmd', 'Stop-Workbench.cmd'].filter(name => fs.existsSync(path.join(sourceRoot, name)))].sort(); + 'package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'index.html', ...(['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.23.0'].includes(evidence.version) ? ['mobile.html'] : []), ...['.gitattributes', '.gitignore', 'Start-Desktop.cmd', 'Start-Workbench.cmd', 'Stop-Workbench.cmd'].filter(name => fs.existsSync(path.join(sourceRoot, name)))].sort(); const snapshot = () => inputNames.map(relative => ({ path: relative.replaceAll('\\', '/'), bytes: fs.statSync(path.join(sourceRoot, relative)).size, sha256: digest(path.join(sourceRoot, relative)) })); const inputs = snapshot(); fs.writeFileSync(path.join(directory, 'inputs.json'), JSON.stringify(inputs, null, 2)); let stage = 'environment preflight', python = null; @@ -83,7 +83,7 @@ try { assert.deepEqual(actualFiles.slice().sort(), Object.keys(expected).sort()); for (const [relative, sha256] of Object.entries(expected)) assert.equal(digest(path.join(sourceRoot, relative)), sha256, relative); let actualRea = null; - 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'].includes(evidence.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.23.0'].includes(evidence.version)) { stage = 'contained REA'; const reaOutput = await run(['scripts/verify-rea.mjs', '--app-root', sourceRoot, '--contained'], 'rea.log'); actualRea = JSON.parse(reaOutput.trim().split('\n').at(-1)); @@ -91,7 +91,7 @@ try { assert.ok(actualRea.results.every(item => item.rootExited === true)); } 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'].includes(evidence.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.23.0'].includes(evidence.version) && process.argv.includes('--native-engines')) { stage = 'native DeepSeek SDK'; const output = await run(['scripts/verify-engines.mjs'], 'engines.log'); actualEngine = JSON.parse(output.trim().split('\n').at(-1)); @@ -99,7 +99,7 @@ try { assert.equal(actualEngine.modelRequests, 0); assert.equal(actualEngine.rootExited, true); assert.equal(actualEngine.nativeMethods.length, 6); } let actualBrowser = null; - if (['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'].includes(evidence.version)) { + if (['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.23.0'].includes(evidence.version)) { stage = 'contained browser runtime'; const output = await run(['scripts/verify-browser.mjs', '--app-root', sourceRoot, '--contained'], 'browser.log'); actualBrowser = JSON.parse(output.trim().split('\n').at(-1)); @@ -109,7 +109,7 @@ try { assert.equal(actualBrowser.modelRequests, 0); } let actualControlled = 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'].includes(evidence.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.23.0'].includes(evidence.version)) { stage = 'compiled controlled-engine delivery'; const output = await run(['scripts/verify-controlled-release.mjs', '--app-root', sourceRoot], 'controlled-engine.log'); actualControlled = JSON.parse(output.trim().split('\n').at(-1)); @@ -117,7 +117,7 @@ try { assert.equal(actualControlled.realModelRequests, 0); assert.equal(actualControlled.cases, 4); assert.ok(actualControlled.fixtureModelRequests > 0); } let actualCompanion = null; - if (['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0'].includes(evidence.version)) { + if (['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.23.0'].includes(evidence.version)) { stage = 'contained companion gateway and UI'; const output = await run(['scripts/verify-companion-ui.mjs', '--app-root', sourceRoot], 'companion-ui.log'); const location = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1]?.trim(); @@ -128,7 +128,7 @@ try { assert.equal(actualCompanion.passed.length, 7); assert.deepEqual(actualCompanion.errors, []); assert.equal(actualCompanion.realModelRequests, 0); } let actualProtocols = null; - if (['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0'].includes(evidence.version)) { + if (['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) { stage = 'contained model protocols and mobile streams'; const output = await run(['scripts/verify-model-protocols-ui.mjs', '--app-root', sourceRoot], 'model-protocols-ui.log'); const location = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1]?.trim(); @@ -139,7 +139,7 @@ try { assert.equal(actualProtocols.passed.length, 5); assert.deepEqual(actualProtocols.pageErrors, []); assert.deepEqual(actualProtocols.requestFailures, []); } let actualVision = null; - if (['1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0'].includes(evidence.version)) { + if (['1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) { stage = 'contained screenshot inputs and exact Task budget resume'; const output = await run(['scripts/verify-vision-ui.mjs', '--app-root', sourceRoot], 'vision-ui.log'); const location = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1]?.trim(); @@ -150,7 +150,7 @@ try { assert.equal(actualVision.passed.length, 5); assert.deepEqual(actualVision.pageErrors, []); assert.equal(actualVision.realModelRequests, 0); } let actualProjectCache = null; - if (['1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0'].includes(evidence.version)) { + if (['1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) { stage = 'contained source-verified parsing cache controls'; const output = await run(['scripts/verify-project-cache-ui.mjs', '--app-root', sourceRoot], 'project-cache-ui.log'); const location = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1]?.trim(); @@ -161,7 +161,7 @@ try { assert.equal(actualProjectCache.realModelRequests, 0); assert.deepEqual(actualProjectCache.pageErrors, []); } let actualEnvironment = null, actualEnvironmentEngineering = null; - if (['1.21.0','1.22.0'].includes(evidence.version)) { + if (['1.21.0','1.22.0', '1.23.0'].includes(evidence.version)) { stage = 'contained environment approval, stop and recovery UI'; const output = await run(['scripts/verify-environment-ui.mjs', '--app-root', sourceRoot], 'environment-ui.log'); const summary = JSON.parse(output.trim().split(/\r?\n/).findLast(line => line.startsWith('{"success":'))); @@ -179,7 +179,7 @@ try { assert.equal(actualEnvironmentEngineering.pythonTests, 2); assert.equal(actualEnvironmentEngineering.realModelRequests, 0); } let actualEmbeddedBrowser = null; - if (evidence.version === '1.22.0') { + if (['1.22.0', '1.23.0'].includes(evidence.version)) { stage = 'actual embedded Electron, Vite and original mobile observation'; await run(['scripts/verify-embedded-browser.mjs', '--app-root', sourceRoot], 'embedded-browser.log'); actualEmbeddedBrowser = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/embedded-browser-latest.json'), 'utf8')); @@ -188,6 +188,20 @@ try { assert.equal(fs.realpathSync.native(actualEmbeddedBrowser.nodePath), path.join(sourceRoot, 'runtime', 'node.exe')); assert.equal(actualEmbeddedBrowser.realModelRequests, 0); assert.deepEqual(actualEmbeddedBrowser.errors, []); } + let actualReleaseEfficiency = null; + if (evidence.version === '1.23.0') { + stage = 'actual update status Edge/Electron and basic saved HTML flows'; + const proofs = []; + for (const script of ['verify-release-efficiency-ui.mjs', 'verify-local-files.mjs']) { + const output = await run(['scripts/' + script], script + '.log'); + const location = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1]?.trim() + ?? JSON.parse(output.trim().split(/\r?\n/).findLast(line => line.startsWith('{"success":'))).root; + assert.ok(location && path.resolve(location).startsWith(path.join(sourceRoot, '.qa') + path.sep)); + const proof = JSON.parse(fs.readFileSync(path.join(location, 'result.json'), 'utf8')); + assert.ok(proof.passed || proof.success); proofs.push({ script, proof }); + } + actualReleaseEfficiency = proofs; + } // Only this file opens the fixed inspector port. Run it separately so another // test's child host can never compete for that port during the full suite. const testFiles = files(path.join(sourceRoot, 'tests')).filter(file => !file.includes(path.sep) && file.endsWith('.test.mjs')); @@ -215,14 +229,14 @@ try { for (const key of ['fail', 'cancelled', 'skipped', 'todo']) assert.equal(groupStats[key], 0); } let actualTaskControl = null; - if (['1.20.1', '1.21.0', '1.22.0'].includes(evidence.version)) { + if (['1.20.1', '1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) { stage = 'task control desktop and 390px'; await run(['scripts/verify-task-control-ui.mjs', '--app-root', sourceRoot], 'task-control-ui.log'); actualTaskControl = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/task-control-ui-validation.json'), 'utf8')); assert.equal(actualTaskControl.success, true); assert.equal(actualTaskControl.passed.length, 5); assert.equal(actualTaskControl.realModelRequests, 0); } let actualDesktop = null; - 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'].includes(evidence.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.23.0'].includes(evidence.version)) { stage = 'actual contained Electron window'; await run(['scripts/verify-desktop-window.mjs'], 'desktop-window.log'); const window = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/desktop-window-latest.json'), 'utf8')); assert.equal(window.success, true); assert.equal(path.resolve(window.appRoot), sourceRoot); assert.equal(window.results.length, 7); @@ -236,7 +250,7 @@ try { actualDesktop = { window, ui, projects, scope: 'Independently rebuilt source and its shipped Electron binary; original window/engine/engineering assertions. Own credentials/HTTP fixtures; Windows native picker and complete host crash/stop have separate actual evidence.' }; } let actualProtocolEngineering = null; - if (['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0'].includes(evidence.version)) { + if (['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) { stage = 'Responses SSE actual Node React Python engineering'; await run(['scripts/verify-controlled-projects.mjs', '--responses'], 'responses-engineering.log'); const location = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/responses-engineering-location.json'), 'utf8')); @@ -246,7 +260,7 @@ try { assert.deepEqual(actualProtocolEngineering.results.map(value => value.parentCheck.results[0].tests.passed), [8, 9, 10]); } let actualVisionEngineering = null; - if (['1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0'].includes(evidence.version)) { + if (['1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) { stage = 'screenshot Task Node React Python engineering'; await run(['scripts/verify-vision-projects.mjs'], 'vision-engineering.log'); const location = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/vision-engineering-location.json'), 'utf8')); @@ -256,7 +270,7 @@ try { assert.deepEqual(actualVisionEngineering.results.map(value => value.check.results[0].tests.passed), [8, 9, 10]); } let actualCacheEngineering = null; - if (['1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0'].includes(evidence.version)) { + if (['1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) { stage = 'cached index original requests and Node React Python engineering'; await run(['scripts/verify-project-cache-projects.mjs'], 'project-cache-engineering.log'); const location = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/project-cache-engineering-location.json'), 'utf8')); @@ -266,7 +280,7 @@ try { assert.deepEqual(actualCacheEngineering.results.map(value => value.check.results[0].tests.passed), [8, 9, 10]); } let actualEvaluations = null, actualEvaluationEngineering = null; - if (['1.20.0', '1.20.1','1.21.0', '1.22.0'].includes(evidence.version)) { + if (['1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) { stage = 'compiled fixed engineering evaluations'; const output = await run(['scripts/verify-evaluations-release.mjs', '--app-root', sourceRoot], 'evaluations-release.log'); const location = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1]?.trim(); @@ -285,7 +299,7 @@ try { } assert.deepEqual(snapshot(), inputs, 'Source package inputs changed during validation.'); const result = { success: true, version: evidence.version, testedAt: new Date().toISOString(), sourceRoot, directory, nodeVersion: process.version, python, offlineInstall: true, - inputs, inputFiles: inputs.length, logs, buildMatchedFiles: Object.keys(expected).length, buildFiles: Object.entries(expected).map(([path, sha256]) => ({ path: path.replaceAll('\\', '/'), sha256 })), tests: stats, testPlan, actualEmbeddedBrowser, actualEnvironment, actualEnvironmentEngineering, actualTaskControl, actualRea, actualEngine, actualBrowser, actualControlled, actualDesktop, actualCompanion, actualProtocols, actualProtocolEngineering, actualVision, actualVisionEngineering, actualProjectCache, actualCacheEngineering, actualEvaluations, actualEvaluationEngineering, credentialsHandling: 'Only build/runtime environment paths are inherited; no configured model credentials are used. The controlled-engine stage supplies a declared owned local response fixture.' }; + inputs, inputFiles: inputs.length, logs, buildMatchedFiles: Object.keys(expected).length, buildFiles: Object.entries(expected).map(([path, sha256]) => ({ path: path.replaceAll('\\', '/'), sha256 })), tests: stats, testPlan, actualReleaseEfficiency, actualEmbeddedBrowser, actualEnvironment, actualEnvironmentEngineering, actualTaskControl, actualRea, actualEngine, actualBrowser, actualControlled, actualDesktop, actualCompanion, actualProtocols, actualProtocolEngineering, actualVision, actualVisionEngineering, actualProjectCache, actualCacheEngineering, actualEvaluations, actualEvaluationEngineering, credentialsHandling: 'Only build/runtime environment paths are inherited; no configured model credentials are used. The controlled-engine stage supplies a declared owned local response fixture.' }; save(result); console.log(JSON.stringify({ success: true, version: result.version, sourceRoot, directory, tests: stats, nodeVersion: process.version, python, inputFiles: inputs.length, buildMatchedFiles: result.buildMatchedFiles, rea: !!actualRea?.success, engine: !!actualEngine?.success, browser: !!actualBrowser?.success, controlled: !!actualControlled?.success })); } catch (error) { save({ success: false, version: evidence.version, testedAt: new Date().toISOString(), stage, error: error.message, sourceRoot, directory, nodeVersion: process.version, python, inputs, logs }); diff --git a/src/client/App.tsx b/src/client/App.tsx index addceb49..bf700eee 100644 --- a/src/client/App.tsx +++ b/src/client/App.tsx @@ -1,6 +1,8 @@ import { EmbeddedBrowserPanel } from './EmbeddedBrowserPanel'; import { ProjectDirectoryPicker } from './ProjectDirectoryPicker'; import { HtmlFilePreview } from './HtmlFilePreview'; +import { InstallationStatus } from './InstallationStatus'; +import { approvalPresentation } from '../shared/approval-presentation.mjs'; import { useEffect, useMemo, useRef, useState } from 'react'; import { Activity, Brain, ClipboardCheck, RotateCw, ArrowDownToLine, ArrowRight, ArrowUp, BookOpenText, Check, ChevronDown, ChevronRight, Code2, Copy, File, FileCode2, Folder, FolderOpen, GitBranch, Link2, LoaderCircle, Maximize2, MessageSquare, Minimize2, PanelLeftClose, PanelLeftOpen, Pencil, Play, Plus, Puzzle, Search, Server as ModelServer, Settings2, ShieldCheck, Square, SquareTerminal, Trash2, X } from 'lucide-react'; import type { Bootstrap, Change, Config, ModelSelection, FileEntry, OpenFile, Project, ResearchDoc, Session, SessionBrief, ToolEvent, RuntimeDiagnostics, RuntimeFailure } from './types'; @@ -95,6 +97,7 @@ export default function App() { const [workersOpen, setWorkersOpen] = useState(false); const [evaluationsOpen, setEvaluationsOpen] = useState(false); const [desktopOpen, setDesktopOpen] = useState(false); + const [installationOpen, setInstallationOpen] = useState(false); const [companionOpen, setCompanionOpen] = useState(false); const [pickingProject, setPickingProject] = useState(false); const [researchDocs, setResearchDocs] = useState([]); @@ -570,7 +573,7 @@ export default function App() { if (file.kind === 'directory') setCollapsed(previous => { const next = new Set(previous); if (next.has(file.path)) next.delete(file.path); else next.add(file.path); return next; }); else loadFile(file.path); }}>{file.kind === 'directory' ? <>{collapsed.has(file.path) ? : } : <>}{filter ? file.path : file.name})}{filter && !visibleFiles.length &&

没有匹配的文件。

} -
{ready ? '本地服务已连接' : '正在连接本地服务'}v{version}
+
{ready ? '本地服务已连接' : '正在连接本地服务'}
{(!sidebarOpen || mobile) && setSidebarOpen(true)}>}
{selectedProject?.name || '工作空间'} 任务

{session?.title || '让任务走到完成'}

@@ -599,10 +602,10 @@ export default function App() { {isRunning && !approval &&
{session?.executionMode === 'demo' ? '正在执行演示流程' : '正在处理任务'}
} } {session&&} - {approval &&
{approval.environmentPlanId ? '确认依赖准备' : approval.browserPlanId ? '确认实际页面检查' : approval.checkPlanId ? '确认工程检查' : '确认这次终端执行'}

{approval.reason}

{approval.command}
+ {approval &&
{approvalPresentation(approval).title}

{approval.reason}

{approval.command}
{approval.environmentSummary&&

所属工作区:{approval.environmentSummary.root}

注册源:{approval.environmentSummary.registry} · {approval.environmentSummary.offline?'只使用缓存':'允许下载'} · {Math.round(approval.environmentSummary.timeoutMs/1000)} 秒

{approval.environmentSummary.scripts==='skip'?'跳过全部安装脚本':'允许根工程及依赖安装脚本'}
安装脚本范围{approval.environmentSummary.lifecycle.map(row=>
{row.name}
{row.script}
)}

锁文件标记 {approval.environmentSummary.installScriptPackages.length} 个包带安装脚本;下载前无法读取其正文。

准备完成后仍需实际工程检查。停止后保留部分依赖,原计划不会自动重放。

} {approval.checkScripts?.filter(check => check.python).map(check =>

Python {check.python!.runtime.version || '执行时核对版本'} · {check.python!.runtime.logicalExecutable || check.python!.runtime.executable || '解释器缺失'}

)} -
{approval.cwd}

{approval.shell || '项目终端'} · UTF-8

{approval.browserPlanId ? '按封存步骤操作当前构建,保存页面原结果。' : '确认后以你的系统权限执行。'}

} +
{approval.cwd}

{approval.shell || '项目终端'} · UTF-8

{approvalPresentation(approval).scope}

} {pending.length > 0 && !isRunning && } {canContinueReview && }
@@ -624,6 +627,7 @@ export default function App() { {selectedProject && void loadFile(path, { line, expectedSha256 })} />}
{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : tab === 'index' ? '结果绑定当前项目及文件 SHA256' : '读取范围限定在当前项目'}
+ {installationOpen && setInstallationOpen(false)}>} {projectOpen && { if (!projectBusy) { setProjectOpen(false); setDirectoryPickerOpen(false); setProjectError(''); } }}>
{ event.preventDefault(); if (!directoryPickerOpen) void openProject(); }}>{projectError &&

{projectError}

}{directoryPickerOpen && { setProjectInput(value); setProjectError(''); setDirectoryPickerOpen(false); }} onCancel={() => setDirectoryPickerOpen(false)} />}
{exampleId && }
} {companionOpen && setCompanionOpen(false)} wide>} {desktopOpen && desktop && setDesktopOpen(false)}> { if (selectedProjectRef.current === scope.projectId && selectedSessionRef.current === scope.sessionId && selectedTaskRef.current === scope.taskId) { setDesktopOpen(false); showInspector('task'); } }} />} diff --git a/src/client/InstallationStatus.css b/src/client/InstallationStatus.css new file mode 100644 index 00000000..ef4f42ed --- /dev/null +++ b/src/client/InstallationStatus.css @@ -0,0 +1,23 @@ +.installation-status { color: var(--text, #24383e); font-size: 13px; line-height: 1.6; } +.installation-status > header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding-bottom: 18px; border-bottom: 1px solid #dce3e7; } +.installation-status h3 { margin: 0 0 4px; font-size: 15px; } +.installation-status p { margin: 5px 0; } +.installation-status button { flex-shrink: 0; } +.installation-facts { display: grid; grid-template-columns: 76px minmax(0, 1fr); gap: 9px 14px; margin: 18px 0; } +.installation-facts dt { color: #52636c; } +.installation-facts dd { margin: 0; overflow-wrap: anywhere; font: 12px/1.6 var(--font-mono, Consolas, monospace); } +.installation-operation { margin-top: 18px; padding: 18px 0 0; border-top: 1px solid #dce3e7; } +.installation-stage { display: flex; align-items: center; gap: 9px; } +.installation-stage > span:last-child { margin-left: auto; white-space: nowrap; color: #52636c; font-variant-numeric: tabular-nums; } +.installation-state-dot { flex: 0 0 7px; height: 7px; border-radius: 50%; background: #337858; } +.installation-failed .installation-state-dot, .installation-unknown .installation-state-dot { background: #a04832; } +.installation-counts { display: grid; gap: 6px; margin: 16px 0; font-variant-numeric: tabular-nums; } +.installation-counts progress { width: 100%; height: 6px; accent-color: #337858; } +.installation-counts code { overflow-wrap: anywhere; color: #52636c; font-size: 11px; } +.installation-note, .installation-empty { padding: 12px 0; color: #52636c; } +.installation-error { margin-top: 12px; padding: 12px; background: #fff2ed; color: #843620; overflow-wrap: anywhere; border-left: 3px solid #b86d4d; } +.installation-history { display: grid; gap: 6px; margin-top: 16px; color: #52636c; } +.installation-history select { width: 100%; min-width: 0; padding: 8px; border: 1px solid #c5d1d8; border-radius: 4px; color: #24383e; background: #fff; font: inherit; } +.connection .version-entry { color: inherit; padding: 0 3px; margin-left: auto; min-width: 0; width: auto; background: transparent; border: 0; font: inherit; font-size: 11px; cursor: pointer; text-decoration: underline; text-underline-offset: 3px; } +.connection .version-entry:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; } +@media(max-width: 480px) { .installation-status > header { flex-wrap: wrap; } .installation-facts { grid-template-columns: 1fr; gap: 3px; } .installation-facts dd { margin-bottom: 9px; } .installation-stage { flex-wrap: wrap; } } diff --git a/src/client/InstallationStatus.tsx b/src/client/InstallationStatus.tsx new file mode 100644 index 00000000..467dff60 --- /dev/null +++ b/src/client/InstallationStatus.tsx @@ -0,0 +1,49 @@ +import { useEffect, useState } from 'react'; +import { RotateCw } from 'lucide-react'; +import { api } from './api'; +import './InstallationStatus.css'; + +type Operation = { + id: string; sequence: number; state: string; stage: string; label: string; updatedAt: string; elapsedMs: number; scope?: string; + counts?: { completedFiles: number; totalFiles: number; completedBytes: number | null; totalBytes: number | null; currentPath?: string } | null; + candidate?: { version: string; manifestSha256: string } | null; + detail?: { error?: { code: string; message: string }; receiptFile?: string; originalError?: string }; + progressFile: string; interrupted?: boolean; +}; +type Status = { installed: boolean; runningVersion: string; activeVersion?: string; previousVersion?: string | null; installRoot?: string; operations: Operation[] }; +const size = (bytes: number) => { const unit = bytes < 1024 ? 0 : bytes < 1024 ** 2 ? 1 : bytes < 1024 ** 3 ? 2 : 3; return new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 1 }).format(bytes / 1024 ** unit) + ' ' + ['B', 'KB', 'MB', 'GB'][unit]; }; +const scopeLabel = (scope?: string) => scope === 'full-manifest' ? '全部发行文件' : scope === 'directory-inventory' ? '实际目录范围' : scope === 'loaded-inputs' ? '宿主与客户端入口' : ''; + +export function InstallationStatus() { + const [status, setStatus] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState(false); + const [refresh, setRefresh] = useState(0); + const [selected, setSelected] = useState(''); + useEffect(() => { + let alive = true, timer: ReturnType; + const load = async () => { + setBusy(true); + try { + const value = await api('/installation/status'); + if (alive) { setStatus(value); setError(''); } + } catch (value) { if (alive) setError(value instanceof Error ? value.message : '无法读取原安装进度。'); } + finally { if (alive) { setBusy(false); timer = setTimeout(() => void load(), 2500); } } + }; + void load(); return () => { alive = false; clearTimeout(timer); }; + }, [refresh]); + const operation = status?.operations.find(value => value.id === selected) ?? status?.operations[0]; + return
+

当前版本

{status ? <>正在运行 v{status.runningVersion}{status.installed && <> · 已登记 v{status.activeVersion}} : '正在读取本机安装登记…'}

+ {error &&

{error}{status && ' 以下保留上次读取结果,请刷新后再判断当前状态。'}

} + {status && !status.installed &&

当前使用源码或便携目录。安装版会在这里显示所属更新阶段和原始失败记录。

} + {status?.installed &&
程序目录
{status.installRoot}
前一版本
{status.previousVersion ? 'v' + status.previousVersion : '首次安装'}
} + {status?.installed && !operation &&

还没有新版安装进度记录。此前版本的原操作收据保存在程序目录的 .installation 中。

} + {status && status.operations.length > 1 && } + {operation &&
+
{operation.interrupted ? '原安装进程已结束,结果待核对' : operation.label}{Math.round(operation.elapsedMs / 1000)} 秒
+ {operation.counts &&
{scopeLabel(operation.scope)}{operation.counts.completedFiles.toLocaleString()} / {operation.counts.totalFiles.toLocaleString()} 文件{operation.counts.completedBytes !== null && operation.counts.totalBytes !== null && {size(operation.counts.completedBytes)} / {size(operation.counts.totalBytes)}}{operation.counts.currentPath && {operation.counts.currentPath}}
} + {operation.detail?.error &&
{operation.detail.error.code}

{operation.detail.error.message}

} +
目标版本
{operation.candidate ? 'v' + operation.candidate.version : '准备时尚未读取候选'}
操作编号
{operation.id} · 序号 {operation.sequence}
原始记录
{operation.progressFile}
{operation.detail?.receiptFile && <>
结果收据
{operation.detail.receiptFile}
}
+

{operation.state === 'ready-to-copy' ? '预检已通过,写入进度由安装器显示;新版本尚未激活。' : operation.interrupted ? '请保留原安装日志与收据,核对已登记版本。不要根据窗口关闭推断安装成功,也不要重复执行原任务。' : operation.state === 'failed' ? '原失败记录已保留。请按具体原因处理,核对已登记版本及回退收据后再开始新的安装。' : operation.state === 'staged' ? '文件已核对并暂存,当前活动版本保留。' : operation.state === 'running' ? '当前阶段核对实际文件。发布版本和回退期间需要保持安装器打开;各阶段单独计数。' : '原会话与工件保留。这里的安装结果不代表模型工程任务已经通过。'}

+
} +
; +} diff --git a/src/client/companion-types.ts b/src/client/companion-types.ts index a8f42f33..a7ccc9ea 100644 --- a/src/client/companion-types.ts +++ b/src/client/companion-types.ts @@ -18,7 +18,7 @@ export interface MobileTask extends MobileBrief { events: { id: string; label: string; phase: string; output: string; taskId?: string; runId?: string; createdAt: string; exitCode?: number; stream?: { status: string; protocol?: string; textCharacters?: number; textPreview?: string; toolFragments?: number } }[]; messages: { id: string; role: string; content: string; createdAt: string }[]; - approvals: { id: string; taskId: string; runId: string; projectId: string; command: string; reason: string; shell: string; fingerprint: string; actionable: boolean }[]; + approvals: { id: string; taskId: string; runId: string; projectId: string; command: string; reason: string; shell: string; kind?: string; fingerprint: string; actionable: boolean }[]; changes: { id: string; path: string; reason: string; status: string; sha256: string; baseSha256: string; additions: number; deletions: number }[]; checks: { id: string; status: string; summary: string; requiresVerification?: boolean; results: { name: string; status: string; exitCode?: number; tests?: { total: number; passed: number; failed: number; skipped: number; cancelled: number } }[] }[]; reports: { id: string; kind: string; sha256: string; bytes: number }[]; diff --git a/src/client/mobile/MobileApp.tsx b/src/client/mobile/MobileApp.tsx index 334abef9..1ca2d5d1 100644 --- a/src/client/mobile/MobileApp.tsx +++ b/src/client/mobile/MobileApp.tsx @@ -1,4 +1,5 @@ import { MobileBrowserObservation } from './MobileBrowserObservation'; +import { approvalPresentation } from '../../shared/approval-presentation.mjs'; import { useCallback, useEffect, useRef, useState } from 'react'; import { ArrowLeft, ChevronRight, ClipboardCheck, FileDiff, Folder, Link2, RefreshCw, ShieldCheck, Square, Terminal, Wifi, WifiOff, X } from 'lucide-react'; import type { CompanionDevice, MobileBrief, MobileTask } from '../companion-types'; @@ -131,6 +132,6 @@ export function MobileApp({ initialToken }: { initialToken: string }) { {['running', 'awaiting_approval', 'stopping'].includes(selectedTask.status) &&
{me.device.permissions.stop ? '停止仍由电脑等待所属工具退出' : '此设备没有停止权限'}
} }
} {document && setDocument(null)}>
{document.title}

SHA-256 已核对{document.redacted ? ' · 已脱敏' : ''}

{document.sha256}
{document.text}
} - {decision && setDecision(null)}>

{decision.kind === 'stop' ? '停止这个原任务' : decision.allow ? '批准原命令请求' : '拒绝原命令请求'}

{projectName(decision.task.projectId)} · {decision.task.title}

{decision.approval &&
{decision.approval.command}
}Task {decision.task.taskId}
Run {decision.task.runId}
修订 {decision.task.revision}
{decision.task.revision !== task?.revision &&

任务修订已变化,请关闭并重新核对。

}

{decision.kind === 'stop' ? '电脑将停止此运行,并保留已经完成的工具结果。' : decision.allow ? '批准后,电脑将在原项目中执行这条已登记命令。' : '拒绝后,这条原命令不会执行。'}

} + {decision && setDecision(null)}>

{decision.kind === 'stop' ? '停止这个原任务' : (decision.allow ? '批准原' : '拒绝原') + approvalPresentation(decision.approval).subject}

{projectName(decision.task.projectId)} · {decision.task.title}

{decision.approval &&
{decision.approval.command}
}Task {decision.task.taskId}
Run {decision.task.runId}
修订 {decision.task.revision}
{decision.task.revision !== task?.revision &&

任务修订已变化,请关闭并重新核对。

}

{decision.kind === 'stop' ? '电脑将停止此运行,并保留已经完成的工具结果。' : decision.allow ? approvalPresentation(decision.approval).scope : approvalPresentation(decision.approval).denied}

} ; } diff --git a/src/client/types.ts b/src/client/types.ts index 114d4a07..509edb79 100644 --- a/src/client/types.ts +++ b/src/client/types.ts @@ -26,6 +26,7 @@ export interface ExecutionSnapshot {browsingTabs?:BrowsingTab[];browsingActions? export interface CheckPlan {environment?:NodeEnvironmentBinding|null} export interface CheckJob {environment?:NodeEnvironmentBinding|null} export interface Approval {environmentPlanId?:string} +export interface Approval {browsingTabId?:string;mcpRegistrationId?:string} export interface Approval {environmentSummary?:Pick} export interface NodeEnvironmentBinding {preparation?:{jobId:string;planId:string;sessionId:string;logArtifactId:string;logSha256:string}|null} export interface ModelSelection { type: 'legacy' | 'connection' | 'pool'; id: string; name: string } diff --git a/src/core/companion/projection.mjs b/src/core/companion/projection.mjs index 93eca5e4..c8f0e252 100644 --- a/src/core/companion/projection.mjs +++ b/src/core/companion/projection.mjs @@ -1,4 +1,5 @@ import { approvalBinding } from '../../shared/contracts/companion.mjs'; +import { approvalKind } from '../../shared/approval-presentation.mjs'; export const pick = (value, names) => Object.fromEntries(names.filter(key => value?.[key] !== undefined).map(key => [key, structuredClone(value[key])])); export const reportKinds = new Set(['delivery-report', 'delivery-report-markdown']); @@ -24,7 +25,7 @@ export function mobileSession(store, runtime, session, redact = String) { messages: session.messages.filter(value => ['assistant', 'system'].includes(value.role)).slice(-8).map(value => ({ ...pick(value, ['id', 'role', 'createdAt']), content: String(value.content).slice(0, 12000) })), approvals: session.approvals.filter(value => value.status === 'pending' && value.taskId === session.taskId && value.runId === session.runId).map(value => ({ ...pick(value, ['id', 'taskId', 'runId', 'projectId', 'command', 'reason', 'shell', 'createdAt']), - fingerprint: approvalBinding(session, value), actionable: runtime.waiters.get(value.id)?.runId === session.runId })), + kind: approvalKind(value), fingerprint: approvalBinding(session, value), actionable: runtime.waiters.get(value.id)?.runId === session.runId })), changes: session.changes.filter(value => value.taskId === session.taskId).slice(-100).map(value => pick(value, ['id', 'path', 'reason', 'status', 'sha256', 'baseSha256', 'additions', 'deletions'])), checks: checks.slice(-12).map(value => ({ ...pick(value, ['id', 'status', 'summary', 'requiresVerification', 'createdAt', 'finishedAt']), results: (value.results ?? []).map(item => pick(item, ['name', 'status', 'exitCode', 'tests', 'durationMs'])) })), diff --git a/src/core/desktop/app-installation.mjs b/src/core/desktop/app-installation.mjs index 8173fe93..cf072cce 100644 --- a/src/core/desktop/app-installation.mjs +++ b/src/core/desktop/app-installation.mjs @@ -5,7 +5,7 @@ import { binaryIdentity } from './process-identity.mjs'; import { ownedChild, readState, assertLocalTree } from './file-state.mjs'; import { canonicalHost, hostError } from '../../shared/contracts/desktop-host.mjs'; -export function inspectHostInstallation(directory, { full = false } = {}) { +export function inspectHostInstallation(directory, { full = false, onProgress = null } = {}) { assertLocalTree(directory); const root = fs.realpathSync.native(path.resolve(directory)); if (!fs.statSync(root).isDirectory()) throw hostError('宿主安装目录无效。'); @@ -26,10 +26,15 @@ export function inspectHostInstallation(directory, { full = false } = {}) { if (full || /^(dist-client|dist-server|dist-desktop)\//.test(row.path)) files.add(row.path); } if (!manifest || manifest.kind === 'source') for (const entry of fs.readdirSync(path.join(root, 'dist-client/assets'))) files.add('dist-client/assets/' + entry); - const inputs = [...files].sort().map(relative => { + const selected = [...files].sort(), totalBytes = selected.reduce((sum, name) => sum + (names.get(name)?.bytes ?? 0), 0); + let completedFiles = 0, completedBytes = 0; + const report = currentPath => onProgress?.({ scope: full ? 'full-manifest' : 'loaded-inputs', root, totalFiles: selected.length, totalBytes: manifest ? totalBytes : null, completedFiles, completedBytes, currentPath }); + report(null); + const inputs = selected.map(relative => { const file = ownedChild(root, relative), identity = binaryIdentity(file), declared = names.get(relative); if (manifest?.kind === 'portable' && !declared) throw hostError('实际宿主程序不在原发行清单中。'); if (declared && (identity.bytes !== declared.bytes || identity.sha256 !== declared.sha256)) throw hostError('实际宿主程序与原发行清单不一致。'); + completedFiles++; completedBytes += identity.bytes; report(relative); return { path: relative, bytes: identity.bytes, sha256: identity.sha256 }; }); const result = { root, version, kind: manifest?.kind ?? 'development-build', manifestSha256: manifest ? digest(fs.readFileSync(manifestFile)) : null, diff --git a/src/core/desktop/install-manager.mjs b/src/core/desktop/install-manager.mjs index 08db776d..d1e597cf 100644 --- a/src/core/desktop/install-manager.mjs +++ b/src/core/desktop/install-manager.mjs @@ -10,25 +10,28 @@ import { observeWindowsProcess, protectUserDirectory, binaryIdentity } from './p import { ownedChild, readState, writeState, samePath, assertLocalTree } from './file-state.mjs'; import { upgradeRunning } from '../../../scripts/upgrade-running.mjs'; import { canonicalHost, hostError } from '../../shared/contracts/desktop-host.mjs'; +import { InstallationProgress } from './installation-progress.mjs'; const digest = value => createHash('sha256').update(value).digest('hex'); const inside = (root, value) => samePath(root, value) || path.resolve(value).toLowerCase().startsWith(path.resolve(root).toLowerCase() + path.sep); const fail = message => hostError(message, 'INSTALLATION_REJECTED', 409); -export function validateInstalledVersion(directory) { - const installation = inspectHostInstallation(directory, { full: true }); +export function validateInstalledVersion(directory, { onProgress = null } = {}) { + const installation = inspectHostInstallation(directory, { full: true, onProgress }); if (installation.kind !== 'portable') throw fail('安装候选需要完整便携发行清单。'); const manifest = readState(path.join(installation.root, 'MANIFEST.json'), 16 * 1024 * 1024), actual = []; const walk = relative => { for (const entry of fs.readdirSync(path.join(installation.root, relative), { withFileTypes: true })) { const next = path.posix.join(relative, entry.name); ownedChild(installation.root, next); - if (entry.isDirectory()) walk(next); else if (entry.isFile()) actual.push(next); else throw fail('安装候选含有链接或非常规文件。'); + if (entry.isDirectory()) walk(next); else if (entry.isFile()) { + actual.push(next); onProgress?.({ scope: 'directory-inventory', root: installation.root, completedFiles: actual.length, totalFiles: manifest.files.length + 1, completedBytes: null, totalBytes: null, currentPath: next }); + } else throw fail('安装候选含有链接或非常规文件。'); } }; walk(''); const declared = manifest.files.map(value => value.path).concat('MANIFEST.json').sort(); if (!isDeepStrictEqual(actual.sort(), declared)) throw fail('安装候选的实际文件范围与清单不同。'); for (const relative of ['AgentWorkbench.exe', 'runtime/node.exe', 'desktop/AgentWorkbench.exe', 'desktop/resources/app/main.cjs', 'desktop/resources/app/package.json', 'dist-desktop/main.cjs', 'dist-desktop/preload.cjs', 'dist-server/install-manager.mjs']) if (!declared.includes(relative)) throw fail('桌面安装缺少必要运行文件。'); // Full-manifest verification covers all shipped bytes; the host identity is // deliberately the same narrower loaded-input identity used by HostController. - return inspectHostInstallation(directory); + return inspectHostInstallation(directory, { onProgress }); } export function snapshotPersistentData(dataRoot) { @@ -55,7 +58,7 @@ export function snapshotPersistentData(dataRoot) { } export class InstallationManager { - constructor({ installRoot, dataRoot, port = 4318, candidateRoot = null, timeoutMs = 60000 }) { + constructor({ installRoot, dataRoot, port = 4318, candidateRoot = null, timeoutMs = 60000, operationId = null, expectedManifestSha256 = null, onProgress = null }) { for (const value of [installRoot, dataRoot]) if (typeof value !== 'string' || !path.isAbsolute(value)) throw fail('安装和数据目录必须为本机绝对路径。'); if (inside(installRoot, dataRoot) || inside(dataRoot, installRoot) || !Number.isInteger(port) || port < 1 || port > 65535) throw fail('程序与用户数据需要独立目录及有效本机端口。'); assertLocalTree(installRoot, { missing: true }); assertLocalTree(dataRoot, { missing: true }); @@ -64,13 +67,34 @@ export class InstallationManager { this.candidateRoot = candidateRoot ? fs.realpathSync.native(candidateRoot) : null; this.recordFile = ownedChild(this.installRoot, 'current.json', { missing: true }); this.stateRoot = ownedChild(this.installRoot, '.installation', { missing: true }); fs.mkdirSync(this.stateRoot, { recursive: true }); protectUserDirectory(this.stateRoot); + this.progressOptions = { operationId, expectedManifestSha256, onProgress }; + if (expectedManifestSha256 !== null && !/^[a-f0-9]{64}$/.test(expectedManifestSha256)) throw fail('安装候选清单身份无效。'); } + async operation(command, action) { + return this.lock(async () => { + const progress = new InstallationProgress({ stateRoot: this.stateRoot, installRoot: this.installRoot, dataRoot: this.dataRoot, command, ...this.progressOptions }); + this.progress = progress; this.receiptFile = null; + try { + const result = await action(); + // The verified publication receipt is authoritative. A status-file error + // after commit must not relabel an activated version as a failed update. + try { progress.finish(command === 'preflight' ? 'ready-to-copy' : command === 'cancel' ? 'cancelled' : result.phase === 'staged' ? 'staged' : command === 'uninstall' ? 'uninstall-ready' : 'completed', { activeVersion: result.active?.version ?? result.current?.version ?? result.candidate?.version ?? null, receiptFile: result.receiptFile ?? null }); } + catch (error) { if (command === 'preflight') throw error; return { ...result, operationId: progress.value.id, progressFile: progress.file, progressWarning: error.message }; } + return { ...result, progressFile: progress.file, operationId: progress.value.id }; + } catch (error) { try { progress.finish('failed', { error: { code: error.code ?? 'INSTALLATION_FAILED', message: error.message }, receiptFile: this.receiptFile, pointer: fs.existsSync(this.recordFile) ? 'retained-record; inspect original receipt' : 'not-published' }); } catch {} throw error; } + finally { this.progress = null; } + }); + } + phase(name, detail = {}) { this.progress?.phase(name, detail); } + async cancelPreparation() { return this.operation('cancel', async () => ({ phase: 'cancelled', activated: false, dataPolicy: 'preserve-original-data' })); } + verification(scope) { return value => this.progress?.count(scope, value); } current() { if (!fs.existsSync(this.recordFile)) return null; const value = readState(this.recordFile, 16384); if (value.schema !== 1 || value.app !== 'agent-workbench-installation' || !/^[a-f0-9-]{36}$/.test(value.installId ?? '') || !Number.isSafeInteger(value.revision) || value.revision < 1 || !samePath(value.dataRoot ?? '', this.dataRoot) || value.port !== this.port) throw fail('当前安装登记无法核对,保留原记录。'); - const root = this.versionRoot(value.active), actual = validateInstalledVersion(root); + this.phase('verify-current', { version: value.active.version }); + const root = this.versionRoot(value.active), actual = validateInstalledVersion(root, { onProgress: this.verification('verify-current') }); if (actual.version !== value.active.version || actual.manifestSha256 !== value.active.manifestSha256 || actual.identitySha256 !== value.active.runtimeIdentity) throw fail('当前活动版本的实际程序与原登记不同。'); if (value.previous) this.versionRoot(value.previous); return value; @@ -84,7 +108,10 @@ export class InstallationManager { if (!this.candidateRoot) throw fail('没有指定独立安装候选。'); const expected = path.join(this.installRoot, 'versions', path.basename(this.candidateRoot)); if (!samePath(expected, this.candidateRoot)) throw fail('新版本只能位于当前安装的独立versions目录。'); - const identity = validateInstalledVersion(this.candidateRoot); + this.phase('verify-candidate'); + const identity = validateInstalledVersion(this.candidateRoot, { onProgress: this.verification('verify-candidate') }); + if (this.progressOptions.expectedManifestSha256 && identity.manifestSha256 !== this.progressOptions.expectedManifestSha256) throw fail('新候选与本次安装器固定的原清单不同。'); + this.progress?.candidate(identity); return { directory: path.basename(identity.root), version: identity.version, manifestSha256: identity.manifestSha256, runtimeIdentity: identity.identitySha256 }; } async host() { @@ -124,10 +151,12 @@ export class InstallationManager { try { return await action(); } finally { if (fs.existsSync(file) && readState(file).nonce === nonce) { fs.unlinkSync(file); fs.rmdirSync(directory); } } } async preflight({ stageOnly = false } = {}) { - const current = this.current(); this.inspectRoot(current); const host = stageOnly ? null : await this.host(); + return this.operation('preflight', async () => { + const current = this.current(); this.phase('inspect-root'); this.inspectRoot(current); this.phase('inspect-host'); const host = stageOnly ? null : await this.host(); return { allowed: true, phase: stageOnly ? 'stage-only' : 'preflight', current: current?.active ?? null, host: host ? { pid: host.identity.pid, instanceId: host.identity.instanceId, unresolvedTools: host.status.activity.unresolvedTools } : null, dataRoot: this.dataRoot, dataPolicy: 'preserve-original-data' }; + }); } inspectRoot(current) { for (const entry of fs.readdirSync(this.installRoot, { withFileTypes: true })) { @@ -141,10 +170,12 @@ export class InstallationManager { } } async activate({ stageOnly = false, beforePointer = null, afterPointer = null } = {}) { - return this.lock(async () => { + return this.operation('activate', async () => { const candidate = this.candidate(), old = this.current(); this.inspectRoot(old); const priorHost = stageOnly ? null : await this.host(); + this.phase('snapshot-data'); const snapshot = snapshotPersistentData(this.dataRoot), id = randomUUID(), receiptFile = path.join(this.stateRoot, 'operation-' + id + '.json'); - const receipt = { schema: 1, id, state: 'prepared', candidate, original: old?.active ?? null, dataRoot: this.dataRoot, snapshot, stageOnly, startedAt: new Date().toISOString() }; + this.receiptFile = receiptFile; + const receipt = { schema: 1, id, operationId: this.progress?.value.id, state: 'prepared', candidate, original: old?.active ?? null, dataRoot: this.dataRoot, snapshot, stageOnly, startedAt: new Date().toISOString() }; writeState(receiptFile, receipt); if (stageOnly) { writeState(receiptFile, { ...receipt, state: 'staged' }); return { phase: 'staged', candidate, receiptFile, activated: false }; } let upgraded = false, next = null, pointerPublished = false; @@ -161,14 +192,17 @@ export class InstallationManager { }; try { if (priorHost && !samePath(priorHost.identity.runtimeRoot, this.candidateRoot)) { + this.phase('retain-host', { pid: priorHost.identity.pid }); await upgradeRunning({ url: priorHost.controller.url, pid: priorHost.identity.pid, currentRoot: priorHost.identity.appRoot, handlerRoot: priorHost.identity.runtimeRoot, newRoot: this.candidateRoot }); upgraded = true; const nextHost = await this.host(); if (!nextHost || nextHost.identity.pid !== priorHost.identity.pid || nextHost.identity.instanceId !== priorHost.identity.instanceId || nextHost.identity.runtimeIdentity !== candidate.runtimeIdentity) throw fail('新处理器没有保持原宿主实例。'); } + this.phase('verify-data'); const after = snapshotPersistentData(this.dataRoot); if (!isDeepStrictEqual(snapshot, after)) throw fail('安装更新改变了原持久行或工件。'); if (beforePointer) await beforePointer(); if (!isDeepStrictEqual(old, this.current())) throw fail('原安装指针已发生变化,停止发布候选。'); if (!isDeepStrictEqual(candidate, this.candidate())) throw fail('新候选在预检后发生变化,停止发布候选。'); + this.phase('publish-pointer', { interruptible: false }); const actualBootstrap = fs.existsSync(bootstrapFile) ? fs.readFileSync(bootstrapFile) : null; if (!isDeepStrictEqual(actualBootstrap, originalBootstrap)) throw fail('原启动器在预检后发生变化,停止发布候选。'); if (!isDeepStrictEqual(originalBootstrap, candidateBootstrap)) { replaceBootstrap(candidateBootstrap); bootstrapPublished = true; } @@ -176,11 +210,13 @@ export class InstallationManager { dataRoot: this.dataRoot, port: this.port, active: candidate, previous: old?.active ?? null, activatedAt: new Date().toISOString() }; writeState(this.recordFile, next); pointerPublished = true; + this.phase('verify-publication', { interruptible: false }); if (afterPointer) await afterPointer(); // Explicit in-process QA fault fixture, never exposed by the CLI. this.inspectRoot(next); writeState(receiptFile, { ...receipt, state: 'activated', hostRetained: upgraded, finishedAt: new Date().toISOString() }); return { phase: 'activated', active: candidate, receiptFile, hostRetained: upgraded, dataPreserved: true }; } catch (error) { + try { this.phase('rollback', { interruptible: false, originalError: error.message }); } catch {} let rollback = 'pointer-preserved'; try { if (pointerPublished && fs.existsSync(this.recordFile)) { @@ -211,10 +247,10 @@ export class InstallationManager { }); } async prepareUninstall() { - return this.lock(async () => { + return this.operation('uninstall', async () => { const current = this.current(); if (!current) throw fail('没有可核对的本产品安装登记。'); this.inspectRoot(current); - const snapshot = snapshotPersistentData(this.dataRoot), host = await this.host(); + this.phase('snapshot-data'); const snapshot = snapshotPersistentData(this.dataRoot); this.phase('inspect-host'); const host = await this.host(); if (host) await host.controller.stop(); if (!isDeepStrictEqual(snapshot, snapshotPersistentData(this.dataRoot))) throw fail('停止后原持久数据变化,卸载仍需核对。'); const receiptFile = path.join(this.stateRoot, 'uninstall-' + randomUUID() + '.json'); diff --git a/src/core/desktop/installation-progress.mjs b/src/core/desktop/installation-progress.mjs new file mode 100644 index 00000000..61e25012 --- /dev/null +++ b/src/core/desktop/installation-progress.mjs @@ -0,0 +1,84 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { performance } from 'node:perf_hooks'; +import { ownedChild, readState, writeState, samePath } from './file-state.mjs'; +import { observeWindowsProcess } from './process-identity.mjs'; +import { hostError } from '../../shared/contracts/desktop-host.mjs'; + +export const INSTALLATION_STAGES = Object.freeze({ + preparing: '准备安装核对', 'verify-current': '核对原活动版本', 'verify-candidate': '核对新版本', + 'inspect-root': '核对安装目录', 'inspect-host': '核对后台宿主与活动任务', 'snapshot-data': '记录原会话与工件', + 'retain-host': '保留原宿主与模型连接', 'verify-data': '核对原会话与工件保持', + 'publish-pointer': '发布活动版本', 'verify-publication': '核对已发布版本', rollback: '核对原版本回退', + 'ready-to-copy': '预检通过,等待安装器写入版本文件', staged: '候选已暂存,尚未切换版本', + completed: '版本激活完成', failed: '安装未完成,请核对原始原因', 'uninstall-ready': '卸载预检完成,用户数据保留', cancelled: '本次安装准备已取消', +}); +const terminal = new Set(['staged', 'completed', 'failed', 'uninstall-ready', 'cancelled']); +const validId = value => typeof value === 'string' && /^(?:[a-f0-9]{64}|[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})$/.test(value); + +export class InstallationProgress { + constructor({ stateRoot, installRoot, dataRoot, command, operationId = null, expectedManifestSha256 = null, onProgress = null }) { + const id = operationId ?? randomUUID(); + if (!validId(id)) throw hostError('安装操作编号无效。'); + this.file = ownedChild(stateRoot, 'progress-' + id + '.json', { missing: true }); + const previous = fs.existsSync(this.file) ? readState(this.file, 512 * 1024) : null; + if (previous && (previous.schema !== 1 || previous.id !== id || !samePath(previous.installRoot, installRoot) || !samePath(previous.dataRoot, dataRoot) + || previous.expectedManifestSha256 !== expectedManifestSha256 || previous.state !== 'ready-to-copy' || !['activate', 'cancel'].includes(command))) throw hostError('原安装操作不允许重放或改变来源。'); + if (!previous && command === 'cancel') throw hostError('没有可取消的原安装准备记录。'); + this.onProgress = onProgress; this.lastSaved = 0; + this.value = { schema: 1, id, installRoot, dataRoot, command, expectedManifestSha256, + startedAt: previous?.startedAt ?? new Date().toISOString(), sequence: previous?.sequence ?? 0, history: previous?.history ?? [], + process: observeWindowsProcess(process.pid), candidate: previous?.candidate ?? null, state: 'running', stage: 'preparing', scope: null, counts: null, interruptible: false }; + // Process identity only; environment, credentials and private data are never included. + const processIdentity = this.value.process; + this.value.process = processIdentity ? { pid: processIdentity.pid, createdAt: processIdentity.createdAt } : { pid: process.pid, createdAt: null }; + this.phase('preparing'); + } + phase(stage, detail = {}) { + if (!Object.hasOwn(INSTALLATION_STAGES, stage)) throw hostError('安装阶段无效。'); + if (this.value.stageStartedAt) this.value.history.push({ stage: this.value.stage, scope: this.value.scope, counts: this.value.counts, startedAt: this.value.stageStartedAt, finishedAt: new Date().toISOString(), elapsedMs: Math.round(performance.now() - this.phaseStarted) }); + this.value.history = this.value.history.slice(-96); + Object.assign(this.value, { stage, label: INSTALLATION_STAGES[stage], scope: null, counts: null, detail, stageStartedAt: new Date().toISOString() }); + this.phaseStarted = performance.now(); this.save(); + } + count(stage, value) { + if (this.value.stage !== stage || this.value.scope !== value.scope) this.phase(stage, { root: value.root }); + this.value.scope = value.scope; + this.value.counts = { completedFiles: value.completedFiles, totalFiles: value.totalFiles, completedBytes: value.completedBytes, totalBytes: value.totalBytes, currentPath: value.currentPath }; + if (performance.now() - this.lastSaved >= 500 || value.completedFiles === value.totalFiles || value.completedFiles === 0) this.save(); + } + candidate(identity) { + this.value.candidate = { root: identity.root, version: identity.version, manifestSha256: identity.manifestSha256, runtimeIdentity: identity.identitySha256 }; + this.save(); + } + save() { + this.value.sequence++; this.value.updatedAt = new Date().toISOString(); + this.value.elapsedMs = Math.max(0, Date.now() - Date.parse(this.value.startedAt)); + writeState(this.file, this.value); this.lastSaved = performance.now(); + // UI/console observers must never decide the installation result. + try { this.onProgress?.(structuredClone(this.value)); } catch {} + } + finish(state, detail = {}) { + if (!terminal.has(state) && state !== 'ready-to-copy') throw hostError('安装终态无效。'); + this.value.state = state; this.phase(state, detail); + } +} + +export function readInstallationProgress({ appRoot, dataRoot }) { + const versions = path.dirname(appRoot); + if (path.basename(versions).toLowerCase() !== 'versions') return { installed: false, operations: [] }; + const installRoot = path.dirname(versions), pointerFile = ownedChild(installRoot, 'current.json', { missing: true }); + if (!fs.existsSync(pointerFile)) return { installed: false, operations: [] }; + const pointer = readState(pointerFile, 16384); + if (pointer.app !== 'agent-workbench-installation' || !samePath(pointer.dataRoot, dataRoot) || !pointer.active?.version) throw hostError('安装进度与当前数据目录不一致。'); + const stateRoot = ownedChild(installRoot, '.installation', { missing: true }); + const operations = fs.existsSync(stateRoot) ? fs.readdirSync(stateRoot).filter(name => /^progress-(?:[a-f0-9-]{36}|[a-f0-9]{64})\.json$/.test(name)).map(name => { + const value = readState(ownedChild(stateRoot, name), 512 * 1024); + if (value.schema !== 1 || !validId(value.id) || name !== 'progress-' + value.id + '.json' || !samePath(value.installRoot, installRoot) || !samePath(value.dataRoot, dataRoot) || !Number.isSafeInteger(value.sequence) || !Object.hasOwn(INSTALLATION_STAGES, value.stage)) throw hostError('原安装进度无法核对,请保留操作收据。'); + const actual = value.state === 'running' ? observeWindowsProcess(value.process?.pid) : null; + const unknown = value.state === 'running' && (!actual || actual.createdAt !== value.process?.createdAt); + return { ...value, state: unknown ? 'unknown' : value.state, interrupted: unknown, progressFile: path.join(stateRoot, name) }; + }).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, 5) : []; + return { installed: true, activeVersion: pointer.active.version, previousVersion: pointer.previous?.version ?? null, revision: pointer.revision, installRoot, operations }; +} diff --git a/src/desktop/install-cli.mjs b/src/desktop/install-cli.mjs index 34a52081..04e0821e 100644 --- a/src/desktop/install-cli.mjs +++ b/src/desktop/install-cli.mjs @@ -1,14 +1,19 @@ import { InstallationManager } from '../core/desktop/install-manager.mjs'; const args = process.argv.slice(2), command = args.shift(), options = {}; -if (!['preflight', 'activate', 'uninstall'].includes(command)) throw new Error('Unsupported installation operation.'); +if (!['preflight', 'activate', 'uninstall', 'cancel'].includes(command)) throw new Error('Unsupported installation operation.'); while (args.length) { const flag = args.shift(); if (flag === '--stage-only' && !options.stageOnly) { options.stageOnly = true; continue; } - if (!['--install-root', '--data-root', '--candidate-root', '--port'].includes(flag) || !args.length || options[flag] !== undefined) throw new Error('Unsupported or repeated installation field.'); + if (!['--install-root', '--data-root', '--candidate-root', '--port', '--operation-id', '--expected-manifest-sha256'].includes(flag) || !args.length || options[flag] !== undefined) throw new Error('Unsupported or repeated installation field.'); options[flag] = args.shift(); } try { - const manager = new InstallationManager({ installRoot: options['--install-root'], dataRoot: options['--data-root'], candidateRoot: options['--candidate-root'], port: Number(options['--port'] || 4318) }); - const result = command === 'preflight' ? await manager.preflight({ stageOnly: !!options.stageOnly }) : command === 'activate' ? await manager.activate({ stageOnly: !!options.stageOnly }) : await manager.prepareUninstall(); + const manager = new InstallationManager({ installRoot: options['--install-root'], dataRoot: options['--data-root'], candidateRoot: options['--candidate-root'], port: Number(options['--port'] || 4318), operationId: options['--operation-id'] ?? null, expectedManifestSha256: options['--expected-manifest-sha256'] ?? null, + onProgress: value => { + const counts = value.counts; + console.log('AWBPROGRESS ' + (value.label + (counts ? ` · ${counts.completedFiles}/${counts.totalFiles} 文件` + (counts.completedBytes !== null ? ` · ${counts.completedBytes}/${counts.totalBytes} 字节` : '') + (counts.currentPath ? ' · ' + counts.currentPath : '') : '')).replace(/[\r\n]/g, ' ')); + console.log('AWBFILES ' + (counts ? counts.completedFiles + '/' + counts.totalFiles : '-')); + } }); + const result = command === 'preflight' ? await manager.preflight({ stageOnly: !!options.stageOnly }) : command === 'activate' ? await manager.activate({ stageOnly: !!options.stageOnly }) : command === 'cancel' ? await manager.cancelPreparation() : await manager.prepareUninstall(); console.log(JSON.stringify(result)); -} catch (error) { console.error(JSON.stringify({ success: false, code: error.code || 'INSTALLATION_FAILED', message: error.message })); process.exitCode = 1; } +} catch (error) { console.error('AWBERROR ' + error.message); console.error(JSON.stringify({ success: false, code: error.code || 'INSTALLATION_FAILED', message: error.message })); process.exitCode = 1; } diff --git a/src/desktop/installer.iss b/src/desktop/installer.iss index 18e9d17b..bacec07b 100644 --- a/src/desktop/installer.iss +++ b/src/desktop/installer.iss @@ -39,6 +39,8 @@ Filename: "{app}\AgentWorkbench.exe"; Description: "打开 Agent Workbench"; Fla [Code] var DataRoot: String; Port: String; StageOnly: Boolean; Activated: Boolean; ActivationFailed: Boolean; + OperationId: String; LastManagerError: String; PreflightPassed: Boolean; ManagerFinished: Boolean; + ManagerPage: TOutputProgressWizardPage; function Quoted(Value: String): String; begin @@ -51,16 +53,44 @@ begin DataRoot := ExpandConstant('{param:DATA_ROOT|{localappdata}\AgentWorkbench}'); Port := ExpandConstant('{param:PORT|4318}'); StageOnly := ExpandConstant('{param:STAGE_ONLY|0}') = '1'; + OperationId := GetSHA256OfString(ExpandConstant('{tmp}') + GetDateTimeString('yyyy-mm-dd hh:nn:ss', '-', ':')); +end; + +procedure ManagerLog(const S: String; const Error, FirstLine: Boolean); +var Value: String; Separator: Integer; +begin + Log(S); + if Error and (LastManagerError = '') then LastManagerError := S; + if Pos('AWBERROR ', S) = 1 then LastManagerError := Copy(S, 10, Length(S)); + if Pos('AWBPROGRESS ', S) = 1 then ManagerPage.SetText(Copy(S, 13, Length(S)), '正在核对实际文件和原状态;阶段变化来自安装进程。请保持此窗口打开。'); + if Pos('AWBFILES ', S) = 1 then begin + Value := Copy(S, 10, Length(S)); Separator := Pos('/', Value); + ManagerPage.ProgressBar.Visible := Separator > 0; + if Separator > 0 then ManagerPage.SetProgress(StrToIntDef(Copy(Value, 1, Separator - 1), 0), StrToIntDef(Copy(Value, Separator + 1, Length(Value)), 1)); + end; end; function RunManager(Command: String; Candidate: Boolean): Boolean; var Parameters: String; ExitCode: Integer; begin + LastManagerError := ''; Parameters := Quoted(ExpandConstant('{tmp}\awb-install-manager.mjs')) + ' ' + Command + - ' --install-root ' + Quoted(ExpandConstant('{app}')) + ' --data-root ' + Quoted(DataRoot) + ' --port ' + Quoted(Port); + ' --install-root ' + Quoted(ExpandConstant('{app}')) + ' --data-root ' + Quoted(DataRoot) + ' --port ' + Quoted(Port) + + ' --operation-id ' + Quoted(OperationId) + ' --expected-manifest-sha256 {#ManifestSha256}'; if Candidate then Parameters := Parameters + ' --candidate-root ' + Quoted(ExpandConstant('{app}\versions\{#VersionDirectory}')); if StageOnly then Parameters := Parameters + ' --stage-only'; - Result := Exec(ExpandConstant('{tmp}\awb-install-node.exe'), Parameters, ExpandConstant('{tmp}'), SW_HIDE, ewWaitUntilTerminated, ExitCode) and (ExitCode = 0); + if ManagerPage = nil then ManagerPage := CreateOutputProgressPage('Agent Workbench 版本更新', '核对原版本、当前阶段与实际结果'); + ManagerPage.SetText('准备核对安装操作', '操作记录:' + ExpandConstant('{app}') + '\.installation\progress-' + OperationId + '.json'); + ManagerPage.ProgressBar.Visible := False; + if Command <> 'cancel' then ManagerPage.Show; + WizardForm.CancelButton.Enabled := False; + try + Result := ExecAndLogOutput(ExpandConstant('{tmp}\awb-install-node.exe'), Parameters, ExpandConstant('{tmp}'), SW_HIDE, ewWaitUntilTerminated, ExitCode, @ManagerLog) and (ExitCode = 0); + if not Result and (LastManagerError = '') then LastManagerError := '安装进程未返回成功结果;请保留安装日志及原操作收据。'; + finally + WizardForm.CancelButton.Enabled := True; + if Command <> 'cancel' then ManagerPage.Hide; + end; end; function PrepareToInstall(var NeedsRestart: Boolean): String; @@ -70,19 +100,26 @@ begin if DirExists(ExpandConstant('{app}\versions\{#VersionDirectory}')) then begin Result := '该独立版本目录已经存在。请保留原版本,使用新的安装候选。'; exit; end; - if not RunManager('preflight', False) then Result := '安装预检未通过。请等待任务、审批与工具结束并关闭桌面窗口,保留后台执行宿主及原数据;端口和安装身份仍需核对。'; + PreflightPassed := RunManager('preflight', False); + if not PreflightPassed then Result := '安装预检未通过:' + LastManagerError + #13#10 + '原程序和用户数据保留。日志及阶段记录见 .installation 目录。'; end; procedure CurStepChanged(CurStep: TSetupStep); begin if CurStep = ssPostInstall then begin ActivationFailed := True; - if not RunManager('activate', True) then RaiseException('候选激活失败;已尝试恢复原安装指针和执行宿主。请保留 .installation 操作收据核对结果。'); + if not RunManager('activate', True) then RaiseException('候选激活未完成:' + LastManagerError + #13#10 + '请保留 .installation 原操作收据,核对当前指针和回退结果。'); ActivationFailed := False; Activated := not StageOnly; + ManagerFinished := True; end; end; +procedure DeinitializeSetup; +begin + if PreflightPassed and not ManagerFinished and not ActivationFailed then RunManager('cancel', False); +end; + function GetCustomSetupExitCode: Integer; begin if ActivationFailed then Result := 8 else Result := 0; diff --git a/src/server/app.mjs b/src/server/app.mjs index 420d830c..783ac216 100644 --- a/src/server/app.mjs +++ b/src/server/app.mjs @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import { createHash } from 'node:crypto'; import path from 'node:path'; import { listFiles, readText, proposeFile, proposePatch, applyChange } from './files.mjs'; import { APP_VERSION, executionEnvironment, sessionSnapshot } from './diagnostics.mjs'; @@ -19,6 +20,7 @@ import { inspectOperations } from './operations.mjs'; import { validateModelWaitSettings } from '../core/models/request-deadline.mjs'; import { nativeParameterSettings } from '../shared/contracts/native-parameters.mjs'; import { localDirectories } from './local-directories.mjs'; +import { readInstallationProgress } from '../core/desktop/installation-progress.mjs'; export function createSessionPublisher(clients) { return session => { @@ -110,6 +112,7 @@ return async (request, response) => { } if (method === 'GET' && route === '/api/host/identity') return json(response, host().attest(url.searchParams.get('challenge'))); if (method === 'GET' && route === '/api/host/status') return json(response, host().status()); + if (method === 'GET' && route === '/api/installation/status') return json(response, { ...readInstallationProgress({ appRoot: appDirectory, dataRoot: store.directory }), runningVersion: APP_VERSION }); if (method === 'POST' && route === '/api/host/windows/register') return json(response, host().registerWindow(await body(request))); if (method === 'POST' && route === '/api/host/windows/unregister') { const input = await body(request); const result = host().unregisterWindow(input); runtime.browsing?.disconnect(input.windowId); return json(response, result); @@ -837,7 +840,9 @@ return async (request, response) => { const document = research.find(item => item.id === report[1]); if (!document) throw new Error('研究报告不存在。'); const file = path.join(appDirectory, 'docs', document.file); - return json(response, { title: document.title, content: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '这份报告正在整理,完成后会保存在产品的 docs 目录。' }); + if (!fs.existsSync(file)) throw Object.assign(new Error('这份原研究报告缺失,请核对完整发行文件。'), { status: 404 }); + const bytes = fs.readFileSync(file); + return json(response, { title: document.title, content: bytes.toString('utf8'), sha256: createHash('sha256').update(bytes).digest('hex') }); } if (method === 'POST' && route === '/api/shutdown') { await body(request); diff --git a/src/server/diagnostics.mjs b/src/server/diagnostics.mjs index 68b22dfc..618fbbf0 100644 --- a/src/server/diagnostics.mjs +++ b/src/server/diagnostics.mjs @@ -1,6 +1,6 @@ import { randomUUID, createHash } from 'node:crypto'; -export const APP_VERSION = '1.22.1'; +export const APP_VERSION = '1.23.0'; export function executionEnvironment() { const windows = process.platform === 'win32'; diff --git a/src/server/runtime.mjs b/src/server/runtime.mjs index fead51f0..19c84f30 100644 --- a/src/server/runtime.mjs +++ b/src/server/runtime.mjs @@ -1,3 +1,4 @@ +import { approvalPresentation } from '../shared/approval-presentation.mjs'; import { PreviewManager } from '../core/preview/preview-manager.mjs'; import { LocalFilePreviews } from '../core/preview/local-file-preview.mjs'; import { BrowsingManager } from '../core/browser/browsing-manager.mjs'; @@ -712,7 +713,7 @@ export class Runtime { signal.addEventListener('abort', cancel, { once: true }); if (signal.aborted) cancel(); }); - if (!decision) { if (!run.controller.signal.aborted) session.status = 'running'; return { status: run.controller.signal.aborted ? 'interrupted' : 'denied', message: '命令未执行。', requires_verification: false }; } + if (!decision) { if (!run.controller.signal.aborted) session.status = 'running'; return { status: run.controller.signal.aborted ? 'interrupted' : 'denied', message: approvalPresentation(approval).denied, requires_verification: false }; } run.controller.signal.throwIfAborted(); const cwd = safePath(run.project); event.phase = 'running'; event.executedAt = now(); session.status = 'running'; diff --git a/src/shared/approval-presentation.d.mts b/src/shared/approval-presentation.d.mts new file mode 100644 index 00000000..7a4e4a4a --- /dev/null +++ b/src/shared/approval-presentation.d.mts @@ -0,0 +1,4 @@ +export type ApprovalKind = 'browsing' | 'environment' | 'mcp' | 'page-check' | 'check' | 'command'; +export interface ApprovalSource { kind?: string; browsingTabId?: string; environmentPlanId?: string; mcpRegistrationId?: string; browserPlanId?: string; checkPlanId?: string } +export function approvalKind(value?: ApprovalSource): ApprovalKind; +export function approvalPresentation(value?: ApprovalSource): { title: string; subject: string; scope: string; denied: string }; diff --git a/src/shared/approval-presentation.mjs b/src/shared/approval-presentation.mjs new file mode 100644 index 00000000..69728275 --- /dev/null +++ b/src/shared/approval-presentation.mjs @@ -0,0 +1,16 @@ +// Derived from the original approval, never from model prose or page content. +export function approvalKind(value = {}) { + return value.browsingTabId ? 'browsing' : value.environmentPlanId ? 'environment' : value.mcpRegistrationId ? 'mcp' + : value.browserPlanId ? 'page-check' : value.checkPlanId ? 'check' : 'command'; +} +export function approvalPresentation(value = {}) { + const kind = value.kind ?? approvalKind(value); + return ({ + browsing: { title: '确认浏览器操作', subject: '浏览器操作', scope: '只在原标签页、原页面观察及已批准范围内执行这次固定动作。', denied: '浏览器操作未执行。' }, + environment: { title: '确认依赖准备', subject: '依赖准备', scope: '按封存计划准备所属工作区依赖;安装脚本和下载范围如下。', denied: '依赖准备未执行。' }, + mcp: { title: '确认 MCP 工具调用', subject: 'MCP 工具调用', scope: '向所属 MCP 独立进程发送下方已登记工具与参数。', denied: 'MCP 工具未调用。' }, + 'page-check': { title: '确认实际页面检查', subject: '页面检查', scope: '按封存步骤操作当前构建,保存页面原结果。', denied: '页面检查未执行。' }, + check: { title: '确认工程检查', subject: '工程检查', scope: '在原项目中执行下方已登记检查。', denied: '工程检查未执行。' }, + command: { title: '确认这次终端执行', subject: '命令请求', scope: '确认后以你的系统权限执行这条原命令。', denied: '命令未执行。' }, + })[kind] ?? approvalPresentation({ kind: 'command' }); +} diff --git a/task_plan.md b/task_plan.md index bc54fac5..3e299758 100644 --- a/task_plan.md +++ b/task_plan.md @@ -1,5 +1,15 @@ # Agent Workbench:核心代理能力研究与产品计划 +## 当前阶段:1.23 发行效率与更新进度 + +接续已交付1.22.1,基线397099b,分支feat/release-efficiency-1.23。用户授权全量推进并及时回顾;按docs/PLAN-1.23.md执行,不委派新代理。保留正式宿主、Provider、用户项目与原证据;研发使用独立数据/端口,不发起真实模型请求。 + +1. [complete] A:核对运行/帮助/研究报告引用闭包,固定同载荷基线、计时来源与更新契约。 +2. [complete] B:运行载荷与历史证据分发拆分;源码保持完整,证据原路径/SHA/来源可追溯。 +3. [complete] C:所属操作/阶段/文件字节计数/终态收据,安装器和桌面真实进度与失败恢复;修正审批类别标题。 +4. [complete] D:审查重复核对边界,仅采纳可证明完整性和并发拒绝的复用;不足时保留完整校验。 +5. [in_progress] E:相关与独立发行验收、实际安装/升级/冷启动/卸载、基础用户操作回看、正式保留状态部署、证据和Git收尾。 + ## 已完成:1.22.1 项目文件夹选择与 HTML 预览修复 用户在正式网页现场指出的两条基础流程缺失已优先修复,产品实现70ac4c4。网页可选择本机项目文件夹,HTML默认可视预览并支持源码切换、刷新与独立打开;保留原项目范围和隔离边界。 diff --git a/tests/release-efficiency.test.mjs b/tests/release-efficiency.test.mjs new file mode 100644 index 00000000..a502b3a1 --- /dev/null +++ b/tests/release-efficiency.test.mjs @@ -0,0 +1,154 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { randomUUID, createHash } from 'node:crypto'; +import { fixture, workspace } from './helpers.mjs'; +import { createDocumentationBundle, REQUIRED_REPORTS } from '../scripts/documentation-bundle.mjs'; +import { InstallationManager, validateInstalledVersion, snapshotPersistentData } from '../src/core/desktop/install-manager.mjs'; +import { InstallationProgress, readInstallationProgress } from '../src/core/desktop/installation-progress.mjs'; +import { approvalPresentation, approvalKind } from '../src/shared/approval-presentation.mjs'; +import { mobileSession } from '../src/core/companion/projection.mjs'; +import { approvalBinding } from '../src/shared/contracts/companion.mjs'; + +const hash = value => createHash('sha256').update(value).digest('hex'); +const json = file => JSON.parse(fs.readFileSync(file, 'utf8')); +function candidate(f, name = 'owned-a') { + const root = path.join(f.root, 'install', 'versions', name); fs.mkdirSync(root, { recursive: true }); + for (const dir of ['dist-client', 'dist-server', 'dist-desktop']) fs.cpSync(path.join(workspace, dir), path.join(root, dir), { recursive: true }); + for (const file of ['AgentWorkbench.exe', 'runtime/node.exe', 'desktop/AgentWorkbench.exe', 'desktop/resources/app/main.cjs', 'desktop/resources/app/package.json']) { + const target = path.join(root, file); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, 'owned-static-fixture-only'); + } + const walk = (dir, prefix = '') => fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => { + const next = path.posix.join(prefix, entry.name), file = path.join(dir, entry.name); + return entry.isDirectory() ? walk(file, next) : [{ path: next, bytes: fs.statSync(file).size, sha256: hash(fs.readFileSync(file)) }]; + }); + fs.writeFileSync(path.join(root, 'MANIFEST.json'), JSON.stringify({ app: 'agent-workbench', kind: 'portable', platform: 'win32-x64', version: json(path.join(workspace, 'package.json')).version, files: walk(root) })); + return root; +} +function manager(f, root, extra = {}) { + const m = new InstallationManager({ installRoot: path.join(f.root, 'install'), dataRoot: f.data, candidateRoot: root, port: 49999, ...extra }); + m.host = async () => null; return m; +} +function documentation(f) { + const root = path.join(f.root, 'source'), portableRoot = path.join(f.root, 'portable'), evidenceRoot = path.join(f.root, 'evidence'); + fs.mkdirSync(path.join(root, 'docs', 'raw'), { recursive: true }); + for (const file of REQUIRED_REPORTS) { fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); fs.writeFileSync(path.join(root, file), '# 原研究\r\n[原件](../raw/failed.json)\r\n'); } + fs.writeFileSync(path.join(root, 'docs', 'raw', 'failed.json'), '{"success":false,"original":"失败也保留"}\n'); + fs.writeFileSync(path.join(root, 'docs', 'GUIDE.md'), '# 指南\n[原失败](raw/failed.json)\n[历史缺失](old-missing.json)\n[异常链接](bad%XX.json)\n'); + fs.writeFileSync(path.join(root, 'README.md'), '# 工作台\n[证据](docs/raw/failed.json)\n'); + return { root, portableRoot, evidenceRoot, archiveName: 'Agent-Workbench-evidence.zip', sourceCommit: 'a'.repeat(40) }; +} + +test('runtime guides map archived evidence while all original reports and successful/failed source bytes remain independently verifiable', t => { + const f = fixture(t), input = documentation(f), result = createDocumentationBundle(input); + assert.equal(result.originalFiles, 6); + for (const row of result.evidenceEntries) assert.equal(hash(fs.readFileSync(path.join(input.evidenceRoot, row.path))), row.sha256); + assert.equal(hash(fs.readFileSync(path.join(input.evidenceRoot, 'MANIFEST.json'))), result.evidenceManifestSha256); + for (const file of REQUIRED_REPORTS) assert.deepEqual(fs.readFileSync(path.join(input.portableRoot, file)), fs.readFileSync(path.join(input.root, file))); + assert.equal(fs.existsSync(path.join(input.portableRoot, 'docs/raw/failed.json')), false); + assert.match(fs.readFileSync(path.join(input.portableRoot, 'docs/GUIDE.md'), 'utf8'), /EVIDENCE-CATALOG\.md#e-[a-f0-9]{16}/); + assert.ok(result.references.some(row => row.disposition === 'historical-source-not-in-repository')); + assert.ok(result.references.some(row => row.disposition === 'malformed-historical-reference')); + assert.equal(json(path.join(input.evidenceRoot, 'docs/raw/failed.json')).success, false); + assert.throws(() => createDocumentationBundle(input), /new directory/); +}); +test('missing required research reports fail packaging rather than creating a successful placeholder', t => { + const f = fixture(t), input = documentation(f); fs.unlinkSync(path.join(input.root, REQUIRED_REPORTS[0])); + assert.throws(() => createDocumentationBundle(input), /Required original research report missing/); + assert.equal(fs.existsSync(input.evidenceRoot), false); +}); +test('full verification reports only verified bytes, complete declared scope and actual directory inventory; changed/deleted files still fail', t => { + const f = fixture(t), root = candidate(f), counts = []; + validateInstalledVersion(root, { onProgress: value => counts.push(value) }); + const manifest = json(path.join(root, 'MANIFEST.json')), full = counts.filter(row => row.scope === 'full-manifest'); + assert.equal(full[0].completedFiles, 0); assert.equal(full.at(-1).completedFiles, manifest.files.length); + assert.equal(full.at(-1).completedBytes, manifest.files.reduce((sum, row) => sum + row.bytes, 0)); + assert.ok(full.every((row, index) => row.completedFiles === index)); + assert.equal(counts.filter(row => row.scope === 'directory-inventory').at(-1).completedFiles, manifest.files.length + 1); + const file = path.join(root, 'dist-client/index.html'), original = fs.readFileSync(file); + fs.appendFileSync(file, 'altered'); assert.throws(() => validateInstalledVersion(root)); + fs.writeFileSync(file, original); fs.unlinkSync(file); assert.throws(() => validateInstalledVersion(root)); +}); +test('preflight and activation continue one monotonic operation bound to installer hash; terminal replay and changed origin are rejected', async t => { + const f = fixture(t), root = candidate(f), operationId = randomUUID(), manifestSha = hash(fs.readFileSync(path.join(root, 'MANIFEST.json'))), samples = []; + const opts = { operationId, expectedManifestSha256: manifestSha, onProgress: value => samples.push(value) }; + const first = await manager(f, root, opts).preflight(); assert.equal(json(first.progressFile).state, 'ready-to-copy'); + const prior = json(first.progressFile), result = await manager(f, root, opts).activate(); + assert.equal(result.operationId, operationId); assert.equal(result.progressFile, first.progressFile); + const progress = json(first.progressFile); assert.equal(progress.state, 'completed'); assert.ok(progress.sequence > prior.sequence); assert.ok(progress.elapsedMs >= prior.elapsedMs); + assert.equal(json(result.receiptFile).operationId, operationId); assert.equal(progress.detail.receiptFile, result.receiptFile); + assert.ok(samples.every((row, index) => !index || row.sequence > samples[index - 1].sequence)); + await assert.rejects(manager(f, root, opts).activate(), /重放/); + await assert.rejects(manager(f, root, { ...opts, expectedManifestSha256: 'b'.repeat(64) }).activate(), /来源/); +}); +test('preflight failures and fixed-candidate mismatches retain the actual reason without publishing a pointer', async t => { + const f = fixture(t), root = candidate(f), m = manager(f, root), unknown = path.join(m.installRoot, 'unrelated.txt'); fs.writeFileSync(unknown, 'owned-original'); + await assert.rejects(m.preflight(), /未登记/); + let progress = fs.readdirSync(m.stateRoot).filter(name => name.startsWith('progress-')).map(name => json(path.join(m.stateRoot, name))); + assert.equal(progress[0].state, 'failed'); assert.match(progress[0].detail.error.message, /未登记/); + fs.unlinkSync(unknown); + const mismatch = manager(f, root, { expectedManifestSha256: 'b'.repeat(64) }); + await assert.rejects(mismatch.activate(), /固定的原清单不同/); assert.equal(mismatch.current(), null); +}); +test('cancel finishes only the original ready preparation, preserves data and pointer and refuses replay', async t => { + const f = fixture(t), root = candidate(f), operationId = randomUUID(), m = manager(f, root, { operationId }), before = snapshotPersistentData(f.data); + const first = await m.preflight(), result = await manager(f, root, { operationId }).cancelPreparation(); + assert.equal(result.activated, false); assert.equal(json(first.progressFile).state, 'cancelled'); + assert.equal(m.current(), null); assert.deepEqual(snapshotPersistentData(f.data), before); + await assert.rejects(manager(f, root, { operationId }).cancelPreparation(), /重放/); + await assert.rejects(manager(f, root, { operationId: randomUUID() }).cancelPreparation(), /没有可取消/); +}); +test('the installation lock rejects concurrent same-id operations before they can overwrite original progress', async t => { + const f = fixture(t), root = candidate(f), operationId = randomUUID(), m = manager(f, root, { operationId }); + let release, entered; const ready = new Promise(resolve => entered = resolve), held = new Promise(resolve => release = resolve); + m.host = async () => { entered(); await held; return null; }; + const first = m.preflight(); await ready; + const file = path.join(m.stateRoot, 'progress-' + operationId + '.json'), before = fs.readFileSync(file); + await assert.rejects(manager(f, root, { operationId }).preflight(), /仍在运行/); + assert.deepEqual(fs.readFileSync(file), before); release(); await first; +}); +test('original post-publication failure is linked to its rollback receipt and every original byte survives', async t => { + const f = fixture(t), root = candidate(f), m = manager(f, root), before = snapshotPersistentData(f.data); + await assert.rejects(m.activate({ afterPointer: () => { throw Error('owned-original-publication-failure'); } }), /owned-original-publication-failure/); + const progress = json(path.join(m.stateRoot, fs.readdirSync(m.stateRoot).find(name => name.startsWith('progress-')))); + assert.equal(progress.state, 'failed'); assert.match(progress.detail.error.message, /owned-original-publication-failure/); + assert.equal(json(progress.detail.receiptFile).state, 'failed'); assert.equal(m.current(), null); assert.deepEqual(snapshotPersistentData(f.data), before); +}); +test('a candidate mutation at the publication boundary still fails even after an earlier successful full validation', async t => { + const f = fixture(t), root = candidate(f), m = manager(f, root); await m.activate(); const original = fs.readFileSync(m.recordFile); + const next = candidate(f, 'owned-b'); m.candidateRoot = next; + await assert.rejects(m.activate({ beforePointer: () => fs.appendFileSync(path.join(next, 'dist-client/index.html'), 'changed-during-update') })); + assert.deepEqual(fs.readFileSync(m.recordFile), original); +}); +test('public progress marks a lost process unknown without editing its original record or claiming completion', async t => { + const f = fixture(t), root = candidate(f), m = manager(f, root); await m.activate(); + const p = new InstallationProgress({ stateRoot: m.stateRoot, installRoot: m.installRoot, dataRoot: m.dataRoot, command: 'preflight' }); + const value = json(p.file); value.process.createdAt = 'owned-mismatched-process-time'; value.updatedAt = '2099-01-01T00:00:00.000Z'; fs.writeFileSync(p.file, JSON.stringify(value)); + const before = fs.readFileSync(p.file), status = readInstallationProgress({ appRoot: root, dataRoot: f.data }); + assert.equal(status.operations[0].state, 'unknown'); assert.equal(status.operations[0].interrupted, true); assert.deepEqual(fs.readFileSync(p.file), before); + assert.equal(readInstallationProgress({ appRoot: workspace, dataRoot: f.data }).installed, false); +}); +test('throwing console/UI progress observers cannot decide the installation result', async t => { + const f = fixture(t), root = candidate(f), m = manager(f, root, { onProgress() { throw Error('owned-observer-error'); } }); + const result = await m.activate(); assert.equal(result.phase, 'activated'); assert.equal(json(result.progressFile).state, 'completed'); +}); +test('a progress-only write failure after committed publication returns the authoritative receipt and a warning', async t => { + const f = fixture(t), root = candidate(f), m = manager(f, root); + const result = await m.activate({ afterPointer: () => { m.progress.finish = () => { throw Error('owned-status-storage-failure'); }; } }); + assert.equal(result.phase, 'activated'); assert.equal(result.progressWarning, 'owned-status-storage-failure'); + assert.equal(json(result.receiptFile).state, 'activated'); assert.equal(m.current().active.directory, path.basename(root)); +}); +test('browser and MCP approvals use actual tool categories; mobile exposes only category while keeping original fingerprint', t => { + const f = fixture(t), session = f.session; session.taskId = randomUUID(); session.runId = randomUUID(); + for (const [field, kind] of [['browsingTabId', 'browsing'], ['mcpRegistrationId', 'mcp'], ['environmentPlanId', 'environment'], ['browserPlanId', 'page-check'], ['checkPlanId', 'check']]) { + const approval = { id: randomUUID(), taskId: session.taskId, runId: session.runId, projectId: session.projectId, [field]: randomUUID(), status: 'pending', command: 'owned fixed operation', browsingInput: { secret: 'not-projected' } }; + session.approvals = [approval]; const original = structuredClone(approval), expected = approvalBinding(session, approval); + const projected = mobileSession(f.store, { waiters: new Map([[approval.id, { runId: session.runId }]]) }, session).approvals[0]; + assert.equal(approvalKind(approval), kind); assert.equal(projected.kind, kind); assert.equal(projected.fingerprint, expected); + assert.equal(Object.hasOwn(projected, 'browsingInput'), false); assert.deepEqual(approval, original); + assert.equal(approvalPresentation(approval).title, approvalPresentation(projected).title); + } + assert.equal(approvalPresentation({ browsingTabId: 'owned' }).title, '确认浏览器操作'); + assert.equal(approvalPresentation({ browsingTabId: 'owned' }).denied, '浏览器操作未执行。'); +});