feat: integrate reviewed batches and preserve task continuation
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
|
||||
本仓库专注AI编程与能力研究工作台。其他项目不纳入本项目计划或代码。用户确定的研究对象为Codex、Claude Code、Cursor、DeepSeek Harness、WorkBuddy及DSH-purge;目标是将有证据的机制独立开发成自有Harness内置能力。
|
||||
|
||||
1.0.0是已保存的基础里程碑;1.1.0已交付M1可靠内核,1.2.0增加当前Task的本地Git交付及证据报告,1.3.0增加有界工程索引与精确补丁。后续实现与真实工程验收见docs/PRODUCT-PLAN.md、docs/CAPABILITIES.md和docs/RESEARCH-ROADMAP.md。计划中的能力不能写成已经实现。
|
||||
1.0.0是已保存的基础里程碑;1.1.0已交付M1可靠内核,1.2.0增加当前Task的本地Git交付及证据报告,1.3.0增加工程索引与精确补丁,1.4.0增加封存多文件变更集与显式恢复。各版本实际部署与验收见docs/VALIDATION.md,后续实现见docs/PRODUCT-PLAN.md、docs/CAPABILITIES.md和docs/RESEARCH-ROADMAP.md。计划中的能力不能写成已经实现。
|
||||
|
||||
## 研究与来源
|
||||
|
||||
|
||||
+10
-1
@@ -1,5 +1,14 @@
|
||||
# Agent Workbench 更新记录
|
||||
|
||||
## 1.4.0 · 2026-10-29
|
||||
|
||||
- 同Task的1–32个文件可封存为统一变更集,保存原/新字节快照、Git基线与审查指纹;模型提供准备工具,桌面与390px界面查看整批差异并确认应用。
|
||||
- 写入前核对全部文件,任一基线冲突则整批不写入;逐文件保存意图和实际结果,失败后按哈希回退,外部编辑内容保留。
|
||||
- 实际进程中断后提供核对、回退及保留外部内容的明确恢复入口,结果未知时阻止同项目的新运行、写入、检查和Git提交;启动不自动重放批次。
|
||||
- 交付报告记录批次身份、封存指纹、实际状态和快照校验。已封存提案不能绕过批次单独应用。
|
||||
- 工具轮次上限后封存的批次应用完成可继续原Task进行实际检查;主动停止、其他预算或结果待核对仍保持各自恢复要求。
|
||||
- 切换项目/会话时清理旧任务的临时提示,原错误及恢复事件保留在所属任务。完整回归、独立包和真实模型的结果见[验收记录](docs/VALIDATION.md)。
|
||||
|
||||
## 1.3.0 · 2026-10-29
|
||||
|
||||
- 增加当前项目的工程索引:JS/TS/React静态声明与导入、Python声明候选、逐文件SHA256增量复用及覆盖范围;新增index_project/query_code模型工具和Task所属索引工件。
|
||||
@@ -31,7 +40,7 @@
|
||||
- 增加Task/Run/工件/预算界面、断线补发和390px日志弹窗;便携宿主随附npm,支持旧Node原进程使用新发行目录的检查器。
|
||||
- 新增封存四模块工程和真实模型交付验收器,记录测试/构建、保护输入、既有改动、审查次数和源文件独立Git提交。
|
||||
|
||||
验收结果以[实际验证记录](docs/VALIDATION.md)为准。任务依赖图、增量索引、ChangeSet、外部引擎及桌面/手机配对继续按M2–M6实施。
|
||||
验收结果以[实际验证记录](docs/VALIDATION.md)为准。任务依赖图、隔离worktree、多类工程验收、外部引擎及桌面/手机配对继续按M2–M6实施。
|
||||
|
||||
## 1.0.0 · 2026-10-29
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# 本地 Agent 工作台
|
||||
|
||||
Agent Workbench 1.3.0 将 Claude Code 与 Cursor 的机制研究整合为独立的本地 AI 编程工作台。工程索引、代码定位、精确补丁、实际检查、文件审查、本地Git提交及交付报告可以在同一个Task中完成。
|
||||
Agent Workbench 1.4.0 将 Claude Code 与 Cursor 的机制研究整合为独立的本地 AI 编程工作台。工程索引、精确补丁、多文件整批审查、实际检查、本地Git提交及交付报告可以在同一个Task中完成。
|
||||
|
||||
每次运行保留模型与预算、已完成工具和日志工件。索引结果可打开实际文件行,精确补丁按文件SHA256和唯一锚点保留未修改内容与格式。检查通过需要实际退出码、测试数量和对应源码快照;应用改动后可点击「继续检查与交付」,沿用原目标进行测试与修复。提交前查看实际文件、diff、署名和检查结果,确认后生成本地提交及可下载的JSON/Markdown报告。版本改动见 [CHANGELOG](CHANGELOG.md),能力范围见[索引与补丁契约](docs/CODE-INDEX-AND-PATCHES.md)。
|
||||
每次运行保留模型与预算、已完成工具和日志工件。多文件变更集封存同Task的原/新字节、Git基线与审查指纹,应用前核对整批文件;中断后显式核对或回退,保留外部修改。应用改动后可点击「继续检查与交付」,沿用原目标进行实际测试与修复。提交前查看实际文件、diff、署名和检查结果,确认后生成本地提交及可下载的JSON/Markdown报告。版本改动见 [CHANGELOG](CHANGELOG.md),编辑范围见[索引与补丁](docs/CODE-INDEX-AND-PATCHES.md)和[变更集恢复契约](docs/CHANGE-SETS.md)。
|
||||
|
||||
## 后续产品与能力建设
|
||||
|
||||
@@ -13,7 +13,7 @@ Agent Workbench 1.3.0 将 Claude Code 与 Cursor 的机制研究整合为独立
|
||||
- [研究路线](docs/RESEARCH-ROADMAP.md)与[目标来源登记](research/targets.json):版本、来源、SDK限制及未解决问题。
|
||||
- [本地Git流程](docs/GIT-WORKFLOW.md)与[项目执行规范](AGENTS.md):源码仓库已建立,main基线`bac87da`、标签`v1.0.0-baseline`;后续按独立小步检查并及时提交。
|
||||
|
||||
1.3.0实现有界JS/TS/React静态索引、Python声明候选和精确补丁,沿用Node/npm检查job、当前Task已审核文件的Git交付及证据报告。任务依赖图、语义引用、ChangeSet、隔离worktree、多类工程检查器、外部引擎、REA执行和桌面/手机配对继续按后续阶段建设。
|
||||
1.4.0增加1–32文件的封存变更集与可恢复应用,沿用工程索引、Node/npm检查job和当前Task的Git交付。文件系统没有跨文件原子事务,部分执行会明确显示需核对。改名/删除、任务依赖图、语义引用、隔离worktree、多类工程检查器、外部引擎、REA执行及桌面/手机配对继续按后续阶段建设。
|
||||
|
||||
## 直接运行
|
||||
|
||||
@@ -24,12 +24,13 @@ Windows x64 便携包自带 Node.js 24.22.1和npm。解压后双击 `Start-Workb
|
||||
1. 打开自带示例项目,或点击项目栏的「+」输入本机项目文件夹路径。
|
||||
2. 输入任务并发送。默认「离线演示」使用固定脚本调用真实本地工具,不进行模型推理。
|
||||
3. 终端请求会显示完整命令、用途和工作目录,确认后才运行。
|
||||
4. 文件建议先成为提案;查看右侧差异,点击「应用这项改动」才写入项目。
|
||||
4. 文件建议先成为提案。跨文件改动在「改动」面板选择「组合审查」,封存并查看整批差异,再确认应用全部文件;模型也可准备批次。独立提案仍可逐项审核,已封存提案通过批次处理。
|
||||
5. 点击「模型连接」,选择兼容模型服务,填写接口根地址、模型和按需填写的 Key;可先「验证模型响应」,再保存连接。
|
||||
6. 遇到请求失败,点击错误卡片的「查看运行诊断」。可在同一会话提问,助手通过本地 `inspect_session` 核对错误来源、近期工具和文件实际状态。
|
||||
7. 点击「查看任务记录」查看目标、各轮运行、累计用量与工件。准备工程检查后,核对npm脚本再执行;查看实际测试数量与日志。应用全部提案后,用「继续检查与交付」继续同一目标。
|
||||
8. 检查通过后,在任务记录中「预览Git提交」,核对已审核路径、差异、署名和说明,再「确认创建本地提交」。工作台保留其他暂存与工作区改动,结果未知时提供「核对提交结果」;报告可直接查看和下载。Git需要本机安装,具体范围见[Git交付契约](docs/GIT-DELIVERY.md)。
|
||||
9. 右侧「索引」按函数、类、路径或导入查找代码,结果可定位原文件行。文件在索引后变化时打开当前内容并提示刷新;Python声明候选与局部模块文件候选显示各自范围。长文件差异可直接「定位首处改动」。
|
||||
10. 批次中断或部分失败时,在所属任务打开「审查变更集」,先核对实际文件,再按当前哈希回退或明确保留外部内容。结果待核对期间同项目的新运行、写入、检查与提交会暂停。
|
||||
|
||||
## 模型连接
|
||||
|
||||
@@ -77,7 +78,7 @@ npm.cmd test
|
||||
|
||||
启动构建结果可运行 `npm.cmd start` 或双击启动脚本。前端开发使用 `npm.cmd run dev`,另开终端运行构建后的本地服务。
|
||||
|
||||
UI 验收先启动独立测试服务(指定不同数据目录),然后依次运行 `npm.cmd run verify:ui`、`npm.cmd run verify:diagnostics`和`node scripts/verify-execution-ui.mjs`。脚本默认检查 `http://127.0.0.1:4319`,使用本机 Edge;可用 `AGENT_WORKBENCH_URL` 指定其他独立测试地址。验证器要求测试服务为离线演示且未配置 Key,防止覆盖用户连接。它会创建工作区内的 `.qa` 测试项目。
|
||||
UI 验收先启动独立测试服务,依次运行基础、诊断、任务、Git交付和索引脚本;`node scripts/verify-change-sets-ui.mjs`自行启动独立批次宿主。默认地址为 `http://127.0.0.1:4319`,索引脚本需用 `AGENT_WORKBENCH_URL` 明确指定独立端口。验证器使用本机Edge、离线演示和未配置Key的宿主,在 `.qa` 创建自有项目。真实模型批次样本使用 `node scripts/verify-live-delivery.mjs --batch`,具体证据见[验收记录](docs/VALIDATION.md)。
|
||||
|
||||
```powershell
|
||||
$env:AGENT_WORKBENCH_DATA_DIR = Join-Path (Get-Location) '.qa\browser-data'
|
||||
|
||||
@@ -19,7 +19,13 @@
|
||||
|
||||
ProjectInspector识别有界工程文件、语言、规则、npm脚本及当前工程自身的Git基线。CheckRunner将脚本和源码指纹固定为plan;执行前再次核对,在用户确认后创建独立job,保留真实退出码、统计与日志工件。模型通过read_artifact读取已有失败信息。没有实际测试、日志不能识别或源码已变化时,verification不记通过。
|
||||
|
||||
应用提案使原Run保留needs_review历史,当前会话的文件状态更新。continue-reviewed仅在当前Task已有应用且无剩余提案/冲突时接受,先校验模型配置,再将review-action追加要求与新Run一同提交;保留原始目标、累计用量和resumeOf。普通completed的resume不会重新调用模型。
|
||||
应用提案后原Run保留needs_review或明确step_limit暂停历史。continue-reviewed要求当前Task已有应用、无剩余提案/冲突/未知工具,只接续这两种状态;先校验模型配置,再将review-action与新Run一同提交,保留原始目标、用量和resumeOf。主动取消、其他预算和重启暂停通过各自恢复入口处理。
|
||||
|
||||
## 多文件变更集
|
||||
|
||||
1.4.0的ChangeSetManager把同Task提案、Git基线和原/新字节快照封存为带SHA256指纹的记录。写入前全批预检,逐文件持久保存意图、同步暂存文件、同目录替换和实际结果;结果未知时启动只标状态,用户显式核对或回退。外部编辑内容按当前哈希保护,临时恢复文件只有类型/大小/哈希一致时复用;详见[恢复契约](CHANGE-SETS.md)。
|
||||
|
||||
模型只准备批次,文件应用/回退由独立审查动作执行。运行、检查、Git和旧逐项应用共享项目互斥与未核对批次检查,界面不能绕过服务端规则。报告记录批次身份/指纹/状态并核对快照完整性。
|
||||
|
||||
## 上下文
|
||||
完整会话仍保留在磁盘。模型请求使用有预算的投影:以完整 user/assistant/tool 组为单位保留近期内容,较早内容形成有长度限制的本地提要。计数为估算,服务返回的 usage 另外记录。该机制是本产品的独立提取式实现,不声称与 Claude Code 的模型摘要等价。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Agent Workbench 能力目标与验收矩阵
|
||||
|
||||
日期:2026-10-29。1.0.0为基础里程碑,1.1.0实现M1,1.2.0实现首个内置Git交付切片,1.3.0增加工程索引和精确补丁。下表保留1.0.0缺口与完整产品目标;每项完成范围以实际验证记录为准。
|
||||
日期:2026-10-29。1.0.0为基础里程碑,1.1.0实现M1,1.2.0增加内置Git交付,1.3.0增加工程索引和精确补丁,1.4.0增加可恢复多文件变更集。下表保留1.0.0缺口与完整产品目标;每项完成范围以实际验证记录为准。
|
||||
|
||||
总体方案见 [PRODUCT-PLAN.md](PRODUCT-PLAN.md),研究问题与来源见 [RESEARCH-ROADMAP.md](RESEARCH-ROADMAP.md)。
|
||||
|
||||
@@ -35,7 +35,14 @@
|
||||
- C07/C23:只读Git检查禁用配置过滤脚本,统一清单排除依赖/凭据/链接;索引范围、格式、Unicode、项目切换、原文件行定位、工件恢复和API契约有实际检查。
|
||||
- 完整112项行为/API/实际退出检查通过,新索引UI8组通过;源码/发行与真实模型工程验收以[验收记录](VALIDATION.md)为准。详见[索引与补丁契约](CODE-INDEX-AND-PATCHES.md)。React/Python真实工程交付、worktree和完整M2/M6仍继续实施。
|
||||
|
||||
| ID / 能力 | 当前1.0.0基础与缺口 | 后续产品目标 | 参考问题 / 模块 / 阶段 | 必须看到的验收证据 |
|
||||
### 1.4.0 M2多文件审查与恢复切片
|
||||
|
||||
- C08:同Task的1–32份提案封存指纹、Git与全部文件预检、原/新字节SHA256快照及整批审查;现阶段包含文本创建/修改,改名/删除与隔离worktree后续实现。
|
||||
- C02/C07:逐文件意图/结果持久保存、真实退出后的显式核对/回退、外部内容和冲突暂存文件保护;未知结果不自动重放并阻止同项目继续写入。
|
||||
- C04/C12:轮次上限后整批应用可继续原Task检查,其他停止原因保持原要求;切换项目清理临时错误提示、忽略过期批次响应。
|
||||
- C13/C23:Git报告引用封存身份/指纹/实际状态与快照校验,桌面/390px整批确认及恢复入口。实际回归、包与真实模型结果见[QA-1.4](QA-1.4.md)。完整M2三类工程、M3引擎与M5桌面/配对尚待完成。
|
||||
|
||||
| ID / 能力 | 1.0.0基础与缺口 | 后续产品目标 | 参考问题 / 模块 / 阶段 | 必须看到的验收证据 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| C01 需求与任务规划 | 有对话和有限步数工具循环,没有任务依赖图 | 固定目标、约束和完成标准;拆任务、判断依赖、接收追加要求与重规划 | CX-1、WB-1 / tasks / M1–M2 | 追加要求后仍保留原目标;任务完成由验收条件决定 |
|
||||
| C02 执行状态与恢复 | 会话JSON保存,active/waiters在内存;重启不重放命令 | 独立Task/Run/Step身份、持久事件、检查点与未知结果核对 | CC-2、CU-1、DS-1 / storage、tasks / M1 | 在审批、调用、结果与落盘等切点中断;恢复不重复已完成副作用 |
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# 多文件变更集与恢复契约
|
||||
|
||||
1.4.0开发中的M2切片。变更集把同Task的1–32份文本提案封存为一次审查;总原文和建议内容最多4MB。每个实际路径只能出现一次,拒绝文件/目录重叠、链接及Windows路径别名。源码文件的原字节和建议字节分别核对SHA256,保留文件格式和普通权限。
|
||||
1.4.0的M2切片。变更集把同Task的1–32份文本提案封存为一次审查;总原文和建议内容最多4MB。每个实际路径只能出现一次,拒绝文件/目录重叠、链接及Windows路径别名。源码文件的原字节和建议字节分别核对SHA256,保留文件格式和普通权限。
|
||||
|
||||
准备操作保存Task/Run、项目真实根目录、只读Git HEAD/分支、原/新文件哈希及内容快照工件;不写项目。界面按实际差异审核后,将同一个封存指纹提交给应用接口。模型只有准备工具,没有应用或回退工具。已封存的提案不能绕过批次单独应用;撤销未执行批次后可重新准备或逐项审查。
|
||||
|
||||
@@ -14,4 +14,4 @@
|
||||
|
||||
结果未核对时阻止同项目新运行、文件应用、检查和Git提交,恢复入口保留所属会话/Task。完成或回退都会使旧检查过期;交付报告引用批次身份、指纹和实际状态。历史批次可查看与核对,普通已完成批次回退仅作用于当前Task且核对封存指纹和当前文件哈希。
|
||||
|
||||
验收包含:整批预检冲突零写入、BOM/CRLF及权限保留、新文件、重复路径/祖先路径/链接、快照损坏、重复请求、同项目隔离、失败回退、owner修改保护,以及准备/写入意图/替换/逐项保存/回退/最终保存的真实进程退出。具体结果完成后登记,当前文档不代替测试证据。
|
||||
验收包含:整批预检冲突零写入、BOM/CRLF及权限保留、新文件、重复路径/祖先路径/链接、快照损坏、重复请求、同项目隔离、失败回退、owner修改保护,以及准备/写入意图/替换/逐项保存/回退/最终保存的真实进程退出。轮次上限后应用整批文件可继续原Task实际检查,其他暂停和未知工具结果不能借此继续。实际结果见[QA-1.4](QA-1.4.md),本文定义契约,不代替测试证据。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Agent Workbench 后续产品与执行开发方案
|
||||
|
||||
日期:2026-10-29。本文保留完整产品规划;1.1.0已实现M1,1.2.0已实现M2的当前Task本地Git交付及证据报告切片。具体已实现范围见[能力矩阵](CAPABILITIES.md),其余阶段与完整验收目标继续实施。
|
||||
日期:2026-10-29。本文保留完整产品规划;1.1.0实现M1,1.2.0增加Task本地Git交付,1.3.0增加索引与精确补丁,1.4.0增加可恢复多文件变更集。实际实现、验收与部署分别见[能力矩阵](CAPABILITIES.md)及[验证记录](VALIDATION.md),完整阶段目标继续实施。
|
||||
|
||||
## 1. 产品目标
|
||||
|
||||
@@ -27,9 +27,9 @@ Purge的源码机制不证明模型权重或工程成功率已经提升。增强
|
||||
|
||||
## 3. 当前基础与关键缺口
|
||||
|
||||
现有基础:React工作台、兼容模型连接、6个固定工具、单文件提案及基线检查、逐条命令确认、中文UTF-8、分类错误、会话保存/恢复、诊断和浏览器重连。34项行为测试、19组UI及真实模型原会话诊断已通过。
|
||||
现有基础:React工作台、兼容模型连接、Task/Run/Tool及预算、SQLite/工件恢复、工程索引与精确补丁、npm实际检查、单文件/整批审核、Git和报告。1.4.0增加原/新字节快照和逐文件执行账本、整批预检及显式恢复;各版本实测证据单独登记。
|
||||
|
||||
当前边界:JSON整段会话存储,active/waiters仍在内存;没有独立任务图、工程索引、长期项目记忆、精确patch、多文件ChangeSet、结构化测试修复、用户工程Git/worktree、REA/MCP工具注册、多worker或桌面壳。模型为一个全局连接且stream:false。
|
||||
当前边界:尚无任务依赖图、长期项目记忆、隔离worktree、多worker、React/Python专用检查与完整三类工程验收、动态REA/MCP/外部引擎注册、桌面壳或手机配对。批次支持文本创建/修改,不提供跨文件原子事务。模型仍使用一个全局连接且stream:false。
|
||||
|
||||
本次已为工作台源码建立本地Git,基线提交为`bac87da`,标签`v1.0.0-baseline`。这是开发仓库的版本管理;让用户在工作台中管理其工程的Git,是后续独立能力。
|
||||
|
||||
@@ -144,8 +144,8 @@ Purge的包声明Apache-2.0,另有商业许可联系说明;Harness声明MIT
|
||||
|
||||
## 9. 下一轮最先执行的三个开发切片
|
||||
|
||||
1. 1.1.0的Task/Run/工件/SQLite及1.2.0的检查/Git/report切片已交付;1.3.0继续完成工程索引和精确补丁,按独立包与长文件真实模型验收发布。
|
||||
2. 下一批实现多文件ChangeSet与可恢复应用、任务工作区/worktree隔离,再完成React/TypeScript及Python专用检查与封存任务;当前单Node样本不计为三类工程完成。
|
||||
1. 完成1.4.0变更集的全回归、独立发行及真实模型整批精确补丁验收,保留原进程/模型连接升级。测试和编译的代码与最终发行逐字节核对。
|
||||
2. 下一批实现任务工作区/worktree隔离,再完成React/TypeScript及Python专用检查与封存任务;当前单Node样本不计为三类工程完成。随后对同题任务验证有界上下文投影,实际统计费用与质量。
|
||||
3. 在写入/取消/事件归属边界稳定后按M3接入REA及Codex/DeepSeek EngineAdapter的契约探针,分别固定Harness/Purge/profile版本,再比较真实同题工程收益。桌面Electron与手机配对网关复用同一执行宿主,按M5推进。
|
||||
|
||||
这些切片优先复用已验证的文件范围、基线备份、UTF-8、取消与诊断能力。研究结论每次至少绑定一个实现模块、一个契约检查和一个用户场景,按实际失败分类持续调整顺序。
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# 1.4.0多文件变更集验收
|
||||
|
||||
本轮实现同Task的文本创建/修改批次、原/新字节快照、全批预检、逐文件持久账本与显式恢复,接入真实检查、Git和证据报告。文件系统不提供跨文件原子事务,部分执行或外部变化保持明确状态;worktree、改名/删除、多类工程和外部引擎继续实施。
|
||||
|
||||
| 用户可见行为 | 实际核对 | 当前证据 |
|
||||
| --- | --- | --- |
|
||||
| 一次审查覆盖整批文件 | 1–32文件、Task/Run、Git基线与封存指纹 | 原/新快照SHA256、整批差异及已封存逐项入口拒绝 |
|
||||
| 最后一个文件冲突也不写入 | 所有文件在第一处写入前预检 | 真实owner冲突、0文件写入 |
|
||||
| 中断结果能核对与回退 | 13个实际进程退出切点 | 不自动重放,按哈希恢复、保护外部字节与冲突暂存文件 |
|
||||
| 应用后继续原任务 | 真实step_limit封存→应用→继续 | 同Task新Run、实际2项测试、已完成工具结果保留 |
|
||||
| 暂停与未知结果不混用 | 主动取消、其他预算、restart与未知命令 | 此审核入口拒绝,不新增Run或写文件 |
|
||||
| 项目与提示保持归属 | 延迟批次响应、切换项目 | 旧响应忽略,临时提示清理,持久错误和恢复记录保留 |
|
||||
| 桌面与390px可审查恢复 | 11组批次流程及43组原界面 | 全部通过,0页面/请求异常,最终手机截图目视核对 |
|
||||
|
||||
完整141项行为/API/进程退出/升级回归全部通过,0失败/跳过/取消;54组真实界面流程全部通过。批次界面见[m2-batch-ui-validation.json](m2-batch-ui-validation.json),源码回归见[m2-batch-tests-validation.json](m2-batch-tests-validation.json)。原有界面结果为[基础](m2-batch-basic-ui-validation.json)、[诊断](m2-batch-diagnostics-ui-validation.json)、[任务](m2-batch-execution-ui-validation.json)、[Git](m2-batch-delivery-ui-validation.json)和[索引](m2-batch-index-ui-validation.json)。
|
||||
|
||||
初始验证曾出现受控HTTP fixture的5秒等待耗尽、部分配置请求被完整配置契约拒绝、UI辅助脚本点击收起后的按钮及证据文件命名不一致。分别修正时间窗口、fixture请求、可见入口和收集器;没有改变产品重试或绕过检查。另一个迟到失败用例先真实复现卸载组件向新项目弹错,再增加作用域清理并通过复验。源码包与真实模型结果以[VALIDATION](VALIDATION.md)为准,正式服务在包验收完成前保持1.3.0。
|
||||
+6
-6
@@ -1,16 +1,16 @@
|
||||
# 升级到 1.2.0并保留原连接
|
||||
# 升级到 1.4.0并保留原连接
|
||||
|
||||
升级脚本在原Node进程中替换工作台实现,保留现有内存连接对象、项目和会话。它不会读取、打印、导出或复制API Key。普通停止后重启会丢失仅在内存中的Key,需要重新填写。
|
||||
|
||||
## 升级条件
|
||||
|
||||
使用已完成构建的1.2.0便携包,保留原启动发行目录及当前实现目录。工作台中的任务、工程检查、Git交付和命令审批均已结束,当前本地9229端口可用。脚本接受127.0.0.1上的0.1.0、1.0.0、1.1.0或1.2.0工作台,先核对进程PID和原发行路径,再迁移对象。升级后校验配置、项目、会话和PID,并关闭本次开启的调试端口。控制请求使用独立HTTP连接,避免调试暂停后复用超时连接。
|
||||
使用已经验收的1.4.0便携包,保留原启动目录和当前实现目录,使用新的独立发行目录。工作台的任务、检查、Git、文件批次和审批没有活动执行,本地9229端口可用。脚本接受127.0.0.1上的0.1.0及1.0.0–1.4.0工作台,先核对PID和原发行路径,再迁移对象。升级后校验公开配置、项目、会话和PID,并关闭本次开启的调试端口。控制请求使用独立HTTP连接。
|
||||
|
||||
首次从旧JSON版本进入SQLite时,数据在保留原字节备份的事务中迁移,旧历史以legacy-import标明来源。已有SQLite实例保留原状态与Map并补齐新增Git记录类型。随附npm位于新发行runtime,原进程保留原Node可执行路径并使用新npm检查器。
|
||||
首次从旧JSON进入SQLite时,在保留原字节备份的事务中迁移,旧历史以legacy-import标明来源。已有SQLite实例保留原状态与Map,并补齐新增Git和change_set类型。1.4.0给旧会话增加空的execution.changeSets数组,原字段和实际批次记录保留。随附npm位于新发行runtime,原进程保留原Node可执行路径并使用新npm检查器。
|
||||
|
||||
## 执行
|
||||
|
||||
在解压后的1.2.0便携目录打开PowerShell。使用service-info保存的原启动目录,数据目录沿用当前启动配置;此前已经热升级的实例另传当前handler目录。
|
||||
在解压后的1.4.0便携目录打开PowerShell。使用service-info保存的原启动目录,数据目录沿用当前启动配置;此前已热升级的实例另传当前handler目录。运行中的发行目录保持不变,后续打包创建新的时间戳目录。
|
||||
|
||||
```powershell
|
||||
$awNewRoot = (Get-Location).Path
|
||||
@@ -20,9 +20,9 @@ if ($awServiceInfo.runtimeRoot) { $awUpgradeArguments += @('--handler-root', $aw
|
||||
& (Join-Path $awNewRoot 'runtime\node.exe') @awUpgradeArguments
|
||||
```
|
||||
|
||||
成功后访问 `http://127.0.0.1:4318/?release=1.2.0`,界面显示v1.2.0。任务记录可查看工程检查、Git预览、提交与交付报告;已有项目路径继续指向原项目,不移动用户文件。
|
||||
成功后访问 `http://127.0.0.1:4318/?release=1.4.0`,界面显示v1.4.0。「改动」面板可审查整批文件与恢复结果,任务记录可查看工程检查、Git及交付报告;已有项目继续指向原目录。
|
||||
|
||||
`service-info.json`保留原启动目录,并更新当前实现目录`runtimeRoot`与版本。再次运行启动器会复用当前本地服务;以后需要重启时,从1.2.0目录启动。
|
||||
`service-info.json`保留原启动目录,并更新当前实现目录`runtimeRoot`与版本。再次运行启动器会复用当前本地服务;以后需要重启时,从最终1.4.0目录启动。
|
||||
|
||||
## 验证范围
|
||||
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
# Agent Workbench 验收记录
|
||||
|
||||
## 1.4.0 · 多文件审查与恢复
|
||||
|
||||
Windows x64、Node24.22.1。构建与141/141项行为/API/实际进程退出/升级回归通过,0失败/跳过/取消;批次11及原有43共54组真实界面流程全部通过,0页面/请求异常。桌面及390px审查/回退截图已目视核对。
|
||||
|
||||
| 验证 | 当前结果 | 证据 |
|
||||
| --- | --- | --- |
|
||||
| 封存指纹/原新快照/全批预检/逐文件恢复和原有契约 | 141/141通过,包含13个批次实际退出切点 | [完整回归](m2-batch-tests-validation.json) |
|
||||
| 批次审查/恢复/step_limit续接/迟到错误归属 | 11/11通过 | [批次界面](m2-batch-ui-validation.json) |
|
||||
| 基础/诊断/任务/Git/索引 | 10/9/7/9/8全部通过 | [QA-1.4](QA-1.4.md) |
|
||||
| 独立便携、源码、原进程升级和真实模型 | 正在进行发行与真实工程验收 | 结果完成后记录 |
|
||||
|
||||
迟到失败用例先复现卸载后的旧组件向新项目弹错,再修复作用域清理并通过复验。多文件写入没有跨文件原子事务;结果未知时只显式核对/回退,不自动重放。完整M2的worktree、多类工程及M3/M5继续实施,当前正式服务在包验收完成前保留1.3.0原进程和连接。
|
||||
|
||||
## 1.3.0 · 工程索引与精确补丁
|
||||
|
||||
Windows x64、Node24.22.1、Edge156.0.4314.42。构建和112/112项行为/API/实际进程退出与连续升级检查通过,0失败/跳过/取消。基础10、诊断9、任务7、Git交付9和索引8共43组真实界面流程全部通过,页面/请求异常为零;桌面与390px截图已目视核对。
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"success": true,
|
||||
"url": "http://127.0.0.1:59261",
|
||||
"browser": "Microsoft Edge 156.0.4314.42",
|
||||
"date": "2026-10-29T11:21:57.842Z",
|
||||
"projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\ui-9eceec8c-3206-4e6a-ad8a-3ecd586af2d0\\ui-project",
|
||||
"viewports": [
|
||||
1440,
|
||||
780,
|
||||
390
|
||||
],
|
||||
"passed": [
|
||||
"project selection and real file preview",
|
||||
"real command consent, execution and stale snapshot rejection",
|
||||
"diff review and verified file application",
|
||||
"manual editor creates a reviewable proposal",
|
||||
"file responses stay with the current selection",
|
||||
"denial, session selection, reload, stale response rejection and export",
|
||||
"project inventory responses cannot replace another project",
|
||||
"780 and 390 px: project drawer, file, diff and trace controls, no page overflow",
|
||||
"unified and detailed research reports render",
|
||||
"model list, ephemeral key, compatible fixture tool loop and return to offline mode"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"modelValidation": "controlled local HTTP fixture; no real model",
|
||||
"releaseVersion": "1.4.0"
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"success": true,
|
||||
"version": "1.4.0",
|
||||
"testedAt": "2026-10-29T11:23:02.797Z",
|
||||
"browser": "156.0.4314.42",
|
||||
"passed": [
|
||||
"actual failing tests and four source proposals retain the original project and task",
|
||||
"reviewed changes continue the same Task through 14 real tests and model-prepared Git review",
|
||||
"review shows actual paths, diffs, tests, author and policy; cancelling leaves Git unchanged",
|
||||
"an index change after confirmation preview refuses the stale job and preserves both staged owners",
|
||||
"390px confirmation keeps file hashes, diffs and actions inside the modal",
|
||||
"double confirmation creates one four-file commit, retains owner bytes and publishes report with completion",
|
||||
"report viewing and Markdown/JSON downloads preserve verified artifact bytes and truthful acceptance limits",
|
||||
"mobile report preview closes cleanly and keeps the task input fixed",
|
||||
"unknown Git results block new submission and the explicit reconcile action restores the existing commit"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\delivery-ui-dd305133-a668-413c-9fa6-262fe0ff75f5\\四模块交付工程",
|
||||
"projectId": "9d5df4e6-cd1b-4a84-8e1f-2b5194d826c8",
|
||||
"sessionId": "5705c193-b058-4c7d-a03f-6d91ee44723b",
|
||||
"taskId": "ec474760-06b8-4c74-a0e1-330ef2465647",
|
||||
"commit": "512c9e4b88b16cc37f3f3d38c71c3a7b267da80a",
|
||||
"recoveryCommit": "bee6a0ae81dbdaf605be182ce6b26ad4f52e7977",
|
||||
"testCounts": {
|
||||
"baselineFailed": 13,
|
||||
"passed": 14
|
||||
},
|
||||
"model": "controlled local HTTP fixture",
|
||||
"confirmations": 2,
|
||||
"releaseVersion": "1.4.0"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"success": true,
|
||||
"version": "1.4.0",
|
||||
"url": "http://127.0.0.1:59261",
|
||||
"date": "2026-10-29T11:22:12.381Z",
|
||||
"passed": [
|
||||
"model response validation checks the tentative connection before saving",
|
||||
"a model failure after successful tools shows source, attempts and local runtime diagnosis",
|
||||
"explicit retry preserves the completed tool result without replaying the task",
|
||||
"an error question receives the actual session diagnosis and formatted answer",
|
||||
"review state exposes the review action and prevents application during a running request",
|
||||
"approved Unicode commands execute in the declared shell and retain Chinese output",
|
||||
"authentication errors do not retry and error/diagnostic controls fit a 390 px viewport",
|
||||
"stop cancels pending retry and clears running model state",
|
||||
"a transient service failure recovers within the bounded retry policy"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"modelValidation": "controlled local HTTP fixture; actual configured model is verified separately",
|
||||
"releaseVersion": "1.4.0"
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"success": true,
|
||||
"version": "1.4.0",
|
||||
"testedAt": "2026-10-29T11:22:31.573Z",
|
||||
"browser": "156.0.4314.42",
|
||||
"passed": [
|
||||
"model-selected checks wait for approval and display actual counted results",
|
||||
"verified artifact preview shows the real check log and hash",
|
||||
"changed source invalidates old checks and manual confirmation runs the new plan",
|
||||
"390px task drawer, log preview, close controls and fixed composer remain operable",
|
||||
"reconnection synchronizes missed session changes in other projects",
|
||||
"budget controls pause before tools and preserve the goal across recorded runs",
|
||||
"applied proposals continue the original task into actual engineering verification"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\execution-ui-1b835c75-f577-4d45-a0c7-294367f1504a\\project",
|
||||
"model": "controlled local HTTP fixture",
|
||||
"releaseVersion": "1.4.0"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"checkedAt": "2026-10-29T11:23:07.975Z",
|
||||
"version": "1.4.0",
|
||||
"passed": [
|
||||
"工程索引可独立于任务使用,实际覆盖范围与损坏文件显示明确",
|
||||
"真实AST查询打开原文件第181行并仅滚动代码容器,输入区和顶部保持可见",
|
||||
"查询词保留;过期SHA不高亮旧位置,增量刷新后正确定位第184行",
|
||||
"切换项目时延迟返回的旧索引不覆盖新项目结果",
|
||||
"Python候选、字符串误报排除和局部导入文件候选保留真实证据标签",
|
||||
"两处唯一锚点成为待审核提案,真实界面应用后BOM/CRLF和未选择原字节保留",
|
||||
"390px索引查询、范围和完整指纹可读且无横向溢出,实际文件行定位通过",
|
||||
"索引刷新失败保留归属和解释,旧结果禁用并可重试恢复"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\index-ui-9723a996-fd81-4593-a0ff-a8d50b1fb4ed",
|
||||
"primaryProjectId": "a7454105-512a-4bc0-bdb6-6fe9487abff1",
|
||||
"otherProjectId": "2d8f63d3-3786-4b94-b776-211f013bdae5",
|
||||
"success": true,
|
||||
"releaseVersion": "1.4.0"
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"success": true,
|
||||
"version": "1.4.0",
|
||||
"testedAt": "2026-10-29T11:26:37.687Z",
|
||||
"node": "v24.22.1",
|
||||
"fileConcurrency": 4,
|
||||
"durationMs": 186158,
|
||||
"tests": {
|
||||
"tests": 141,
|
||||
"pass": 141,
|
||||
"fail": 0,
|
||||
"cancelled": 0,
|
||||
"skipped": 0,
|
||||
"todo": 0
|
||||
},
|
||||
"log": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\tests-1.4.log",
|
||||
"failures": [],
|
||||
"scope": "Complete behavior/API/process-exit/upgrade regression; isolated synthetic model fixtures only."
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"success": true,
|
||||
"version": "1.4.0",
|
||||
"testedAt": "2026-10-29T11:30:15.302Z",
|
||||
"cases": [
|
||||
"Desktop batch scope, per-file diffs, sealed single-write guard and pre-apply bytes",
|
||||
"Three-file reviewed application preserves exact BOM/CRLF/LF and creates the new file",
|
||||
"Explicit batch rollback restores exact originals and removes only the reviewed new file",
|
||||
"A last-file owner conflict blocks the whole batch and shows the real recovery direction",
|
||||
"Durable partial recovery reads actual hashes and preserves owner content during rollback",
|
||||
"Changed observation fingerprints reject stale acknowledgement without releasing the project",
|
||||
"Explicit owner-content acknowledgement ends recovery without claiming successful application",
|
||||
"Switching projects clears the previous task notification while retaining its durable error and recovery history",
|
||||
"390px step-limit review, same-task continuation entry, rollback confirmation and keyboard close fit the viewport",
|
||||
"A delayed preparation response never opens a different project or changes its selected session",
|
||||
"A failed batch response after its component unmounts cannot display an error in the newly selected project"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"screenshots": [
|
||||
".qa/screenshots/1.4-batch-desktop-review.png",
|
||||
".qa/screenshots/1.4-batch-desktop-conflict.png",
|
||||
".qa/screenshots/1.4-batch-desktop-recovery.png",
|
||||
".qa/screenshots/1.4-batch-mobile-review.png",
|
||||
".qa/screenshots/1.4-batch-mobile-rollback.png"
|
||||
],
|
||||
"projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\batch-ui-b2636260-4373-4120-a082-eb3cd8d64e91",
|
||||
"scope": "Real independent demo host and durable batch states; UI fixtures include actual owner conflict/rollback results. No real model credentials or user project were used."
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 160 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 154 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 145 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 67 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 72 KiB |
+11
@@ -160,3 +160,14 @@ Claude Code 报告已验证工具输入校验、权限决定、队列并发屏
|
||||
- ChangeSet先完成显式核对/按哈希回退;新文件空父目录可保留,不递归删除。文件系统没有跨文件事务或通用外部编辑器锁,报告区分completed、rolled_back及unknown/partial。
|
||||
- 首轮22项专项21通过/1失败:实际进程在restore_staged退出留下了原字节临时文件,后续wx创建冲突阻挡回退。改为校验本批次临时文件类型/大小/SHA并复用原字节,不删除或覆盖不匹配文件;补充临时文件owner保护与跨Run同Task提案专项。
|
||||
- 实现补丁两次使用长单行的前缀作为完整上下文导致校验失败;改为完整独立行锚点,不重复失效匹配。未应用的补丁没有改变运行服务。
|
||||
- API首轮2/3通过,模型工具用例误用了fixture.url及completion参数形状;核对helpers后使用baseUrl和calls/content契约,单项复验后再进入完整回归,产品连接实现不因测试脚本问题修改。
|
||||
- 完整139项首轮138通过/1失败:新模型批次fixture单独3.8秒通过,默认全文件并发时其8秒等待窗口耗尽。该用例改为30秒阶段等待/60秒总上限;最终QA采用4份文件并发,仍覆盖原有明确的API并发/竞态用例。失败不记为产品验证通过。
|
||||
- 批次UI首轮7组桌面应用/冲突/恢复通过,390px选择项目后产品已自动关闭侧栏,测试仍点击隐藏的收起按钮而超时。helper改为核对实际可见状态后操作;继续窄屏及延迟旧响应流程。
|
||||
- 基础UI前9组通过,末项兼容HTTP fixture在完整测试并发时第三轮尚未结束,5秒断言耗尽;独立QA需要先停止自有fixture并恢复demo,末项改20秒再顺序回归,未改产品连接重试逻辑。
|
||||
- 模型在prepare_change_set后到达工具轮次上限会留下paused/step_limit;整批应用后session completed而原Run仍paused。审核续接仅补这个明确状态,并拒绝Task中仍需核对的工具结果;主动取消、其他预算及重启暂停不从此入口继续。
|
||||
- 首轮新增续接API与QA刷新使用部分config请求,完整配置契约在URL校验时拒绝且无写入;改为只在独立fixture上合并公开配置字段。未知工具及其他暂停拒绝用例首轮通过,续接用例改正请求后复验。
|
||||
- 修正后批次API5/5通过,新增用例实际执行2个测试、保留原Task与旧Run/tool结果且未重放;手机新增Escape后检查续接入口通过,但Escape同时收起检视区,再打开批次须先使用可见的“查看改动”入口,已校正UI脚本。
|
||||
- 手机目视验收暴露前一个项目的错误toast仍覆盖新项目的批次弹窗;切换项目/会话时清理临时提示,所属项目的持久事件/错误/恢复记录保留。增加真实切换验收,截图不再混入旧任务提示。
|
||||
- 五套UI实际流程43组均通过;收集器误用index-ui-validation.json且假定其success字段,索引脚本实际输出index-ui-result.json。修正证据读取契约,最后冻结前端后重新收集5套结果。
|
||||
- 最终新增的延迟失败用例真实复现:原ChangeSetPanel卸载后旧scopeRef仍匹配,旧请求catch向新项目弹出toast。组件卸载/作用域变更时作废原scope,并让文件刷新失败同样核对scope;新用例先失败再修复,不只验证成功响应。
|
||||
- 141项最终回归通过,批次UI11组和原有43组通过;末次文档补丁误用验收记录标题,校验拒绝且未修改文件,按实际标题更正后保存。
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "local-agent-workbench",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "local-agent-workbench",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"dependencies": {
|
||||
"@babel/parser": "7.29.11",
|
||||
"diff": "^8.0.2",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "local-agent-workbench",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
|
||||
|
||||
@@ -134,3 +134,6 @@
|
||||
- 最终包20261029101643317:2138份便携/283份源码清单、CRC与SHA通过,77份运行/测试/全部脚本和6份构建产物与已独立安装/112项验收源码逐字节一致;原PID23080更新保留全部6项目/7会话的消息、事件、提案和execution指纹。下一批进入同Task多文件变更集与可恢复应用。
|
||||
- 1.4.0封存变更集/原新字节快照/整批预检/逐文件意图和结果/显式核对回退/外部改动确认已实现。24/24专项通过,包含13个真实退出切点;首轮restore_staged失败修正为校验并复用原字节暂存文件。模型准备工具和API接入,继续统一审查界面与交付报告证据。
|
||||
- 相关原有文件/运行/存储/Git交付27/27回归与构建通过;保存多文件核心本地提交,继续界面与实际API验收。原4318仍运行已验证的最终1.3.0,不重启或读取内存Key。
|
||||
- 接续5d03af9:1.4未提交UI/API与139项完整回归、9组批次UI证据保留;普通UI末项时间窗口不足已记录。补齐step_limit批次应用后的同Task新Run续接和未知工具保护,重新验证后发行。
|
||||
- 续接修复的批次API5/5、批次UI10/10和原有基础10/诊断9/任务7/Git9/索引8全部通过;53组界面0页面/请求异常。两份最终390px截图已目视核对,旧项目toast清理后无覆盖;开始冻结源码的完整回归、包验证和真实模型批次交付。
|
||||
- 完整141/141回归通过;最终增加组件卸载后的迟到失败保护,用例先复现再修复,批次UI11/11及原有43组通过,共54组。源码构建已冻结,准备保存实现并进行独立发行/源码验收,原服务仍为1.3.0/PID23080。
|
||||
|
||||
@@ -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'].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'].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 = [];
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { chromium, expect } from 'playwright/test';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { batchFixture, assertBatchBytes } from '../tests/fixtures/change-set-project.mjs';
|
||||
|
||||
const root = path.resolve('.qa', 'batch-ui-' + randomUUID()), data = path.join(root, 'data'); fs.mkdirSync(root, { recursive: true });
|
||||
fs.mkdirSync('.qa/screenshots', { recursive: true });
|
||||
const store = new Store(data), cases = {};
|
||||
for (const name of ['normal', 'conflict', 'recovery', 'mobile', 'delayed']) {
|
||||
const projectRoot = path.join(root, 'batch-ui-' + name); fs.mkdirSync(projectRoot); fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Owned UI fixture\n');
|
||||
const project = store.addProject(projectRoot), session = store.createSession(project.id, '批次验收 ' + name), f = { projectRoot, project, session, store };
|
||||
const b = batchFixture(f, name === 'recovery' ? { faultInjector: (phase, set, index) => {
|
||||
if (phase === 'replaced' && index === 1) { fs.writeFileSync(path.join(projectRoot, 'src/one.mjs'), 'Owner recovery content\n'); throw new Error('Owned UI lost result'); }
|
||||
} } : {});
|
||||
cases[name] = { ...f, b };
|
||||
if (name === 'mobile') {
|
||||
const run = store.core.run.get(session.runId); session.status = 'paused'; store.finishRun(session, run, 'step_limit');
|
||||
}
|
||||
if (name === 'recovery' || name === 'mobile') {
|
||||
const set = await b.manager.prepare(session, b.ids);
|
||||
if (name === 'recovery') await (await b.manager.start(session, set.id, set.fingerprint)).promise;
|
||||
}
|
||||
}
|
||||
store.close();
|
||||
const env = { ...process.env, AGENT_WORKBENCH_APP_DIR: process.cwd(), AGENT_WORKBENCH_DATA_DIR: data, AGENT_WORKBENCH_PORT: '0' }; delete env.AGENT_WORKBENCH_API_KEY;
|
||||
const child = spawn(process.execPath, ['dist-server/server.mjs'], { cwd: process.cwd(), env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let output = '', errors = '', url = ''; child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8');
|
||||
child.stdout.on('data', value => { output += value; for (const line of output.split('\n')) { try { const item = JSON.parse(line); if (item.ready) url = item.url; } catch {} } });
|
||||
child.stderr.on('data', value => { errors += value; });
|
||||
const wait = async predicate => { const deadline = Date.now() + 15000; while (!await predicate()) { if (Date.now() > deadline) throw new Error('UI fixture timed out: ' + errors); await new Promise(resolve => setTimeout(resolve, 40)); } };
|
||||
await wait(() => url); const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
|
||||
assert.equal(bootstrap.version, '1.4.0'); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
|
||||
const api = async (route, input) => { const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST', headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token, Connection: 'close' },
|
||||
...(input === undefined ? {} : { body: JSON.stringify(input) }) }); const value = await response.json(); assert.ok(response.ok, value.error); return value; };
|
||||
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
const passed = [], pageErrors = [], requestFailures = [], screenshots = [];
|
||||
page.on('pageerror', error => pageErrors.push(error.message)); page.on('requestfailed', request => { if (request.resourceType() !== 'eventsource') requestFailures.push(request.failure()?.errorText); });
|
||||
const dialog = () => page.getByRole('dialog', { name: '多文件变更集审查', exact: true });
|
||||
const session = f => api('/sessions/' + f.session.id);
|
||||
const current = async f => (await session(f)).execution.changeSets.at(-1);
|
||||
async function choose(name) {
|
||||
const f = cases[name];
|
||||
if (!await page.locator('.project-sidebar').isVisible()) await page.getByRole('button', { name: '展开项目栏', exact: true }).click();
|
||||
await page.getByLabel('当前项目', { exact: true }).selectOption(f.project.id);
|
||||
await expect(page.locator('.session-item.selected')).toContainText('批次验收 ' + name);
|
||||
if ((await page.viewportSize()).width <= 940) {
|
||||
if (await page.locator('.project-sidebar').isVisible()) await page.getByRole('button', { name: '收起项目栏', exact: true }).click();
|
||||
await page.getByRole('button', { name: '查看改动', exact: true }).click();
|
||||
} else await page.locator('.inspector-tabs').getByRole('button', { name: /^改动/ }).click();
|
||||
await expect(page.locator('.changes-inspector')).toBeVisible(); return f;
|
||||
}
|
||||
async function seal() {
|
||||
await page.getByRole('button', { name: '组合审查', exact: true }).click();
|
||||
await page.getByRole('button', { name: '封存审查范围', exact: true }).click(); await expect(dialog()).toBeVisible();
|
||||
}
|
||||
async function viewport(name) {
|
||||
const bounds = await page.evaluate(() => {
|
||||
const modal = document.querySelector('[role="dialog"]'), close = modal?.querySelector('[aria-label="关闭窗口"]');
|
||||
const rect = modal?.getBoundingClientRect(), closeRect = close?.getBoundingClientRect();
|
||||
return { scrollY, width: innerWidth, height: innerHeight, scrollWidth: document.documentElement.scrollWidth, scrollHeight: document.documentElement.scrollHeight,
|
||||
modal: rect ? { top: rect.top, bottom: rect.bottom, width: rect.width, scrollWidth: modal.scrollWidth } : null,
|
||||
close: closeRect ? { top: closeRect.top, bottom: closeRect.bottom } : null };
|
||||
});
|
||||
assert.equal(bounds.scrollY, 0); assert.ok(bounds.scrollWidth <= bounds.width + 1 && bounds.scrollHeight <= bounds.height + 1, JSON.stringify(bounds));
|
||||
if (bounds.modal) assert.ok(bounds.modal.top >= 0 && bounds.modal.bottom <= bounds.height + 1 && bounds.modal.scrollWidth <= bounds.modal.width + 1 && bounds.close.bottom <= bounds.height, JSON.stringify(bounds));
|
||||
const destination = '.qa/screenshots/1.4-batch-' + name + '.png'; await page.screenshot({ path: destination, scale: 'css' }); screenshots.push(destination);
|
||||
}
|
||||
try {
|
||||
await page.goto(url, { waitUntil: 'networkidle' });
|
||||
let f = await choose('normal'); await seal();
|
||||
await expect(page.getByRole('button', { name: '应用这项改动', exact: true })).toBeDisabled();
|
||||
for (const relative of Object.keys(f.b.after)) { await dialog().getByRole('button', { name: '查看批次差异 ' + relative, exact: true }).click(); await expect(dialog().getByLabel('文件差异 ' + relative)).toBeVisible(); }
|
||||
assertBatchBytes(assert, f, f.b.before); await viewport('desktop-review'); passed.push('Desktop batch scope, per-file diffs, sealed single-write guard and pre-apply bytes');
|
||||
await dialog().getByRole('button', { name: '确认应用全部 3 项', exact: true }).click(); await wait(async () => (await current(f)).status === 'completed');
|
||||
assertBatchBytes(assert, f, f.b.after); await expect(dialog().getByText('整批文件的实际建议字节已核对,全部应用完成。')).toBeVisible(); passed.push('Three-file reviewed application preserves exact BOM/CRLF/LF and creates the new file');
|
||||
await dialog().getByRole('button', { name: '回退本批已写入文件', exact: true }).click(); await dialog().getByRole('button', { name: '确认回退本批次', exact: true }).click();
|
||||
await wait(async () => (await current(f)).status === 'rolled_back'); assertBatchBytes(assert, f, f.b.before); passed.push('Explicit batch rollback restores exact originals and removes only the reviewed new file');
|
||||
await dialog().getByRole('button', { name: '关闭窗口', exact: true }).click();
|
||||
f = await choose('conflict'); await seal(); fs.mkdirSync(path.join(f.projectRoot, 'docs')); fs.writeFileSync(path.join(f.projectRoot, 'docs/new.md'), 'Owner conflict\n');
|
||||
await dialog().getByRole('button', { name: '确认应用全部 3 项', exact: true }).click(); await wait(async () => (await current(f)).status === 'stale');
|
||||
assertBatchBytes(assert, f, { ...f.b.before, 'docs/new.md': Buffer.from('Owner conflict\n') });
|
||||
await expect(dialog().getByRole('button', { name: '确认应用全部 3 项', exact: true })).toHaveCount(0); await viewport('desktop-conflict'); passed.push('A last-file owner conflict blocks the whole batch and shows the real recovery direction');
|
||||
await dialog().getByRole('button', { name: '撤销未执行批次', exact: true }).click(); await dialog().getByRole('button', { name: '关闭窗口', exact: true }).click();
|
||||
f = await choose('recovery'); await page.getByRole('button', { name: '审查变更集', exact: true }).click();
|
||||
await dialog().getByRole('button', { name: '核对实际文件', exact: true }).click(); await expect(dialog().getByText('外部改动', { exact: true })).toBeVisible();
|
||||
await dialog().getByRole('button', { name: '回退本批已写入文件', exact: true }).click(); await dialog().getByRole('button', { name: '确认回退本批次', exact: true }).click();
|
||||
await expect(dialog().getByRole('button', { name: '保留外部改动,结束恢复', exact: true })).toBeEnabled(); await viewport('desktop-recovery'); passed.push('Durable partial recovery reads actual hashes and preserves owner content during rollback');
|
||||
await dialog().getByRole('button', { name: '保留外部改动,结束恢复', exact: true }).click(); fs.writeFileSync(path.join(f.projectRoot, 'src/one.mjs'), 'Owner changed after review\n');
|
||||
await dialog().getByRole('button', { name: '确认保留外部改动', exact: true }).click(); await expect(page.locator('.toast')).toContainText('当前文件变化');
|
||||
assert.equal((await current(f)).requiresVerification, true); passed.push('Changed observation fingerprints reject stale acknowledgement without releasing the project');
|
||||
await dialog().getByRole('button', { name: '返回审查', exact: true }).click(); await dialog().getByRole('button', { name: '核对实际文件', exact: true }).click();
|
||||
await dialog().getByRole('button', { name: '保留外部改动,结束恢复', exact: true }).click(); await dialog().getByRole('button', { name: '确认保留外部改动', exact: true }).click();
|
||||
await wait(async () => (await current(f)).status === 'resolved_external'); assert.equal(fs.readFileSync(path.join(f.projectRoot, 'src/one.mjs'), 'utf8'), 'Owner changed after review\n');
|
||||
passed.push('Explicit owner-content acknowledgement ends recovery without claiming successful application'); await dialog().getByRole('button', { name: '关闭窗口', exact: true }).click();
|
||||
await page.setViewportSize({ width: 390, height: 844 }); f = await choose('mobile');
|
||||
await expect(page.locator('.toast')).toHaveCount(0); passed.push('Switching projects clears the previous task notification while retaining its durable error and recovery history');
|
||||
await page.getByRole('button', { name: '审查变更集', exact: true }).click();
|
||||
await viewport('mobile-review'); await dialog().getByRole('button', { name: '确认应用全部 3 项', exact: true }).click(); await wait(async () => (await current(f)).status === 'completed');
|
||||
await page.keyboard.press('Escape'); await expect(page.getByRole('button', { name: '继续检查与交付', exact: true })).toBeVisible();
|
||||
if (!await page.locator('.changes-inspector').isVisible()) await page.getByRole('button', { name: '查看改动', exact: true }).click();
|
||||
await page.getByRole('button', { name: '审查变更集', exact: true }).click();
|
||||
await dialog().getByRole('button', { name: '回退本批已写入文件', exact: true }).click(); await viewport('mobile-rollback');
|
||||
await dialog().getByRole('button', { name: '确认回退本批次', exact: true }).click(); await wait(async () => (await current(f)).status === 'rolled_back'); assertBatchBytes(assert, f, f.b.before);
|
||||
await page.keyboard.press('Escape'); await expect(dialog()).toHaveCount(0); await expect(page.getByRole('button', { name: '继续检查与交付', exact: true })).toHaveCount(0);
|
||||
passed.push('390px step-limit review, same-task continuation entry, rollback confirmation and keyboard close fit the viewport');
|
||||
await page.setViewportSize({ width: 1440, height: 1000 }); f = await choose('delayed');
|
||||
let release, held = false; const gate = new Promise(resolve => { release = resolve; });
|
||||
await page.route('**/api/sessions/' + f.session.id + '/change-sets', async route => { held = true; await gate; await route.continue(); });
|
||||
await page.getByRole('button', { name: '组合审查', exact: true }).click(); await page.getByRole('button', { name: '封存审查范围', exact: true }).click(); await wait(() => held);
|
||||
await page.keyboard.press('Escape'); await choose('normal'); release(); await wait(async () => (await current(f))?.status === 'prepared');
|
||||
await expect(dialog()).toHaveCount(0); await expect(page.locator('.session-item.selected')).toContainText('批次验收 normal');
|
||||
const delayed = await current(f); await api('/sessions/' + f.session.id + '/change-sets/' + delayed.id + '/discard', { fingerprint: delayed.fingerprint });
|
||||
passed.push('A delayed preparation response never opens a different project or changes its selected session');
|
||||
f = await choose('delayed'); let failRelease, failureHeld = false;
|
||||
const failedGate = new Promise(resolve => { failRelease = resolve; }), failedUrl = '/api/sessions/' + f.session.id + '/change-sets';
|
||||
await page.route('**' + failedUrl, async route => { failureHeld = true; await failedGate; await route.fulfill({ status: 409, contentType: 'application/json', body: JSON.stringify({ error: '旧任务的延迟批次准备失败' }) }); });
|
||||
await page.getByRole('button', { name: '组合审查', exact: true }).click(); await page.getByRole('button', { name: '封存审查范围', exact: true }).click(); await wait(() => failureHeld);
|
||||
await page.keyboard.press('Escape'); await choose('normal');
|
||||
const failedResponse = page.waitForResponse(response => response.url().endsWith(failedUrl) && response.status() === 409);
|
||||
failRelease(); await (await failedResponse).finished();
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
await expect(page.locator('.toast')).toHaveCount(0); await expect(dialog()).toHaveCount(0); await expect(page.locator('.session-item.selected')).toContainText('批次验收 normal');
|
||||
passed.push('A failed batch response after its component unmounts cannot display an error in the newly selected project');
|
||||
assert.equal(pageErrors.length, 0, pageErrors.join('\n')); assert.equal(requestFailures.length, 0, requestFailures.join('\n'));
|
||||
const result = { success: true, version: '1.4.0', testedAt: new Date().toISOString(), cases: passed, pageErrors, requestFailures, screenshots, projectRoot: root,
|
||||
scope: 'Real independent demo host and durable batch states; UI fixtures include actual owner conflict/rollback results. No real model credentials or user project were used.' };
|
||||
fs.writeFileSync('docs/m2-batch-ui-validation.json', JSON.stringify(result, null, 2) + '\n'); console.log(JSON.stringify(result, null, 2));
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: '.qa/screenshots/1.4-batch-failure.png', scale: 'css' }); fs.writeFileSync('.qa/batch-ui-failure.json', JSON.stringify({ passed, message: error.message, pageErrors, requestFailures }, null, 2)); throw error;
|
||||
} finally {
|
||||
await browser.close(); try { await api('/shutdown', {}); await wait(() => child.exitCode !== null); } catch { if (child.exitCode === null) child.kill(); }
|
||||
}
|
||||
@@ -18,7 +18,7 @@ fs.writeFileSync(path.join(primaryRoot, 'broken.js'), 'export function unfinishe
|
||||
fs.writeFileSync(path.join(primaryRoot, 'package.json'), JSON.stringify({ name: 'index-ui-project', type: 'module' }));
|
||||
fs.writeFileSync(path.join(otherRoot, 'other.ts'), 'export function otherOnly() { return true; }\n');
|
||||
const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
|
||||
assert.equal(bootstrap.version, '1.3.0'); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
|
||||
assert.equal(bootstrap.version, JSON.parse(fs.readFileSync('package.json', 'utf8')).version); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
|
||||
const api = async (route, input) => {
|
||||
const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token }, ...(input === undefined ? {} : { body: JSON.stringify(input) }) });
|
||||
|
||||
@@ -8,7 +8,8 @@ import { APP_VERSION } from '../src/server/diagnostics.mjs';
|
||||
// Operates only on a fresh synthetic project. The configured model remains in
|
||||
// the running host; bootstrap contains an API session token, never its model key.
|
||||
const workspace = process.cwd();
|
||||
const precision = process.argv.includes('--precision');
|
||||
const batch = process.argv.includes('--batch');
|
||||
const precision = batch || process.argv.includes('--precision');
|
||||
const bannerLines = 420;
|
||||
const url = process.env.AGENT_WORKBENCH_URL || 'http://127.0.0.1:4318';
|
||||
const origin = new URL(url);
|
||||
@@ -25,8 +26,8 @@ const api = async (route, input) => {
|
||||
return result;
|
||||
};
|
||||
|
||||
const caseRoot = path.resolve('.qa', (precision ? 'live-precision-' : 'live-delivery-') + randomUUID());
|
||||
const projectRoot = path.join(caseRoot, precision ? '精确补丁交付工程' : '交付报告工程');
|
||||
const caseRoot = path.resolve('.qa', (batch ? 'live-batch-' : precision ? 'live-precision-' : 'live-delivery-') + randomUUID());
|
||||
const projectRoot = path.join(caseRoot, batch ? '多文件变更集交付工程' : precision ? '精确补丁交付工程' : '交付报告工程');
|
||||
const allowed = ['src/normalize.mjs', 'src/summary.mjs', 'src/render.mjs', 'src/cli.mjs'];
|
||||
const scripts = { test: 'node --test test/*.test.mjs', build: 'node scripts/build.mjs' };
|
||||
fs.mkdirSync(caseRoot, { recursive: true });
|
||||
@@ -69,11 +70,11 @@ const assertProtected = () => {
|
||||
};
|
||||
const project = await api('/projects', { root: projectRoot });
|
||||
const session = await api('/sessions', { projectId: project.id });
|
||||
const started = Date.now(), applied = [], decisions = [], reviewLimit = 4;
|
||||
let reviewedRounds = 0, state, succeeded = false, lastProgress = '', originalTaskId;
|
||||
const started = Date.now(), applied = [], decisions = [], batches = [], reviewLimit = 4;
|
||||
let reviewedRounds = 0, sealingFollowups = 0, state, succeeded = false, lastProgress = '', originalTaskId;
|
||||
const saveEvidence = result => {
|
||||
fs.writeFileSync(path.join(caseRoot, 'result.json'), JSON.stringify(result, null, 2));
|
||||
fs.writeFileSync(path.join(workspace, precision ? '.qa/live-precision-validation.json' : '.qa/live-delivery-validation.json'), JSON.stringify(result, null, 2));
|
||||
fs.writeFileSync(path.join(workspace, batch ? '.qa/live-batch-validation.json' : precision ? '.qa/live-precision-validation.json' : '.qa/live-delivery-validation.json'), JSON.stringify(result, null, 2));
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -85,18 +86,19 @@ try {
|
||||
: '只能用 propose_file 修改 src/normalize.mjs、src/summary.mjs、src/render.mjs、src/cli.mjs;') +
|
||||
'允许修改的源码仅为 src/normalize.mjs、src/summary.mjs、src/render.mjs、src/cli.mjs。' +
|
||||
'测试、fixtures、构建脚本、package.json、README 和 OWNER 文件必须保留。四模块都需修复,不能修改验收来通过。' +
|
||||
(batch ? '四个源码提案全部准备后,必须用 prepare_change_set 一次封存这四份change_id,等待整批审查。第一次不要只封存部分文件;到工具轮次上限会继续原任务,已保存提案无需重做。' : '') +
|
||||
'本工程没有第三方依赖,不用安装。不要使用 run_command、不要自己提交Git;本轮终端仅通过已识别的npm检查计划运行。' +
|
||||
'提案等待审查应用,随后继续同一目标并实际重新运行 test/build,依据日志修复直至通过。检查通过后用 plan_delivery 准备本Task的四文件本地Git预览,等待用户独立确认;最后用中文报告实际测试数量、构建结果和改动。' });
|
||||
while (Date.now() - started < 720000) {
|
||||
state = await api('/sessions/' + session.id); originalTaskId ??= state.execution.task.id;
|
||||
assert.equal(state.execution.task.id, originalTaskId, 'Engineering delivery must retain the original Task.');
|
||||
assertProtected();
|
||||
const progress = state.status + '|' + state.events.length + '|' + state.execution.checks.map(job => job.status).join(',');
|
||||
const progress = state.status + '|' + state.events.length + '|' + state.execution.checks.map(job => job.status).join(',') + '|' + (state.execution.changeSets ?? []).map(set => set.status).join(',');
|
||||
if (progress !== lastProgress) {
|
||||
console.log(JSON.stringify({ status: state.status, elapsedSeconds: Math.round((Date.now() - started) / 1000),
|
||||
tools: state.events.filter(event => event.kind === 'tool').slice(-5).map(event => ({ tool: event.tool, phase: event.phase })),
|
||||
checks: state.execution.checks.map(job => ({ status: job.status, results: job.results.map(result => ({ name: result.name, status: result.status, tests: result.tests })) })),
|
||||
appliedFiles: applied.map(item => item.path) }));
|
||||
appliedFiles: applied.map(item => item.path), changeSets: (state.execution.changeSets ?? []).map(set => ({ id: set.id, status: set.status, files: set.files.length })) }));
|
||||
lastProgress = progress;
|
||||
}
|
||||
for (const proposal of state.changes.filter(change => ['pending', 'conflict'].includes(change.status))) assert.ok(allowed.includes(proposal.path), 'Out-of-scope proposal: ' + proposal.path);
|
||||
@@ -117,15 +119,15 @@ try {
|
||||
}
|
||||
if (['running', 'awaiting_approval', 'stopping'].includes(state.status)) { await new Promise(resolve => setTimeout(resolve, 1000)); continue; }
|
||||
if (state.status === 'failed') throw new Error(state.failure?.message ?? 'The real model task failed.');
|
||||
const preparedSets = (state.execution.changeSets ?? []).filter(set => set.taskId === originalTaskId && set.status === 'prepared');
|
||||
if (state.status === 'paused') {
|
||||
assert.equal(state.execution.run.stopReason, 'step_limit', 'Budget/cancellation must be inspected before continuing.');
|
||||
assert.ok(state.execution.runs.length < 5, 'Bounded continuation count exceeded.');
|
||||
await api('/sessions/' + session.id + '/resume', {}); continue;
|
||||
if (!preparedSets.length) { await api('/sessions/' + session.id + '/resume', {}); continue; }
|
||||
}
|
||||
const pending = state.changes.filter(change => change.status === 'pending');
|
||||
if (pending.length) {
|
||||
assert.ok(state.execution.checks.some(job => job.status === 'failed' && job.results.some(result => result.tests?.failed > 0)), 'Capture a real baseline test failure before applying repairs.');
|
||||
assert.ok(++reviewedRounds <= reviewLimit, 'Too many repair/review rounds.');
|
||||
for (const proposal of pending) {
|
||||
assert.equal(sha(proposal.path), proposal.baseSha256, 'Proposal baseline changed.');
|
||||
assert.notEqual(proposal.content.trim(), '', 'Empty source proposal.');
|
||||
@@ -135,11 +137,41 @@ try {
|
||||
assert.deepEqual(Buffer.from(proposal.content).subarray(0, sourcePrefixes[proposal.path].length), sourcePrefixes[proposal.path]);
|
||||
assert.equal(proposal.patch.preservedBom, sourceFormats[proposal.path].bom); assert.equal(proposal.patch.lineEnding, sourceFormats[proposal.path].lineEnding);
|
||||
}
|
||||
const beforeApply = await api('/sessions/' + session.id + '/changes/' + proposal.id + '/apply', {});
|
||||
assert.equal(sha(proposal.path), proposal.sha256, 'Applied bytes do not match the reviewed proposal.');
|
||||
applied.push({ id: proposal.id, path: proposal.path, sha256: proposal.sha256, taskId: originalTaskId, ...(precision ? { editKind: proposal.editKind, patch: proposal.patch } : {}) });
|
||||
assert.ok(beforeApply.session ?? beforeApply, 'No apply response.'); assertProtected();
|
||||
}
|
||||
if (batch && !preparedSets.length) {
|
||||
assert.ok(++sealingFollowups <= 1, 'The actual model did not seal the requested batch after the bounded follow-up.');
|
||||
await api('/sessions/' + session.id + '/messages', { content: '沿用原任务与已保存的提案,不重新修改或重放工具。请用 prepare_change_set 一次封存以下待审查change_id,并等待用户审查:' + JSON.stringify(pending.map(proposal => proposal.id)) });
|
||||
continue;
|
||||
}
|
||||
assert.ok(++reviewedRounds <= reviewLimit, 'Too many repair/review rounds.');
|
||||
let changeSetId = null;
|
||||
if (preparedSets.length) {
|
||||
assert.equal(preparedSets.length, 1); const set = preparedSets[0]; changeSetId = set.id;
|
||||
assert.equal(set.source, 'agent'); assert.equal(set.taskId, originalTaskId);
|
||||
assert.deepEqual(set.files.map(file => file.changeId).sort(), pending.map(proposal => proposal.id).sort(), 'The reviewed batch must cover all pending proposals.');
|
||||
if (batch && reviewedRounds === 1) assert.deepEqual(set.files.map(file => file.path).sort(), [...allowed].sort(), 'The first batch must seal all four modules.');
|
||||
for (const file of set.files) {
|
||||
const proposal = pending.find(proposal => proposal.id === file.changeId);
|
||||
assert.equal(file.baseSha256, proposal.baseSha256); assert.equal(file.sha256, proposal.sha256); assert.equal(file.sourceRunId, proposal.runId);
|
||||
}
|
||||
await api('/sessions/' + session.id + '/change-sets/' + set.id + '/apply', { fingerprint: set.fingerprint });
|
||||
let completedSet;
|
||||
for (let attempt = 0; attempt < 120; attempt++) {
|
||||
completedSet = await api('/sessions/' + session.id + '/change-sets/' + set.id);
|
||||
if (!['applying', 'rolling_back'].includes(completedSet.status)) break;
|
||||
await new Promise(resolve => setTimeout(resolve, 250));
|
||||
}
|
||||
assert.equal(completedSet.status, 'completed', completedSet.summary); assert.equal(completedSet.requiresVerification, false);
|
||||
assert.equal(completedSet.fingerprint, set.fingerprint); assert.ok(completedSet.files.every(file => file.writeAttempted && file.state === 'after'));
|
||||
batches.push(completedSet);
|
||||
} else {
|
||||
for (const proposal of pending) await api('/sessions/' + session.id + '/changes/' + proposal.id + '/apply', {});
|
||||
}
|
||||
for (const proposal of pending) {
|
||||
assert.equal(sha(proposal.path), proposal.sha256, 'Applied bytes do not match the reviewed proposal.');
|
||||
applied.push({ id: proposal.id, path: proposal.path, sha256: proposal.sha256, taskId: originalTaskId, changeSetId, ...(precision ? { editKind: proposal.editKind, patch: proposal.patch } : {}) });
|
||||
}
|
||||
assertProtected();
|
||||
await api('/sessions/' + session.id + '/continue-reviewed', {}); continue;
|
||||
}
|
||||
assert.equal(state.status, 'completed'); break;
|
||||
@@ -194,6 +226,12 @@ try {
|
||||
};
|
||||
const deliveryJson = await readArtifact(deliveryJob.reportArtifactId), deliveryMarkdown = await readArtifact(deliveryJob.reportMarkdownArtifactId);
|
||||
const report = JSON.parse(deliveryJson); assert.equal(report.status, 'verified_committed'); assert.equal(report.task.id, originalTaskId);
|
||||
if (batch) assert.ok(batches.length > 0, 'The actual model must prepare a reviewed ChangeSet.');
|
||||
for (const set of batches) {
|
||||
const recorded = report.changeSets.find(value => value.id === set.id);
|
||||
assert.equal(recorded.status, 'completed'); assert.equal(recorded.fingerprint, set.fingerprint); assert.equal(recorded.snapshotVerified, true);
|
||||
assert.ok(report.changes.filter(change => set.files.some(file => file.changeId === change.id)).every(change => change.changeSetId === set.id));
|
||||
}
|
||||
assert.equal(report.verifiedCheckJobId, passedJob.id); assert.equal(report.deliveries.at(-1).commit, deliveredCommit);
|
||||
assert.equal(report.task.requirementsAcceptance, 'not_recorded'); assert.match(deliveryMarkdown, /14\/14/);
|
||||
fs.writeFileSync(path.join(caseRoot, 'delivery-report.json'), deliveryJson); fs.writeFileSync(path.join(caseRoot, 'delivery-report.md'), deliveryMarkdown);
|
||||
@@ -207,19 +245,19 @@ try {
|
||||
do { log = await api('/artifacts/' + result.logArtifactId + '?session=' + session.id + '&offset=' + offset + '&limit=16000'); text += log.content; offset += log.content.length; } while (log.truncated && log.content.length);
|
||||
fs.writeFileSync(path.join(caseRoot, job.id + '-' + result.name + '.log'), text);
|
||||
}
|
||||
const result = { success: true, version: bootstrap.version, mode: precision ? 'indexed-exact-patch' : 'whole-file', testedAt: new Date().toISOString(), model: bootstrap.config.model,
|
||||
const result = { success: true, version: bootstrap.version, mode: batch ? 'reviewed-multi-file-exact-patch' : precision ? 'indexed-exact-patch' : 'whole-file', testedAt: new Date().toISOString(), model: bootstrap.config.model,
|
||||
projectRoot, projectId: project.id, sessionId: session.id, taskId: originalTaskId, baselineCommit, deliveredCommit, deliveryPlan, deliveryJob,
|
||||
elapsedSeconds: Math.round((Date.now() - started) / 1000), runs: state.execution.runs.length, reviewRounds: reviewedRounds, applied,
|
||||
elapsedSeconds: Math.round((Date.now() - started) / 1000), runs: state.execution.runs.length, reviewRounds: reviewedRounds, sealingFollowups, applied, batches,
|
||||
protectedHashes, ownerEditsPreserved: true, ownerStagePreserved: true, precisionEvidence, reportStatus: report.status, reportPath: path.join(caseRoot, 'delivery-report.md'), buildOutput: JSON.parse(built.stdout), usage: state.execution.task.usage,
|
||||
checks: state.execution.checks, decisions, diffPath: path.join(caseRoot, 'reviewed-changes.diff'), sessionPath: path.join(caseRoot, 'session.json'),
|
||||
credentialsHandling: 'Calls use the running host model configuration; no model key was read, copied or saved.',
|
||||
intervention: 'Verifier approved only sealed npm scripts, reviewed and applied four source proposals, and confirmed an owned Git preview through the Workbench API. Implementation came from the configured model; the Workbench generated and verified the commit and evidence reports.',
|
||||
scope: 'One synthetic Node engineering sample; does not establish all M2 engineering classes, ChangeSet/worktree or M6 delivery success rates.' };
|
||||
intervention: 'Verifier approved only sealed npm scripts, reviewed all source proposals before applying them through the single-file or fingerprint-bound batch API, and confirmed an owned Git preview. Implementation and batch preparation came from the configured model; the Workbench verified the files, checks, commit and reports.',
|
||||
scope: 'One synthetic Node engineering sample; does not establish all M2 engineering classes, worktrees or M6 delivery success rates.' };
|
||||
saveEvidence(result); succeeded = true;
|
||||
console.log(JSON.stringify({ success: true, model: result.model, testsPassed: 14, buildPassed: true, deliveredCommit, elapsedSeconds: result.elapsedSeconds, reviewRounds: reviewedRounds, projectRoot, sessionId: session.id }, null, 2));
|
||||
} catch (error) {
|
||||
saveEvidence({ success: false, version: bootstrap.version, testedAt: new Date().toISOString(), model: bootstrap.config.model, projectRoot,
|
||||
projectId: project.id, sessionId: session.id, taskId: originalTaskId, error: error.message, elapsedSeconds: Math.round((Date.now() - started) / 1000), applied, decisions,
|
||||
projectId: project.id, sessionId: session.id, taskId: originalTaskId, error: error.message, elapsedSeconds: Math.round((Date.now() - started) / 1000), applied, decisions, batches,
|
||||
checks: state?.execution?.checks ?? [] });
|
||||
throw error;
|
||||
} finally {
|
||||
|
||||
@@ -6,7 +6,7 @@ import { createHash } from 'node:crypto';
|
||||
const url = process.env.AGENT_WORKBENCH_URL || 'http://127.0.0.1:4318';
|
||||
const sessionId = process.env.AGENT_WORKBENCH_SESSION || '569c9457-d399-46e6-b53e-4b1fdbb02109';
|
||||
const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
|
||||
assert.ok(['1.0.0', '1.1.0', '1.2.0', '1.3.0'].includes(bootstrap.version));
|
||||
assert.ok(['1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0'].includes(bootstrap.version));
|
||||
assert.equal(bootstrap.config.mode, 'compatible');
|
||||
assert.ok(bootstrap.config.hasKey, 'The existing in-memory connection must be present.');
|
||||
const api = async (route, input) => {
|
||||
|
||||
@@ -226,7 +226,7 @@ try {
|
||||
await settings.getByRole('button', { name: '保存连接', exact: true }).click();
|
||||
await expect(page.getByRole('button', { name: 'fixture-ui-agent', exact: true })).toBeVisible();
|
||||
await newTask('UI 兼容接口验证');
|
||||
await expect(page.locator('.conversation')).toContainText('兼容协议流程已完成');
|
||||
await expect(page.locator('.conversation')).toContainText('兼容协议流程已完成', { timeout: 20000 });
|
||||
await expect(page.locator('.task-toolbar .status')).toHaveText('待审查');
|
||||
assert.equal(modelRequests, 3);
|
||||
await page.locator('.review-callout').click();
|
||||
|
||||
+27
-5
@@ -6,13 +6,14 @@ import { DiffView, EmptyInspector, IconButton, Modal, ResearchContent, Status, T
|
||||
import { DiagnosticsPanel } from './DiagnosticsPanel';
|
||||
import { TaskPanel } from './TaskPanel';
|
||||
import { CodeIndexPanel } from './CodeIndexPanel';
|
||||
import { ChangesInspector } from './ChangesInspector';
|
||||
|
||||
const activeStates = ['running', 'awaiting_approval', 'stopping'];
|
||||
const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048, hasKey: false, maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000 };
|
||||
|
||||
export default function App() {
|
||||
const [token, setAccess] = useState('');
|
||||
const [version, setVersion] = useState('1.3.0');
|
||||
const [version, setVersion] = useState('1.4.0');
|
||||
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
|
||||
const [diagnostics, setDiagnostics] = useState<RuntimeDiagnostics | null>(null);
|
||||
const [diagnosticsBusy, setDiagnosticsBusy] = useState(false);
|
||||
@@ -36,6 +37,7 @@ export default function App() {
|
||||
const [changeBusy, setChangeBusy] = useState('');
|
||||
const [deciding, setDeciding] = useState(false);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const editingRef = useRef(editing); editingRef.current = editing;
|
||||
const [draft, setDraft] = useState('');
|
||||
const [composer, setComposer] = useState('');
|
||||
const [sending, setSending] = useState(false);
|
||||
@@ -76,9 +78,16 @@ export default function App() {
|
||||
const sessionCreation = useRef<Promise<Session | null> | null>(null);
|
||||
const selectedProject = projects.find(project => project.id === projectId);
|
||||
const isRunning = !!session && (activeStates.includes(session.status) || session.execution?.checks.some(job => ['queued', 'running'].includes(job.status)) === true
|
||||
|| session.execution?.deliveries?.some(job => ['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting'].includes(job.status)) === true);
|
||||
|| session.execution?.deliveries?.some(job => ['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting'].includes(job.status)) === true
|
||||
|| session.execution?.changeSets?.some(set => ['applying', 'rolling_back'].includes(set.status)) === true);
|
||||
const anyRunning = isRunning || briefs.some(item => activeStates.includes(item.status));
|
||||
const pending = session?.changes.filter(change => ['pending', 'conflict'].includes(change.status)) || [];
|
||||
const reviewedRun = session?.execution?.run;
|
||||
const canContinueReview = !!session && pending.length === 0 && !isRunning
|
||||
&& (reviewedRun?.status === 'needs_review' || reviewedRun?.status === 'paused' && reviewedRun.stopReason === 'step_limit')
|
||||
&& reviewedRun?.taskId === session.execution?.task?.id
|
||||
&& !session.execution?.progress.requiresVerification.length
|
||||
&& session.changes.some(change => change.status === 'applied' && (!change.taskId || change.taskId === session.execution?.task?.id));
|
||||
const selectedChange = session?.changes.find(change => change.id === changeId) || pending[0] || session?.changes.at(-1);
|
||||
const selectedEvent = session?.events.find(event => event.id === eventId) || session?.events.at(-1);
|
||||
const approval = session?.approvals.find(item => item.status === 'pending');
|
||||
@@ -107,7 +116,7 @@ export default function App() {
|
||||
function failure(error: unknown) { notify(error instanceof Error ? error.message : String(error)); }
|
||||
function selectSession(id: string) {
|
||||
if (selectedSessionRef.current === id) return;
|
||||
selectedSessionRef.current = id; setSessionId(id); setSession(null);
|
||||
selectedSessionRef.current = id; setSessionId(id); setSession(null); setToast('');
|
||||
localStorage.setItem('awb-session', id); setChangeId(''); setEventId('');
|
||||
}
|
||||
function acceptSession(updated: Session) {
|
||||
@@ -138,6 +147,7 @@ export default function App() {
|
||||
if (request === filesRequest.current && selectedProjectRef.current === id) setFiles(result.files);
|
||||
}
|
||||
async function chooseProject(id: string, preferredSession?: string) {
|
||||
if (selectedProjectRef.current !== id) setToast('');
|
||||
selectedProjectRef.current = id; setProjectId(id); localStorage.setItem('awb-project', id);
|
||||
filesRequest.current++; fileRequest.current++;
|
||||
setOpenFile(null); setFiles([]); setFileLoading(false); setFileLine(null); setFileNotice(''); setEditing(false); setCollapsed(new Set()); setFilter('');
|
||||
@@ -231,6 +241,18 @@ export default function App() {
|
||||
notify(action === 'apply' ? '已应用 ' + change.path : '已撤回提案。');
|
||||
} catch (error) { failure(error); } finally { setChangeBusy(''); }
|
||||
}
|
||||
async function refreshBatchFiles() {
|
||||
const targetProject = selectedProjectRef.current, marker = fileRequest.current, relative = openFile?.path;
|
||||
await refreshFiles(targetProject);
|
||||
if (!relative || selectedProjectRef.current !== targetProject || fileRequest.current !== marker) return;
|
||||
if (editingRef.current) { setFileNotice('文件批次已更新项目;本地编辑草稿保留,请先核对当前文件。'); return; }
|
||||
try {
|
||||
const file = await api<OpenFile>('/projects/' + targetProject + '/file?path=' + encodeURIComponent(relative));
|
||||
if (selectedProjectRef.current === targetProject && fileRequest.current === marker && !editingRef.current) {
|
||||
setOpenFile(file); setDraft(file.content); setFileLine(null); setFileNotice('');
|
||||
}
|
||||
} catch (error) { if (selectedProjectRef.current === targetProject && fileRequest.current === marker) setFileNotice('批次更新后该文件已移除或不可读取,请从文件列表重新选择。'); }
|
||||
}
|
||||
async function decide(allow: boolean) {
|
||||
if (!session || !approval || deciding) return;
|
||||
setDeciding(true);
|
||||
@@ -444,7 +466,7 @@ export default function App() {
|
||||
</div>}
|
||||
{approval && <div className="approval-card"><div className="approval-heading"><span><ShieldCheck size={17} /></span><div><strong>确认这次终端执行</strong><p>{approval.reason}</p></div></div><pre>{approval.command}</pre><div className="approval-path"><Folder size={12} /><span>{approval.cwd}</span></div><p className="approval-shell">{approval.shell || '项目终端'} · UTF-8</p><p className="approval-scope">确认后以你的系统权限执行。</p><div className="approval-actions"><button className="button secondary" onClick={() => decide(false)} disabled={deciding}>拒绝执行</button><button className="button primary" onClick={() => decide(true)} disabled={deciding}><Play size={14} />确认执行</button></div></div>}
|
||||
{pending.length > 0 && !isRunning && <button className="review-callout" onClick={() => { setChangeId(pending[0].id); showInspector('changes'); }}><FileCode2 size={17} /><span><strong>{pending.length} 项改动等待审查</strong><small>查看差异后,再应用到项目文件。</small></span><ArrowRight size={17} /></button>}
|
||||
{pending.length === 0 && !isRunning && session?.execution?.run?.status === 'needs_review' && session.changes.some(change => change.status === 'applied' && (!change.taskId || change.taskId === session.execution?.task?.id)) && <button type="button" aria-label="继续检查与交付" className="review-callout" disabled={resuming} onClick={continueReviewed}><ClipboardCheck size={17} /><span><strong>继续检查与交付</strong><small>改动已应用,沿用原任务继续实际测试和修复。</small></span><ArrowRight size={17} /></button>}
|
||||
{canContinueReview && <button type="button" aria-label="继续检查与交付" className="review-callout" disabled={resuming} onClick={continueReviewed}><ClipboardCheck size={17} /><span><strong>继续检查与交付</strong><small>改动已应用,沿用原任务继续实际测试和修复。</small></span><ArrowRight size={17} /></button>}
|
||||
<div ref={chatEnd} />
|
||||
</section>
|
||||
<footer className="composer-wrap"><form className="composer" onSubmit={event => { event.preventDefault(); submit(); }}><textarea ref={composerRef} aria-label="任务内容" placeholder={config.mode === 'demo' ? '先体验完整流程,或连接自己的模型开始开发…' : '描述项目任务,或询问工作台的执行状态与报错…'} value={composer} onChange={event => setComposer(event.target.value)} onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); submit(); } }} maxLength={20000} rows={3} /><div className="composer-bottom"><span><Folder size={13} />{selectedProject?.name || '选择项目'}<span className="composer-divider" />{config.mode === 'demo' ? '固定演示脚本' : '兼容模型服务'}</span>{isRunning ? <button type="button" className="stop-button" onClick={() => session && api('/sessions/' + session.id + '/stop', {}).catch(failure)}><Square size={13} />停止</button> : <button type="submit" className="send-button" aria-label="发送任务" disabled={!composer.trim() || sending || creatingSession || !ready || !!(sessionId && !session)}>{sending ? <LoaderCircle size={17} className="spin" /> : <ArrowUp size={18} />}</button>}</div></form><div className="composer-footnote"><span>Ctrl + Enter 发送 · 会话自动保存</span><span>{session?.estimatedTokens ? '上下文估算 ' + session.estimatedTokens.toLocaleString() + ' tokens' : '改动与执行结果可追溯'}</span></div></footer>
|
||||
@@ -453,7 +475,7 @@ export default function App() {
|
||||
<aside className="inspector">
|
||||
<div className="inspector-tabs"><button className={tab === 'file' ? 'selected' : ''} onClick={() => setTab('file')}><FileCode2 size={14} />文件</button><button className={tab === 'changes' ? 'selected' : ''} onClick={() => setTab('changes')}><GitBranch size={14} />改动{pending.length > 0 && <b>{pending.length}</b>}</button><button className={tab === 'trace' ? 'selected' : ''} onClick={() => setTab('trace')}><SquareTerminal size={14} />轨迹</button><button className={tab === 'task' ? 'selected' : ''} onClick={() => setTab('task')}><ClipboardCheck size={14} />任务</button><button className={tab === 'index' ? 'selected' : ''} onClick={() => setTab('index')}><Search size={14} />索引</button><IconButton label={narrow ? '关闭检视区' : wide ? '缩小检视区' : '放大检视区'} onClick={() => setWide(previous => !previous)}>{narrow ? <X size={16} /> : wide ? <Minimize2 size={14} /> : <Maximize2 size={14} />}</IconButton></div>
|
||||
{tab === 'file' && (fileLoading ? <div className="loading-inspector"><LoaderCircle className="spin" size={24} />正在读取文件</div> : openFile ? <div className="file-inspector"><div className="file-heading"><FileCode2 size={15} /><span title={openFile.path}>{openFile.path}</span><IconButton label="复制文件内容" onClick={() => navigator.clipboard.writeText(openFile.content).then(() => notify('已复制文件内容。')).catch(failure)}><Copy size={14} /></IconButton><IconButton label={editing ? '取消编辑' : '编辑文件'} onClick={() => { setEditing(previous => !previous); setDraft(openFile.content); }}><Pencil size={14} /></IconButton></div><div className="file-details"><span>{lineCount} 行 · {openFile.bytes.toLocaleString()} B{fileLine ? ' · 定位第 ' + fileLine + ' 行' : ''}</span><span className="code-utility">{openFile.sha256.slice(0, 10)}</span></div>{fileNotice && <div className="file-index-notice" role="status">{fileNotice}</div>}{editing ? <><textarea className="code-editor" aria-label="编辑文件内容" spellCheck={false} value={draft} onChange={event => setDraft(event.target.value)} /><div className="editor-actions"><button className="button primary" onClick={saveDraft} disabled={draft === openFile.content || draftSaving}><GitBranch size={14} />保存为提案</button></div></> : <div className="code-view" ref={codeViewRef}>{openFile.content.split('\n').map((line, index) => <div key={index} data-line={index + 1} className={fileLine === index + 1 ? 'code-line-target' : ''}><span>{index + 1}</span><code>{line.replace(/\r$/, '') || ' '}</code></div>)}</div>}</div> : <EmptyInspector kind="file" />)}
|
||||
{tab === 'changes' && (selectedChange ? <div className="changes-inspector"><div className="change-list">{session?.changes.map(change => <button key={change.id} className={selectedChange.id === change.id ? 'selected' : ''} onClick={() => setChangeId(change.id)}><FileCode2 size={14} /><span>{change.path}</span><span className="change-stats"><b>+{change.additions}</b><i>−{change.deletions}</i></span></button>)}</div><div className="change-summary"><div><strong>{selectedChange.path}</strong><Status value={selectedChange.status} /></div><p>{selectedChange.reason}</p>{selectedChange.patch && <p className="patch-detail">精确补丁 · {selectedChange.patch.edits} 处替换 · {selectedChange.patch.lineEnding === 'mixed' ? '按原文核对混合换行' : '保留 ' + selectedChange.patch.lineEnding.toUpperCase() + ' 换行'}{selectedChange.patch.preservedBom ? ' · 保留 BOM' : ''}</p>}</div><DiffView change={selectedChange} /><div className="change-actions">{['pending', 'conflict'].includes(selectedChange.status) ? <><button className="button secondary" onClick={() => changeAction(selectedChange, 'reject')} disabled={!!changeBusy || isRunning}>撤回提案</button><button className="button primary" disabled={selectedChange.status !== 'pending' || !!changeBusy || isRunning} onClick={() => changeAction(selectedChange, 'apply')}><Check size={14} />应用这项改动</button></> : <span className="subtle">{selectedChange.status === 'applied' ? '这项改动已写入项目。' : '这项提案已结束。'}</span>}<IconButton label="下载建议内容" onClick={() => downloadBlob(new Blob([selectedChange.content], { type: 'text/plain;charset=utf-8' }), selectedChange.path.split('/').at(-1) || 'proposal.txt')}><ArrowDownToLine size={15} /></IconButton></div></div> : <EmptyInspector kind="changes" />)}
|
||||
{tab === 'changes' && (session ? <ChangesInspector session={session} selectedChange={selectedChange} busy={!!changeBusy} isRunning={isRunning} onSelect={setChangeId} onAction={changeAction} onSession={acceptSession} onError={failure} onFilesChanged={refreshBatchFiles} /> : <EmptyInspector kind="changes" />)}
|
||||
{tab === 'trace' && (session?.events.length ? <div className="trace-inspector"><div className="trace-caption"><span>完整执行记录</span><span>{toolEvents.length} 次工具调用</span></div><div className="trace-list">{session.events.map(event => <ToolRow key={event.id} event={event} selected={selectedEvent?.id === event.id} onSelect={() => setEventId(event.id)} />)}</div>{selectedEvent && <div className="event-details"><div className="event-detail-heading"><strong>{selectedEvent.label}</strong><Status value={selectedEvent.phase} /></div>{selectedEvent.input && <><h4>输入</h4><pre>{JSON.stringify(selectedEvent.input, null, 2)}</pre></>}<h4>结果</h4><pre>{selectedEvent.output || (selectedEvent.phase === 'waiting' ? '等待确认后执行。' : '正在等待工具结果。')}</pre>{selectedEvent.durationMs !== undefined && <p className="subtle">耗时 {(selectedEvent.durationMs / 1000).toFixed(2)} 秒,包含确认等待。</p>}</div>}</div> : <EmptyInspector kind="trace" />)}
|
||||
{tab === 'task' && (session ? <TaskPanel key={session.id} session={session} onSession={acceptSession} onError={failure} busy={isRunning} /> : <EmptyInspector kind="trace" />)}
|
||||
{selectedProject && <CodeIndexPanel key={selectedProject.id} project={selectedProject} active={tab === 'index'} onOpen={(path, line, expectedSha256) => void loadFile(path, { line, expectedSha256 })} />}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
.change-set-bar{display:flex;align-items:center;flex-wrap:wrap;gap:9px;padding:12px;border-bottom:1px solid #dce7d8;background:#f2f7ee;flex-shrink:0;color:#456243}
|
||||
.change-set-bar>div{flex:1;min-width:150px}.change-set-bar strong{display:block;font-size:12px;font-weight:600}.change-set-bar small{display:block;font-size:10px;line-height:1.6;margin-top:3px;color:#71836b;overflow-wrap:anywhere}.change-set-bar .button{padding:7px 10px;font-size:11px;min-height:30px}
|
||||
.batch-attention{background:#fff7ea;border-color:#e6d1ac;color:#7c613b}.batch-attention small{color:#8a7658}.batch-sealed-note{font-size:10px!important;color:#6b7d55!important}
|
||||
.batch-select-list{flex:1;min-height:0;overflow:auto;border-top:1px solid #dce7d8}.batch-select-list>label{display:flex;align-items:center;gap:12px;padding:14px 8px;border-bottom:1px solid #e6ece1;cursor:pointer}.batch-select-list input{width:16px;height:16px;accent-color:#507247;flex-shrink:0}.batch-select-list>label>span:first-of-type{flex:1;min-width:0}.batch-select-list strong{display:block;font:12px Consolas,monospace;overflow-wrap:anywhere}.batch-select-list small{display:block;font-size:11px;color:#7c8b72;margin-top:5px;line-height:1.6;overflow-wrap:anywhere}
|
||||
.batch-heading{display:flex;align-items:center;gap:10px;flex-wrap:wrap;font-size:11px;line-height:1.7;padding:10px 0 14px;flex-shrink:0}.batch-heading>span:nth-child(2){flex:1;min-width:180px;overflow-wrap:anywhere}.batch-heading select{max-width:100%;font-size:11px;border:1px solid #d9e5d4;padding:6px;border-radius:5px;color:#4a6646;background:#f7faf3}
|
||||
.batch-review-grid{display:grid;grid-template-columns:minmax(180px,26%) minmax(0,1fr);flex:1;min-height:160px;border:1px solid #dfe8d7;border-radius:7px;overflow:hidden}.batch-file-list{overflow:auto;min-height:0;border-right:1px solid #dfe8d7;background:#f8faf5}.batch-file-list button{display:block;width:100%;text-align:left;padding:12px;border-bottom:1px solid #e7edde;color:#506647;outline-offset:-3px}.batch-file-list button.selected{background:#eaf2df;box-shadow:inset 3px 0 #6e8f54}.batch-file-list strong{display:block;font:11px Consolas,monospace;overflow-wrap:anywhere}.batch-file-list small{display:block;font-size:10px;margin-top:5px;color:#7c8b71}.batch-file-list code{display:block;font-size:10px;color:#8b967e;margin-top:5px}.batch-file-list .batch-problem{color:#966636;line-height:1.6;overflow-wrap:anywhere}.batch-diff{display:flex;flex-direction:column;min-width:0;min-height:0}.batch-diff-heading{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px 12px;border-bottom:1px solid #dfe8d7;flex-shrink:0;font-size:11px}.batch-diff-heading strong{font:11px Consolas,monospace;overflow-wrap:anywhere}.batch-diff-heading span{color:#89957e;white-space:nowrap}
|
||||
.batch-fingerprint{display:grid;grid-template-columns:60px minmax(0,1fr);gap:5px 12px;padding:11px 0;font-size:10px;flex-shrink:0;color:#8a967e}.batch-fingerprint code{font-size:10px;color:#6b7f58;overflow-wrap:anywhere}.batch-actions{display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:8px;padding-top:12px;border-top:1px solid #dfe8d7;flex-shrink:0}.batch-actions>span{font-size:10px;line-height:1.7;flex:1;min-width:130px;color:#7c8c70;overflow-wrap:anywhere}.batch-actions .button{font-size:11px;min-height:34px}.batch-confirmation{padding:12px;background:#fff7e9;border:1px solid #e3cdac;border-radius:7px;flex-shrink:0;font-size:12px;line-height:1.7;color:#82673f}.batch-confirmation p{font-size:11px;margin:6px 0 10px}.batch-confirmation .button{font-size:11px;margin-right:8px}.status-partial,.status-rolling_back{background:#fff0d8;color:#846129}.status-applying{background:#e9f2df;color:#617e42}.status-rolled_back,.status-resolved_external,.status-external_preserved{background:#edf2eb;color:#66805c}
|
||||
@media(max-width:650px){.batch-review-grid{grid-template-columns:minmax(0,1fr);grid-template-rows:110px minmax(100px,1fr);min-height:180px}.batch-file-list{border-right:0;border-bottom:1px solid #dfe8d7}.batch-file-list button{padding:8px 10px}.batch-file-list small,.batch-file-list code{display:inline-block;margin:3px 10px 0 0}.batch-heading{padding:6px 0 9px}.batch-actions .button{flex:1;white-space:normal}.batch-actions>span{flex-basis:100%}.batch-fingerprint{gap:3px 8px;padding:8px 0}.batch-confirmation{padding:9px}.batch-confirmation .button{min-height:32px;padding:6px 8px}.change-set-bar>div{min-width:130px}.change-set-bar .button{font-size:10px}}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Check, Files, LoaderCircle, RotateCcw, ScanLine, ShieldCheck } from 'lucide-react';
|
||||
import type { ChangeSet, Session } from './types';
|
||||
import { api } from './api';
|
||||
import { DiffView, Modal, Status } from './components';
|
||||
import './ChangeSetPanel.css';
|
||||
|
||||
const openStates = ['prepared', 'applying', 'rolling_back', 'unknown', 'partial'];
|
||||
const labels: Record<string, string> = { before: '原文件', after: '建议内容', external: '外部改动', unavailable: '无法读取', writing: '正在写入', restoring: '正在回退' };
|
||||
|
||||
export function ChangeSetPanel({ session, busy, onSession, onError, onFilesChanged }: {
|
||||
session: Session; busy: boolean; onSession: (session: Session) => void; onError: (error: unknown) => void; onFilesChanged: () => Promise<void>;
|
||||
}) {
|
||||
const sets = session.execution?.changeSets ?? [], taskId = session.execution?.task?.id;
|
||||
const pending = session.changes.filter(change => change.taskId === taskId && change.status === 'pending'
|
||||
&& !sets.some(set => set.id === change.changeSetId && openStates.includes(set.status)));
|
||||
const current = sets.slice().reverse().find(set => openStates.includes(set.status)) ?? sets.at(-1);
|
||||
const [stage, setStage] = useState<'select' | 'review' | null>(null);
|
||||
const [setId, setSetId] = useState(''), [fileId, setFileId] = useState('');
|
||||
const [choices, setChoices] = useState<string[]>([]), [working, setWorking] = useState(false);
|
||||
const [confirmation, setConfirmation] = useState<'rollback' | 'acknowledge' | null>(null);
|
||||
const scope = session.id + ':' + (taskId ?? ''), scopeRef = useRef(scope); scopeRef.current = scope;
|
||||
const filesSignature = sets.filter(set => ['completed', 'rolled_back', 'partial', 'unknown', 'resolved_external'].includes(set.status))
|
||||
.map(set => set.id + ':' + set.status + ':' + set.finishedAt).join('|');
|
||||
const lastFiles = useRef({ scope, signature: filesSignature });
|
||||
useEffect(() => {
|
||||
scopeRef.current = scope;
|
||||
setStage(null); setSetId(''); setFileId(''); setChoices([]); setConfirmation(null); setWorking(false);
|
||||
return () => { if (scopeRef.current === scope) scopeRef.current = ''; };
|
||||
}, [scope]);
|
||||
useEffect(() => {
|
||||
const previous = lastFiles.current; lastFiles.current = { scope, signature: filesSignature };
|
||||
if (previous.scope === scope && previous.signature !== filesSignature) void onFilesChanged().catch(error => { if (scopeRef.current === scope) onError(error); });
|
||||
}, [scope, filesSignature, onFilesChanged, onError]);
|
||||
const selected = sets.find(set => set.id === setId) ?? current;
|
||||
const file = selected?.files.find(value => value.changeId === fileId) ?? selected?.files[0];
|
||||
const proposal = session.changes.find(change => change.id === file?.changeId);
|
||||
const active = !!selected && ['applying', 'rolling_back'].includes(selected.status);
|
||||
const disabled = busy || working || active;
|
||||
const close = () => { setStage(null); setConfirmation(null); };
|
||||
async function prepare() {
|
||||
if (!choices.length || choices.length > 32 || disabled) return;
|
||||
const target = scope; setWorking(true);
|
||||
try {
|
||||
const result = await api<Session>('/sessions/' + session.id + '/change-sets', { changeIds: choices });
|
||||
if (scopeRef.current !== target) return;
|
||||
onSession(result);
|
||||
const next = result.execution?.changeSets?.slice().reverse().find(set => set.status === 'prepared');
|
||||
if (next) { setSetId(next.id); setFileId(next.files[0]?.changeId ?? ''); setStage('review'); }
|
||||
} catch (error) { if (scopeRef.current === target) onError(error); }
|
||||
finally { if (scopeRef.current === target) setWorking(false); }
|
||||
}
|
||||
async function act(set: ChangeSet, action: 'apply' | 'reconcile' | 'rollback' | 'discard' | 'acknowledge') {
|
||||
if (disabled) return;
|
||||
const target = scope; setWorking(true);
|
||||
try {
|
||||
const result = await api<Session>('/sessions/' + session.id + '/change-sets/' + set.id + '/' + action,
|
||||
{ fingerprint: set.fingerprint, ...(action === 'acknowledge' ? { observationFingerprint: set.observationFingerprint } : {}) });
|
||||
if (scopeRef.current === target) { onSession(result); setConfirmation(null); }
|
||||
} catch (error) { if (scopeRef.current === target) onError(error); }
|
||||
finally { if (scopeRef.current === target) setWorking(false); }
|
||||
}
|
||||
const canAcknowledge = selected?.status === 'partial' && !!selected.observationFingerprint
|
||||
&& !!selected.observations?.length && selected.observations.every(value => ['before', 'external'].includes(value.state));
|
||||
return <>
|
||||
<div className={'change-set-bar' + (current?.requiresVerification ? ' batch-attention' : '')}>
|
||||
<Files size={17} /><div><strong>{current ? `多文件变更集 · ${current.files.length} 个文件` : '组合审查文件改动'}</strong>
|
||||
<small>{current ? current.requiresVerification ? '实际文件需要核对,恢复入口保留在这个任务。' : current.summary : pending.length ? `${pending.length} 份提案可组合为一个审查批次。` : '本任务有提案后,可一起审查与应用。'}</small></div>
|
||||
{current && <button type="button" className="button secondary" disabled={working} onClick={() => { setSetId(current.id); setFileId(current.files[0]?.changeId ?? ''); setStage('review'); }}>审查变更集</button>}
|
||||
{!current || !openStates.includes(current.status) ? <button type="button" className="button secondary" disabled={!taskId || !pending.length || busy || working}
|
||||
onClick={() => { setChoices(pending.slice(0, 32).map(change => change.id)); setStage('select'); }}>组合审查</button> : null}
|
||||
</div>
|
||||
{stage === 'select' && <Modal title="选择要一起审查的提案" description="选择1到32份同任务提案,封存后查看整批差异。" wide onClose={close}>
|
||||
<div className="batch-select-list">{pending.map(change => <label key={change.id}><input type="checkbox" aria-label={'选择提案 ' + change.path} checked={choices.includes(change.id)}
|
||||
onChange={event => setChoices(previous => event.target.checked ? [...previous, change.id] : previous.filter(id => id !== change.id))} />
|
||||
<span><strong>{change.path}</strong><small>{change.reason}</small></span><span className="change-stats"><b>+{change.additions}</b><i>−{change.deletions}</i></span></label>)}</div>
|
||||
<div className="batch-actions"><span>已选择 {choices.length} / 32 项</span><button type="button" className="button primary" disabled={disabled || !choices.length || choices.length > 32} onClick={prepare}>
|
||||
{working ? <LoaderCircle size={14} className="spin" /> : <ShieldCheck size={14} />}封存审查范围</button></div>
|
||||
</Modal>}
|
||||
{stage === 'review' && selected && <Modal title="多文件变更集审查" description={`本任务 ${selected.taskId.slice(0, 8)} · ${selected.files.length} 个文件`} wide onClose={close}>
|
||||
<div className="batch-heading"><Status value={selected.status} /><span>{selected.summary}</span>
|
||||
{sets.length > 1 && <select aria-label="选择变更批次" value={selected.id} onChange={event => { setSetId(event.target.value); setFileId(''); setConfirmation(null); }}>
|
||||
{sets.slice().reverse().map(set => <option key={set.id} value={set.id}>{set.id.slice(0, 8)} · {set.files.length} 个文件 · {set.status}</option>)}</select>}
|
||||
</div>
|
||||
<div className="batch-review-grid"><div className="batch-file-list" aria-label="批次文件范围">{selected.files.map(item => {
|
||||
const observation = selected.observations?.find(value => value.path === item.path);
|
||||
return <button type="button" key={item.changeId} aria-label={'查看批次差异 ' + item.path} className={file?.changeId === item.changeId ? 'selected' : ''}
|
||||
onClick={() => setFileId(item.changeId)}><strong>{item.path}</strong><small>{labels[observation?.state ?? item.state] ?? item.state}</small>
|
||||
<code title={observation?.actualSha256 ?? item.baseSha256 ?? '新文件'}>{(observation?.actualSha256 ?? item.baseSha256)?.slice(0, 12) ?? '新文件'}</code>
|
||||
{observation?.problem && <small className="batch-problem">{observation.problem}</small>}{item.restoreError && <small className="batch-problem">{item.restoreError}</small>}</button>;
|
||||
})}</div><div className="batch-diff"><div className="batch-diff-heading"><strong>{file?.path}</strong><span>提案差异</span></div>{proposal && <DiffView change={proposal} />}</div></div>
|
||||
<div className="batch-fingerprint"><span>审查指纹</span><code>{selected.fingerprint}</code><span>Git基线</span><code>{selected.baseline.available ? `${selected.baseline.branch ?? '未命名'} · ${selected.baseline.head?.slice(0, 12) ?? '尚无提交'}` : '项目尚未启用Git'}</code></div>
|
||||
{confirmation && <div className="batch-confirmation" role="alert"><strong>{confirmation === 'rollback' ? '回退本批次已写入的文件' : '保留外部改动并结束恢复'}</strong>
|
||||
<p>{confirmation === 'rollback' ? '只有当前字节仍等于本批次建议时才恢复原文,外部修改会保留。已新建的文件会按同样规则移除。' : '将保留目前已核对的外部内容,并结束这个未成功应用的批次。当前文件再次变化时会拒绝确认。'}</p>
|
||||
<button type="button" className="button secondary" disabled={disabled} onClick={() => setConfirmation(null)}>返回审查</button>
|
||||
<button type="button" className="button primary" disabled={disabled} onClick={() => act(selected, confirmation)}>{confirmation === 'rollback' ? '确认回退本批次' : '确认保留外部改动'}</button></div>}
|
||||
<div className="batch-actions"><span>{active ? '文件批次正在执行,结果会持续更新。' : selected.requiresVerification ? '先核对实际文件,恢复不会自动续写。' : '应用前会核对所有文件及原审查指纹。'}</span>
|
||||
{working && <LoaderCircle size={14} className="spin" />}
|
||||
{['prepared', 'stale'].includes(selected.status) && <button type="button" className="button secondary" disabled={disabled} onClick={() => act(selected, 'discard')}>撤销未执行批次</button>}
|
||||
{selected.status === 'prepared' && <button type="button" className="button primary" disabled={disabled} onClick={() => act(selected, 'apply')}><Check size={14} />确认应用全部 {selected.files.length} 项</button>}
|
||||
{selected.requiresVerification && <button type="button" className="button secondary" disabled={disabled} onClick={() => act(selected, 'reconcile')}><ScanLine size={14} />核对实际文件</button>}
|
||||
{['completed', 'partial', 'unknown'].includes(selected.status) && <button type="button" className="button secondary" disabled={disabled || !!confirmation} onClick={() => setConfirmation('rollback')}><RotateCcw size={14} />回退本批已写入文件</button>}
|
||||
{canAcknowledge && <button type="button" className="button secondary" disabled={disabled || !!confirmation} onClick={() => setConfirmation('acknowledge')}>保留外部改动,结束恢复</button>}
|
||||
</div>
|
||||
</Modal>}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { ArrowDownToLine, Check, FileCode2 } from 'lucide-react';
|
||||
import type { Change, Session } from './types';
|
||||
import { downloadBlob } from './api';
|
||||
import { DiffView, EmptyInspector, IconButton, Status } from './components';
|
||||
import { ChangeSetPanel } from './ChangeSetPanel';
|
||||
|
||||
export function ChangesInspector({ session, selectedChange, busy, isRunning, onSelect, onAction, onSession, onError, onFilesChanged }: {
|
||||
session: Session; selectedChange?: Change; busy: boolean; isRunning: boolean; onSelect: (id: string) => void;
|
||||
onAction: (change: Change, action: 'apply' | 'reject') => Promise<void>; onSession: (session: Session) => void;
|
||||
onError: (error: unknown) => void; onFilesChanged: () => Promise<void>;
|
||||
}) {
|
||||
const sealed = !!selectedChange?.changeSetId && !!session.execution?.changeSets?.some(set => set.id === selectedChange.changeSetId
|
||||
&& ['prepared', 'applying', 'rolling_back', 'unknown', 'partial'].includes(set.status));
|
||||
return <div className="changes-inspector"><ChangeSetPanel session={session} busy={busy || isRunning} onSession={onSession} onError={onError} onFilesChanged={onFilesChanged} />
|
||||
{selectedChange ? <>
|
||||
<div className="change-list">{session.changes.map(change => <button key={change.id} className={selectedChange.id === change.id ? 'selected' : ''} onClick={() => onSelect(change.id)}>
|
||||
<FileCode2 size={14} /><span>{change.path}</span><span className="change-stats"><b>+{change.additions}</b><i>−{change.deletions}</i></span></button>)}</div>
|
||||
<div className="change-summary"><div><strong>{selectedChange.path}</strong><Status value={selectedChange.status} /></div><p>{selectedChange.reason}</p>
|
||||
{selectedChange.patch && <p className="patch-detail">精确补丁 · {selectedChange.patch.edits} 处替换 · {selectedChange.patch.lineEnding === 'mixed' ? '按原文核对混合换行' : '保留 ' + selectedChange.patch.lineEnding.toUpperCase() + ' 换行'}{selectedChange.patch.preservedBom ? ' · 保留 BOM' : ''}</p>}
|
||||
{sealed && <p className="batch-sealed-note">已封存到变更集,请在上方审查整个批次。</p>}</div>
|
||||
<DiffView change={selectedChange} />
|
||||
<div className="change-actions">{['pending', 'conflict'].includes(selectedChange.status) ? <>
|
||||
<button type="button" className="button secondary" onClick={() => onAction(selectedChange, 'reject')} disabled={busy || isRunning || sealed}>撤回提案</button>
|
||||
<button type="button" className="button primary" disabled={selectedChange.status !== 'pending' || busy || isRunning || sealed} onClick={() => onAction(selectedChange, 'apply')}><Check size={14} />应用这项改动</button>
|
||||
</> : <span className="subtle">{selectedChange.status === 'applied' ? '这项改动已写入项目。' : selectedChange.status === 'external_preserved' ? '已保留外部内容,批次未记为成功应用。' : selectedChange.status === 'rolled_back' ? '这项改动已恢复为原文件。' : '这项提案已结束。'}</span>}
|
||||
<IconButton label="下载建议内容" onClick={() => downloadBlob(new Blob([selectedChange.content], { type: 'text/plain;charset=utf-8' }), selectedChange.path.split('/').at(-1) || 'proposal.txt')}><ArrowDownToLine size={15} /></IconButton>
|
||||
</div>
|
||||
</> : <EmptyInspector kind="changes" />}
|
||||
</div>;
|
||||
}
|
||||
@@ -13,6 +13,8 @@ const statusNames: Record<string, string> = {
|
||||
not_configured: '尚未检查', passed: '检查通过', cancelled: '已取消', stale: '需重新检查',
|
||||
planned: '待确认', preparing: '准备提交', prepared: '准备完成', publishing: '发布本地提交', committed: '已生成提交',
|
||||
reporting: '生成报告',
|
||||
applying: '应用中', rolling_back: '回退中', rolled_back: '已回退', partial: '部分结果待核对',
|
||||
resolved_external: '已保留外部修改', external_preserved: '外部内容已保留',
|
||||
};
|
||||
export function Status({ value }: { value: string }) {
|
||||
return <span className={'status status-' + value}><span className="status-dot" />{statusNames[value] || value}</span>;
|
||||
|
||||
+11
-1
@@ -15,6 +15,7 @@ export interface ToolEvent {
|
||||
export interface DiffPart { value: string; count: number; added?: boolean; removed?: boolean }
|
||||
export interface Change {
|
||||
taskId?: string | null; runId?: string | null;
|
||||
changeSetId?: string; rolledBackAt?: string;
|
||||
id: string; path: string; reason: string; status: string; baseExists: boolean; baseSha256: string | null;
|
||||
baseContent: string; content: string; sha256: string; diff: DiffPart[]; additions: number; deletions: number;
|
||||
createdAt: string; appliedAt?: string;
|
||||
@@ -88,4 +89,13 @@ export interface DeliveryJob {
|
||||
commit: string | null; expectedCommit?: string | null; summary?: string; requiresVerification: boolean; startedAt: string; finishedAt: string | null;
|
||||
reportArtifactId?: string; reportMarkdownArtifactId?: string; reportError?: string; indexPreserved?: boolean; workspacePreserved?: boolean;
|
||||
}
|
||||
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; accountedTaskTokens: number }
|
||||
export interface ChangeSet {
|
||||
id: string; taskId: string; runId: string; sessionId: string; projectId: string; fingerprint: string;
|
||||
status: string; requiresVerification: boolean; summary: string; createdAt: string; finishedAt?: string;
|
||||
baseline: { available: boolean; head: string | null; branch: string | null }; observationFingerprint?: string;
|
||||
files: { changeId: string; path: string; baseExists: boolean; baseSha256: string | null; sha256: string; bytes: number;
|
||||
baseBytes: number; mode: number; reason: string; state: string; writeAttempted: boolean; restoreAttempted: boolean;
|
||||
snapshotArtifactId: string; sourceRunId: string; restoreError?: string }[];
|
||||
observations?: { path: string; state: string; exists: boolean | null; actualSha256: string | null; problem?: string }[];
|
||||
}
|
||||
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; accountedTaskTokens: number }
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ return async (request, response) => {
|
||||
eventCursor: store.eventCursor, storage: store.storageInfo(), runtimeRoot: appDirectory,
|
||||
environment: executionEnvironment(),
|
||||
projects: store.projects, sessions: store.listSessions(), exampleProjectId: exampleProject?.id ?? null,
|
||||
capabilities: { fileChanges: 'review', exactPatches: 'sha256-unique-anchors', codeIndex: 'bounded-ast-and-candidates', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified', checks: 'npm-script-jobs', projectInspection: 'bounded-source-and-git', gitDelivery: 'reviewed-local-snapshot', deliveryReports: 'evidence-json-markdown' },
|
||||
capabilities: { changeSets: 'reviewed-recoverable-batches', fileChanges: 'review', exactPatches: 'sha256-unique-anchors', codeIndex: 'bounded-ast-and-candidates', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified', checks: 'npm-script-jobs', projectInspection: 'bounded-source-and-git', gitDelivery: 'reviewed-local-snapshot', deliveryReports: 'evidence-json-markdown' },
|
||||
});
|
||||
if (method === 'GET' && route === '/api/diagnostics') {
|
||||
const selected = url.searchParams.get('session');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
export const APP_VERSION = '1.3.0';
|
||||
export const APP_VERSION = '1.4.0';
|
||||
|
||||
export function executionEnvironment() {
|
||||
const windows = process.platform === 'win32';
|
||||
|
||||
@@ -103,7 +103,9 @@ export class Runtime {
|
||||
continueReviewed(id) {
|
||||
const session = this.store.session(id), run = this.store.core.run.get(session.runId), task = this.store.core.task.get(session.taskId);
|
||||
if (this.isActive(id) || this.checks?.projectActive(session.projectId)) throw Object.assign(new Error('请等待正在执行的任务或检查结束。'), { status: 409 });
|
||||
if (!task || run?.taskId !== task.id || run?.status !== 'needs_review' || session.changes.some(change => ['pending', 'conflict'].includes(change.status))
|
||||
const stoppedForReview = run?.status === 'needs_review' || run?.status === 'paused' && run.stopReason === 'step_limit';
|
||||
if (!task || run?.taskId !== task.id || !stoppedForReview || session.changes.some(change => ['pending', 'conflict'].includes(change.status))
|
||||
|| [...this.store.core.tool.values()].some(tool => tool.taskId === task.id && tool.requiresVerification)
|
||||
|| !session.changes.some(change => change.status === 'applied' && (!change.taskId || change.taskId === task.id))) throw Object.assign(new Error('当前没有已审查并应用、需要继续交付的任务改动。'), { status: 409 });
|
||||
const content = '本任务的改动已经审查并应用。请继续原始目标,识别并实际执行工程检查,依据失败日志修复,完成审查和交付说明。';
|
||||
return this.start(id, content, true, { instructionSource: 'review-action' });
|
||||
|
||||
+2
-2
@@ -167,5 +167,5 @@
|
||||
|
||||
1. [complete] 核对提案、SQLite/工件/Task、API/UI与升级边界;CHANGE-SETS.md明确封存指纹、Git/文件全批预检、逐文件写入账本及显式核对/回退,普通源码开发不新建研究worker。
|
||||
2. [complete] Task所属封存指纹、快照工件、整批预检与可恢复应用已实现,24/24专项通过,包含13个真实进程退出切点、格式/Git保留、owner修改和恢复临时文件保护。
|
||||
3. [in_progress] 模型准备工具和API已接入;继续桌面/390px统一审查、应用与恢复入口,以及交付报告批次证据。
|
||||
4. [pending] 完成相关回归和受控多文件实际任务,保存本地实现、独立发行验证并保留原进程更新。
|
||||
3. [complete] 模型/API、桌面/390px批次统一审查及报告已实现;step_limit续接和卸载后迟到错误归属已修复,141项完整回归与11组批次/43组原UI全部通过。
|
||||
4. [in_progress] 保存实现,验证独立便携/源码包及真实模型整批精确交付;完成后保留原进程更新和最终不可变发行,进入worktree与多类工程检查。
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fixture, launchWorkbench, until, compatibleFixture, call, completion, assertToolPairs } from './helpers.mjs';
|
||||
import { batchFixture, assertBatchBytes } from './fixtures/change-set-project.mjs';
|
||||
import { Runtime } from '../src/server/runtime.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
|
||||
test('batch APIs enforce ownership and review fingerprints, apply once, and persist the completed batch across restart', { timeout: 30000 }, async t => {
|
||||
const f = fixture(t), b = batchFixture(f); f.store.close();
|
||||
const host = await launchWorkbench(t, f.data), route = '/sessions/' + f.session.id;
|
||||
const first = await host.api(route + '/change-sets', { changeIds: b.ids }), set = first.execution.changeSets.at(-1);
|
||||
assert.equal((await host.api(route + '/change-sets', { changeIds: b.ids })).execution.changeSets.at(-1).id, set.id);
|
||||
assertBatchBytes(assert, f, b.before);
|
||||
await assert.rejects(host.api(route + '/change-sets/' + set.id + '/apply', {}), /指纹/);
|
||||
await assert.rejects(host.api(route + '/changes/' + b.ids[0] + '/apply', {}), /封存/);
|
||||
await assert.rejects(host.api(route + '/messages', { content: 'different task' }), /变更集/);
|
||||
const other = await host.api('/sessions', { projectId: f.project.id });
|
||||
await assert.rejects(host.api('/sessions/' + other.id + '/change-sets/' + set.id), /不属于/);
|
||||
await host.api(route + '/change-sets/' + set.id + '/apply', { fingerprint: set.fingerprint });
|
||||
let applied;
|
||||
await until(async () => { applied = await host.api(route); return applied.execution.changeSets.at(-1).status === 'completed'; });
|
||||
assertBatchBytes(assert, f, b.after);
|
||||
await assert.rejects(host.api(route + '/change-sets/' + set.id + '/apply', { fingerprint: set.fingerprint }), /重复应用/);
|
||||
await host.close();
|
||||
const restarted = await launchWorkbench(t, f.data), restored = await restarted.api(route);
|
||||
assert.deepEqual(restored.execution.changeSets, applied.execution.changeSets); assertBatchBytes(assert, f, b.after);
|
||||
});
|
||||
|
||||
test('delivery reports bind actual batch identity and reject corrupted snapshot evidence without changing project files', { timeout: 30000 }, async t => {
|
||||
const f = fixture(t), b = batchFixture(f), set = await b.manager.prepare(f.session, b.ids);
|
||||
await (await b.manager.start(f.session, set.id, set.fingerprint)).promise;
|
||||
const snapshot = f.store.owned('artifact', set.files[1].snapshotArtifactId, f.session.id), snapshotPath = path.join(f.store.artifactStore.root, snapshot.relative);
|
||||
f.store.close(); const host = await launchWorkbench(t, f.data), route = '/sessions/' + f.session.id;
|
||||
const valid = await host.api(route + '/delivery-reports', {}), jsonArtifact = valid.execution.artifacts.slice().reverse().find(item => item.kind === 'delivery-report');
|
||||
const preview = await host.api('/artifacts/' + jsonArtifact.id + '?session=' + f.session.id + '&limit=16000'), report = JSON.parse(preview.content);
|
||||
assert.equal(report.changeSets[0].id, set.id); assert.equal(report.changeSets[0].snapshotVerified, true);
|
||||
assert.ok(report.changes.every(change => change.changeSetId === set.id)); assert.equal(report.status, 'needs_checks');
|
||||
fs.writeFileSync(snapshotPath, 'Corrupt owned QA snapshot');
|
||||
const invalid = await host.api(route + '/delivery-reports', {}), artifact = invalid.execution.artifacts.slice().reverse().find(item => item.kind === 'delivery-report');
|
||||
const invalidReport = JSON.parse((await host.api('/artifacts/' + artifact.id + '?session=' + f.session.id + '&limit=16000')).content);
|
||||
assert.equal(invalidReport.status, 'needs_verification'); assert.equal(invalidReport.changeSets[0].snapshotVerified, false); assertBatchBytes(assert, f, b.after);
|
||||
});
|
||||
|
||||
test('a compatible model can seal proposals through the real HTTP loop while application stays behind user review', { timeout: 60000 }, async t => {
|
||||
const f = fixture(t); f.store.close(); let count = 0;
|
||||
const provider = await compatibleFixture(t, (url, input) => {
|
||||
if (!input?.messages) return { data: [{ id: 'fixture-model' }] };
|
||||
count++;
|
||||
if (count === 1) return completion([
|
||||
call('first-file', 'propose_file', { path: 'src/new.mjs', content: 'export const newValue = 1;\n', reason: '新增模块' }),
|
||||
call('second-file', 'propose_file', { path: 'docs/new.md', content: '# New\n', reason: '补充说明' }),
|
||||
], '准备两个文件提案。');
|
||||
if (count === 2) {
|
||||
const ids = input.messages.filter(message => message.role === 'tool').map(message => JSON.parse(message.content).change_id).filter(Boolean);
|
||||
return completion([call('seal-batch', 'prepare_change_set', { change_ids: ids })], '封存整批审查范围。');
|
||||
}
|
||||
return completion([], '文件批次已封存,等待用户审查应用。');
|
||||
});
|
||||
const host = await launchWorkbench(t, f.data);
|
||||
await host.api('/config', { mode: 'compatible', baseUrl: provider.baseUrl, model: 'fixture-model', apiKey: 'SYNTHETIC-QA-ONLY' });
|
||||
await host.api('/sessions/' + f.session.id + '/messages', { content: '创建两个文件并组合审查' });
|
||||
let session;
|
||||
await until(async () => { session = await host.api('/sessions/' + f.session.id); return session.status === 'needs_review'; }, 30000);
|
||||
assert.equal(session.execution.changeSets.length, 1); assert.equal(session.execution.changeSets[0].status, 'prepared');
|
||||
assert.equal(session.execution.changeSets[0].files.length, 2); assert.equal(fs.existsSync(path.join(f.projectRoot, 'src')), false);
|
||||
assert.equal(fs.existsSync(path.join(f.projectRoot, 'docs')), false);
|
||||
assert.equal(session.events.find(event => event.tool === 'prepare_change_set').phase, 'completed');
|
||||
const tools = provider.requests.find(request => request.input?.tools)?.input.tools.map(tool => tool.function.name);
|
||||
assert.ok(tools.includes('prepare_change_set')); assert.ok(!tools.includes('apply_change_set')); assert.ok(!tools.includes('rollback_change_set'));
|
||||
});
|
||||
|
||||
test('a step-limited sealed batch applies and continues the same Task into actual checks without replaying saved tools', { timeout: 60000 }, async t => {
|
||||
const f = fixture(t);
|
||||
fs.mkdirSync(path.join(f.projectRoot, 'test'));
|
||||
const acceptance = "import test from 'node:test'; import assert from 'node:assert/strict'; import { left } from '../src/left.mjs'; import { right } from '../src/right.mjs';\ntest('left value', () => assert.equal(left, 1)); test('right value', () => assert.equal(right, 2));\n";
|
||||
fs.writeFileSync(path.join(f.projectRoot, 'test/values.test.mjs'), acceptance);
|
||||
fs.writeFileSync(path.join(f.projectRoot, 'package.json'), JSON.stringify({ type: 'module', scripts: { test: 'node --test test/*.test.mjs' } }));
|
||||
f.store.close(); let count = 0;
|
||||
const model = await compatibleFixture(t, (url, input) => {
|
||||
if (!input?.messages) return { data: [{ id: 'batch-continuation-fixture' }] };
|
||||
count++;
|
||||
if (count === 1) return completion([
|
||||
call('paused-left', 'propose_file', { path: 'src/left.mjs', content: 'export const left = 1;\n', reason: '第一份受控模块' }),
|
||||
call('paused-right', 'propose_file', { path: 'src/right.mjs', content: 'export const right = 2;\n', reason: '第二份受控模块' }),
|
||||
]);
|
||||
const results = input.messages.filter(message => message.role === 'tool').map(message => JSON.parse(message.content));
|
||||
if (count === 2) return completion([call('paused-seal', 'prepare_change_set', { change_ids: results.map(result => result.change_id).filter(Boolean) })]);
|
||||
if (count === 3) return completion([call('continued-check-plan', 'plan_checks', { names: ['test'] })]);
|
||||
if (count === 4) return completion([call('continued-actual-check', 'run_checks', { plan_id: results.findLast(result => result.checks && result.fingerprint).id })]);
|
||||
return completion([], '原任务的两份文件已通过真实工程检查。');
|
||||
});
|
||||
const host = await launchWorkbench(t, f.data), route = '/sessions/' + f.session.id;
|
||||
await host.api('/config', { mode: 'compatible', baseUrl: model.baseUrl, model: 'batch-continuation-fixture', maxSteps: 2 });
|
||||
await host.api(route + '/messages', { content: '完成原始双模块工程目标并运行测试' });
|
||||
let paused;
|
||||
await until(async () => { paused = await host.api(route); return paused.status === 'paused'; }, 30000);
|
||||
assert.equal(paused.execution.run.stopReason, 'step_limit'); assert.equal(count, 2);
|
||||
const set = paused.execution.changeSets.at(-1), firstRun = structuredClone(paused.execution.run);
|
||||
assert.equal(set.status, 'prepared'); assert.equal(fs.existsSync(path.join(f.projectRoot, 'src')), false);
|
||||
const savedMessages = (await host.api(route + '/export')).session.providerMessages;
|
||||
const savedResults = savedMessages.filter(message => message.role === 'tool'); assert.equal(savedResults.length, 3);
|
||||
await assert.rejects(host.api(route + '/resume', {}), /变更集/);
|
||||
await assert.rejects(host.api(route + '/continue-reviewed', {}), { status: 409 });
|
||||
await host.api(route + '/change-sets/' + set.id + '/apply', { fingerprint: set.fingerprint });
|
||||
await until(async () => (await host.api(route)).execution.changeSets.at(-1).status === 'completed', 30000);
|
||||
await host.api('/config', { ...(await host.api('/bootstrap')).config, maxSteps: 5 });
|
||||
await host.api(route + '/continue-reviewed', {});
|
||||
let waiting;
|
||||
await until(async () => { waiting = await host.api(route); return waiting.approvals.some(approval => approval.status === 'pending'); }, 30000);
|
||||
await host.api(route + '/approvals/' + waiting.approvals.find(approval => approval.status === 'pending').id, { allow: true });
|
||||
let completed;
|
||||
await until(async () => { completed = await host.api(route); return completed.status === 'completed'; }, 30000);
|
||||
assert.equal(completed.execution.task.id, paused.execution.task.id);
|
||||
assert.equal(completed.execution.task.goal, '完成原始双模块工程目标并运行测试');
|
||||
assert.equal(completed.execution.run.resumeOf, firstRun.id); assert.equal(completed.execution.task.verification.status, 'passed');
|
||||
assert.equal(completed.execution.checks.length, 1); assert.equal(completed.execution.checks[0].results[0].tests.passed, 2);
|
||||
assert.equal(completed.execution.runs.find(run => run.id === firstRun.id).status, 'paused');
|
||||
assert.deepEqual(completed.execution.runs.find(run => run.id === firstRun.id).usage, firstRun.usage);
|
||||
assert.equal(completed.execution.changeSets[0].runId, firstRun.id); assert.equal(count, 5);
|
||||
const exported = (await host.api(route + '/export')).session.providerMessages;
|
||||
assert.deepEqual(exported.filter(message => message.role === 'tool').slice(0, 3), savedResults); assertToolPairs(exported);
|
||||
assert.equal(completed.events.filter(event => event.kind === 'tool' && ['propose_file', 'prepare_change_set'].includes(event.tool)).length, 3);
|
||||
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'test/values.test.mjs'), 'utf8'), acceptance);
|
||||
await assert.rejects(host.api(route + '/continue-reviewed', {}), { status: 409 });
|
||||
});
|
||||
|
||||
test('applied batches cannot turn cancellation, other budgets, restart or unknown commands into a review continuation', async t => {
|
||||
const f = fixture(t), b = batchFixture(f), set = await b.manager.prepare(f.session, b.ids);
|
||||
await (await b.manager.start(f.session, set.id, set.fingerprint)).promise;
|
||||
const runtime = new Runtime(f.store, new Provider()), run = f.store.core.run.get(f.session.runId);
|
||||
for (const reason of ['cancelled', 'time_limit', 'token_limit', 'task_token_limit', 'restart']) {
|
||||
run.status = 'paused'; run.stopReason = reason;
|
||||
const before = JSON.stringify(f.store.publicSession(f.session));
|
||||
assert.throws(() => runtime.continueReviewed(f.session.id), { status: 409 });
|
||||
assert.equal(JSON.stringify(f.store.publicSession(f.session)), before); assertBatchBytes(assert, f, b.after);
|
||||
}
|
||||
const invocation = call('unknown-command', 'run_command', { command: 'echo owned-fixture', reason: 'Unknown result must be reviewed' });
|
||||
const event = f.store.event(f.session, { kind: 'tool', tool: 'run_command', toolCallId: invocation.id, phase: 'running' });
|
||||
f.store.beginInvocation(f.session, invocation, run, event); f.store.invocationState(f.session, event, 'running');
|
||||
f.store.interruptPending(f.session, run); f.session.status = 'paused'; f.store.finishRun(f.session, run, 'step_limit');
|
||||
const before = JSON.stringify(f.store.publicSession(f.session));
|
||||
assert.equal(f.store.publicSession(f.session).execution.progress.requiresVerification.length, 1);
|
||||
assert.throws(() => runtime.continueReviewed(f.session.id), { status: 409 });
|
||||
assert.equal(JSON.stringify(f.store.publicSession(f.session)), before); assertBatchBytes(assert, f, b.after);
|
||||
});
|
||||
Reference in New Issue
Block a user