fix: keep artifact pages observable and pause repeated context reads

This commit is contained in:
Agent Workbench Dev
2026-10-29 21:50:53 +08:00
parent 3825142a68
commit 6e465a26d4
42 changed files with 520 additions and 30 deletions
+7
View File
@@ -1,5 +1,12 @@
# Agent Workbench 更新记录
## 1.5.1 · 2026-10-29
- 修复大工件结果因请求预算不足而再次被封存、模型无法看到刚读内容的问题:读取页按下一请求的实际JSON编码字节预算选择,返回next_offset、实际字符数及预算缩小标记;完整原工件保留。
- 历史选择优先保留直接代码及原执行工件依据,历史索引用于按需定位,减少不断读取更新索引的循环。
- 同Task持久记录不可变工件的已读区间;3次连续重复已覆盖区间或连续追逐6个新历史索引时明确no_progress暂停。新的区间/直接证据与显式续接有各自处理,重启不自动发送请求或重放工具。
- 手机上可查看重复读取原因并显式继续原Task。完整回归、包与失败样本续接结果分别保存到[验收记录](docs/VALIDATION.md),1.5.0的真实失败记录保留。
## 1.5.0 · 2026-10-29
- 长任务按完整工具调用/结果组选取上下文,原参数和历史保留;任务目标、全部追加要求及最后用户消息完整发送,超大历史通过SHA256工件分段读取。
+2 -2
View File
@@ -1,6 +1,6 @@
# 本地 Agent 工作台
Agent Workbench 1.5.0 将 Claude Code 与 Cursor 的机制研究整合为独立的本地 AI 编程工作台。工程索引、精确补丁、多文件整批审查、实际检查、本地Git提交及交付报告可以在同一个Task中完成。
Agent Workbench 1.5.1 将 Claude Code 与 Cursor 的机制研究整合为独立的本地 AI 编程工作台。工程索引、精确补丁、多文件整批审查、实际检查、本地Git提交及交付报告可以在同一个Task中完成。
每次运行保留模型与预算、已完成工具和日志工件。多文件变更集封存同Task的原/新字节、Git基线与审查指纹,应用前核对整批文件;中断后显式核对或回退,保留外部修改。应用改动后可点击「继续检查与交付」,沿用原目标进行实际测试与修复。提交前查看实际文件、diff、署名和检查结果,确认后生成本地提交及可下载的JSON/Markdown报告。版本改动见 [CHANGELOG](CHANGELOG.md),编辑范围见[索引与补丁](docs/CODE-INDEX-AND-PATCHES.md)和[变更集恢复契约](docs/CHANGE-SETS.md)。
@@ -62,7 +62,7 @@ Windows 终端使用 PowerShell 5.1,通过 UTF-8 stdin 传入经确认的完
- [统一机制报告](docs/RESEARCH.md):原版静态证据与本产品实现逐项对照。
- [详细报告与证据索引](docs/research):Claude Code 工具循环、上下文/恢复,以及 Cursor 工具执行/编辑。
- [验收记录](docs/VALIDATION.md):逐版本保留实际结果、失败与部署身份。
- [本轮验收清单](docs/QA-1.5.md)、[封存四模块工程基准](benchmarks/node-delivery-v1/README.md)与[保留连接的升级说明](docs/UPGRADE.md)。
- [本轮验收清单](docs/QA-1.5.1.md)、[封存四模块工程基准](benchmarks/node-delivery-v1/README.md)与[保留连接的升级说明](docs/UPGRADE.md)。
- [独立架构](docs/ARCHITECTURE.md)与[界面设计](DESIGN.md)。
原版研究没有执行 Claude Code/Cursor,报告不表示恢复了全部源码或验证了远端服务。完整分析工件保留在原研究工作区;本产品包不包含第三方客户端原二进制、完整提取源码或大体积代码切片。
+8
View File
@@ -23,3 +23,11 @@
覆盖单user回合的长Task、近期大小混合结果、Unicode、完整多工具配对、原参数和历史不变、目标和追加要求完整、固定开销/输出余量/Run和Task剩余预算、工件缺失/外部篡改、显式续接及实际进程重启。API/桌面/390px应能读取请求估算与实际用量、历史索引和工件;真实同题样本单独报告用量和人工介入。
本文件描述当前开发契约;实际完成/部署以VALIDATION.md为准。
## 1.5.1:读取预算与重复进展
1.5.0真实样本暴露较大工件页被整体封存的循环,失败记录保留。1.5.1的read_artifact按下一请求中工具消息的双层JSON字节预算生成实际读取页;默认2000字符,requested_limit与实际范围分别返回,next_offset指向下一段。UTF-16坐标按合法Unicode边界处理;分页不改写历史工具参数,原工件与SHA256保持。
请求计划优先选择近期直接代码/原结果组,并提供有界working_evidence定位。目标、追加要求和完整协议仍按原契约保留;不能容纳的原大结果仍整体封存,不宣称所有任意大小工具组都能进入模型窗口。
Task保存有界工件覆盖区间、重复次数和最近读取身份。连续3次读取已完整覆盖区间或连续追逐6个更新历史索引时,以no_progress暂停,所有已执行结果先保存并完成工具配对。读取新区间或取得直接证据会结束重复序列;显式续接清除暂停序列,保留已读证据与同Task身份。此检测针对工件读取,尚不是通用任务调度/语义无进展判断。
+9
View File
@@ -0,0 +1,9 @@
# 1.5.1 验收清单
本轮由[1.5真实失败](context-live-model-failure.json)驱动:较大的工件页在下一请求中被封存,模型反复读取同一片段。修复实际工具分页、直接依据保留和工件重复进展检测。
专项4/4读取测试及1项直接代码保留回归通过;原上下文/API/Runtime的25项针对性回归通过。专项包含实际本地HTTP中模型必须收到最新工件结果、完整Unicode重建、重复读取暂停、保存后重新打开不重放,以及显式续接同Task。
完整163/163项行为/API/实际退出/升级回归通过,0失败/跳过/取消,见[完整回归](context-fix-tests-validation.json)。基础10、诊断9、任务7、Git9、索引8、批次11及上下文9共63组界面通过,0页面/请求异常,见[界面总表](context-fix-all-ui-validation.json)。新增暂停用例最初误沿用桌面视口,已显式设置并验证390px后复验;手机查看原因、关闭任务抽屉及显式续接保持原Task。
便携/源码独立验收、保留原进程升级与同一个真实失败Task的续接随后登记。当前正式服务仍为1.5.0,不将待验收结果写为完成。
+8
View File
@@ -1,5 +1,13 @@
# Agent Workbench 验收记录
## 1.5.1 · 实际工件分页与重复读取暂停
构建、163/163项完整回归及63组界面全部通过,0失败/跳过/取消/页面或请求异常;见[回归](context-fix-tests-validation.json)、[界面总表](context-fix-all-ui-validation.json)和[QA-1.5.1](QA-1.5.1.md)。工件页按下一请求的双层JSON字节限额生成、返回next_offset;原工件、Unicode与完整协议保留。直接代码依据优先选择,Task已读区间和no_progress暂停持久保存,恢复不自动重放。
新增实际HTTP用例证明下一请求包含刚读取的大工件页,分页推进而不重复工具;重复已覆盖区间的实际循环以no_progress暂停,重新打开后保留原Task/已完成结果,显式续接才请求模型。手机用例检查实际390px宽度、可读原因和续接归属;第一次误用桌面截图的验证器已修正并重跑。
独立发行和同一真实失败Task续接正在执行,后续追加实际结果。1.5.0首轮失败证据保持,尚无同题多次对照的费用收益结论。
## 1.5.0 · 有界请求与完整历史
Windows x64、Node24.22.1、Edge156.0.4314.42。构建与158/158项行为/API/实际进程退出/升级回归通过,0失败/跳过/取消;上下文8、批次11及原有43共62组真实界面全部通过,0页面/请求异常。桌面与390px历史/工件截图已目视核对。
+38
View File
@@ -0,0 +1,38 @@
{
"success": true,
"version": "1.5.1",
"testedAt": "2026-10-29T13:47:45.452Z",
"count": 63,
"checks": [
{
"script": "verify-ui.mjs",
"passed": 10
},
{
"script": "verify-diagnostics-ui.mjs",
"passed": 9
},
{
"script": "verify-execution-ui.mjs",
"passed": 7
},
{
"script": "verify-delivery-ui.mjs",
"passed": 9
},
{
"script": "verify-index-ui.mjs",
"passed": 8
},
{
"script": "verify-change-sets-ui.mjs",
"passed": 11
},
{
"script": "verify-context-ui.mjs",
"passed": 9
}
],
"contextUiRecheckedAt": "2026-10-29T13:47:45.452Z",
"mobileReadPauseWidth": 390
}
+27
View File
@@ -0,0 +1,27 @@
{
"success": true,
"url": "http://127.0.0.1:52218",
"browser": "Microsoft Edge 156.0.4314.42",
"date": "2026-10-29T13:39:52.423Z",
"projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\ui-4e108dc4-3f09-4a10-8235-1d0125675aba\\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"
}
+29
View File
@@ -0,0 +1,29 @@
{
"success": true,
"version": "1.5.1",
"testedAt": "2026-10-29T13:42:38.074Z",
"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": [
"docs/screenshots/context-fix-batch-desktop-review.png",
"docs/screenshots/context-fix-batch-desktop-conflict.png",
"docs/screenshots/context-fix-batch-desktop-recovery.png",
"docs/screenshots/context-fix-batch-mobile-review.png",
"docs/screenshots/context-fix-batch-mobile-rollback.png"
],
"projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\batch-ui-261708de-6af0-40ff-ad0d-66e5b444cfa3",
"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."
}
@@ -0,0 +1,31 @@
{
"success": true,
"version": "1.5.1",
"testedAt": "2026-10-29T13:42:22.402Z",
"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-5b728005-4b5e-4f90-96ad-d21bb97c4efe\\四模块交付工程",
"projectId": "bc9f1b3a-0af3-4919-8a8e-6e736e6ae638",
"sessionId": "e6703858-6abd-40bb-a25f-76267efc3bec",
"taskId": "9d62894b-79d2-429f-a13e-b8e38c0cb036",
"commit": "657c040cdef31e810a75ee3f7668221a84ac16a4",
"recoveryCommit": "34836a8ffdbe75921a28d8523e073043e03d3cd2",
"testCounts": {
"baselineFailed": 13,
"passed": 14
},
"model": "controlled local HTTP fixture",
"confirmations": 2
}
@@ -0,0 +1,20 @@
{
"success": true,
"version": "1.5.1",
"url": "http://127.0.0.1:52218",
"date": "2026-10-29T13:40:38.565Z",
"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"
}
@@ -0,0 +1,19 @@
{
"success": true,
"version": "1.5.1",
"testedAt": "2026-10-29T13:41:30.900Z",
"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-db8cc267-eb38-49b5-ae45-693fbf088ca5\\project",
"model": "controlled local HTTP fixture"
}
+19
View File
@@ -0,0 +1,19 @@
{
"checkedAt": "2026-10-29T13:42:27.687Z",
"version": "1.5.1",
"passed": [
"工程索引可独立于任务使用,实际覆盖范围与损坏文件显示明确",
"真实AST查询打开原文件第181行并仅滚动代码容器,输入区和顶部保持可见",
"查询词保留;过期SHA不高亮旧位置,增量刷新后正确定位第184行",
"切换项目时延迟返回的旧索引不覆盖新项目结果",
"Python候选、字符串误报排除和局部导入文件候选保留真实证据标签",
"两处唯一锚点成为待审核提案,真实界面应用后BOM/CRLF和未选择原字节保留",
"390px索引查询、范围和完整指纹可读且无横向溢出,实际文件行定位通过",
"索引刷新失败保留归属和解释,旧结果禁用并可重试恢复"
],
"pageErrors": [],
"requestFailures": [],
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\index-ui-982c3cea-8762-4ac7-ab43-3328c8ef105f",
"primaryProjectId": "759b7254-d556-41dd-a529-05154762bc73",
"otherProjectId": "bf558c4e-768f-4ac1-a268-cb53f496283d"
}
+16
View File
@@ -0,0 +1,16 @@
{
"success": true,
"version": "1.5.1",
"testedAt": "2026-10-29T13:41:56.942Z",
"counts": {
"tests": 163,
"pass": 163,
"fail": 0,
"cancelled": 0,
"skipped": 0,
"todo": 0
},
"exitCode": 0,
"logFile": ".qa/context-full-tests.tap",
"testFiles": 19
}
+30
View File
@@ -0,0 +1,30 @@
{
"success": true,
"version": "1.5.1",
"testedAt": "2026-10-29T13:47:45.452Z",
"passed": [
"desktop request estimate, actual usage, complete goal and history identity are visible",
"paged complete history opens actual tool result artifacts without executing tools",
"historical and resumed Runs retain their own request records",
"390px history, original JSON and sent-body dialogs fit and retain close controls",
"late old history failure stays in its original scope after switching projects",
"late old Run failure stays in its original scope after switching projects",
"late old request-body failure stays in its original scope after switching projects",
"context-limit pause explains the intact requirement and explicit continuation",
"390px repeated-read pause explains the cause and explicit continuation retains the same Task"
],
"pageErrors": [],
"requestFailures": [],
"screenshots": [
"docs/screenshots/context-fix-desktop-plan.png",
"docs/screenshots/context-fix-desktop-history.png",
"docs/screenshots/context-fix-mobile-history.png",
"docs/screenshots/context-fix-mobile-original.png",
"docs/screenshots/context-fix-mobile-request-body.png",
"docs/screenshots/context-fix-mobile-read-pause.png"
],
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\context-ui-17d4e124-33a6-45cc-8004-ff58e3bad461",
"data": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\context-ui-17d4e124-33a6-45cc-8004-ff58e3bad461\\data",
"mode": "saved synthetic context evidence; no real model or project commands executed by this UI verifier",
"browser": "156.0.4314.42"
}
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: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

+6
View File
@@ -196,3 +196,9 @@ Claude Code 报告已验证工具输入校验、权限决定、队列并发屏
- 独立1.5源码离线安装、6份编译字节对照及158/158项回归全部通过。升级验收器首次读取export未携带既有接口控制令牌,返回HTTP403并在升级前停止,正式进程无变化;补齐bootstrap控制令牌后继续,未读取模型Key。
- 真实1.5模型失败根因:读取历史索引16000字符经JSON双层编码后超过当前硬输入预算,最新完整工具组被整体封存;后续计划始终保留同一组[0,2,12,13,14,15],模型看不到刚读取的片段,重复offset4000/5000。最终服务超时,27请求/249537已报告tokens、无提案。需要工具实际响应按当轮可用字节预算分页,让最新结果能发送;还需按不可变工件的已覆盖区间识别循环,并优先保留直接代码/检查依据。
- 1.5.1修复:真实工件页按下一请求中的双层JSON字节限额选择,保持Unicode与next_offset;完整工具参数/原工件保留。Task持久记录已读区间,3次连续重复或6个不断更新的索引触发no_progress暂停,显式续接保留原Task。相关原25项回归通过。首轮新测试3/4通过,HTTP fixture错把/v1/chat/completions当无效路径;诊断显示0实际fixture请求,已改按实际端点后缀核对。一次组合补丁误用Store的数据库import,校验拒绝且未写入,已拆分按实际源码完成。
- 冻结1.5.1完整163项回归与63组UI全部通过。目视发现新增mobile-read-pause截图实际为1440px:该用例沿用了迟到错误测试的桌面视口,标签不能作为手机证据。已显式切到390px、验证宽度/溢出,手机查看暂停原因后关闭任务抽屉再续接,重新独立跑9组上下文UI。
- 390px最终暂停截图已目视确认原因、运行下拉和关闭控件清晰;完整63组UI0页面/请求异常。一个只读路径误写tests/git-delivery.test.mjs,查询失败且无改动;rg实际定位为tests/delivery.test.mjs和delivery-recovery.test.mjs。
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "local-agent-workbench",
"version": "1.5.0",
"version": "1.5.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "local-agent-workbench",
"version": "1.5.0",
"version": "1.5.1",
"dependencies": {
"@babel/parser": "7.29.11",
"diff": "^8.0.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "local-agent-workbench",
"version": "1.5.0",
"version": "1.5.1",
"private": true,
"type": "module",
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
+4
View File
@@ -147,3 +147,7 @@
- 1.5最终158项回归及62组桌面/手机UI通过,原历史证据已隔离保存;桌面/390px上下文截图目视确认。公开说明、能力/路线和QA清单已更新为已实现范围与尚待发行实测的区别。检查diff并保存本地实现,随后不可变打包、独立源码验收及保留原进程升级。
- 1.5独立源码158/158回归、6份构建一致及便携2180/源码343份归档验证通过,原PID23080/连接和7项目9会话完整保留更新。真实模型首轮失败:27请求/249537tokens、358秒服务超时,无提案或源码/Git写入。工件读取偏大导致最新结果不能进入下一请求,连续重复索引/相同片段;原记录已单独封存。下一步优先1.5.1读取预算、当前修复依据和无进展检测,再接续已保存的工作区实现草稿。
- 1.5.1工件预算/Unicode分页、直接代码优先保留及Task已读范围/no_progress已实现;4项真实HTTP/重复暂停/重新打开/显式续接专项与1项优先选择验证通过。完整163项回归与63组UI进行中,现有独立UI基础10/诊断9已通过。正式1.5.0保持,等待相关检查后创建新包并续接原失败Task。
- 1.5.1冻结163/163完整回归和63组UI通过。390px新增暂停用例已显式复验并目视核对,查看原因/关闭抽屉/续接原Task可用;1.5.0历史证据保持。已准备只复用原失败工程和标准审核/检查/Git循环的续接验收器,不创建新Task、不重跑基线、不修改四源码之外文件;等待独立包验收与升级后执行。
+1 -1
View File
@@ -64,7 +64,7 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo
if (!fs.existsSync(originalScript) || !fs.existsSync(upgradeScript) || !fs.existsSync(path.join(next, 'dist-client', 'index.html'))) throw new Error('Upgrade bundles are incomplete.');
if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error('Invalid target process.');
const before = await readUpgradeJson(origin + '/api/bootstrap', 5000, 'Read original Workbench');
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1'].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 = [];
+3 -3
View File
@@ -33,9 +33,9 @@ child.stdout.on('data', value => { output += value; for (const line of output.sp
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.ok(['1.4.0', '1.5.0'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const proofPrefix = bootstrap.version === '1.4.0' ? 'm2-batch' : 'context-batch';
const screenshotPrefix = bootstrap.version === '1.4.0' ? '1.4-batch' : 'context-batch';
assert.ok(['1.4.0', '1.5.0', '1.5.1'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const proofPrefix = bootstrap.version === '1.4.0' ? 'm2-batch' : bootstrap.version === '1.5.0' ? 'context-batch' : 'context-fix-batch';
const screenshotPrefix = bootstrap.version === '1.4.0' ? '1.4-batch' : proofPrefix;
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 } });
+23 -8
View File
@@ -12,16 +12,17 @@ import { call } from '../tests/helpers.mjs';
const root = path.resolve('.qa', 'context-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 ['long', 'other', 'paused']) {
for (const name of ['long', 'other', 'paused', 'paused-repeat']) {
const projectRoot = path.join(root, 'context-' + name); fs.mkdirSync(projectRoot);
fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Owned context UI fixture\n');
const project = store.addProject(projectRoot), session = store.createSession(project.id, '上下文验收 ' + name);
const goal = '这是独立界面验收样本。完整任务要求与实际原记录保留,读取工件不得重新执行工具。';
store.message(session, 'user', goal); session.providerMessages.push({ role: 'user', content: goal });
const run = store.beginRun(session, goal, false, store.config), planner = new RequestPlanner(store);
if (name === 'paused') {
session.status = 'paused'; store.message(session, 'system', '完整任务要求超过请求上下文预算,请核对配置后继续。');
store.finishRun(session, run, 'context_limit'); cases[name] = { project, session, projectRoot, runs: [run.id] }; continue;
if (name === 'paused' || name === 'paused-repeat') {
session.status = 'paused'; store.message(session, 'system', name === 'paused' ? '完整任务要求超过请求上下文预算,请核对配置后继续。' : '模型重复读取已覆盖工件区间,原任务已暂停,请核对后继续。');
if (name === 'paused-repeat') store.core.task.get(run.taskId).readProgress = { schemaVersion: 1, reads: [], repeated: 3, changingIndexes: [], warning: '重复读取已覆盖区间', pause: true };
store.finishRun(session, run, name === 'paused' ? 'context_limit' : 'no_progress'); cases[name] = { project, session, projectRoot, runs: [run.id] }; continue;
}
if (name === 'long') for (let index = 0; index < 18; index++) {
const tool = call('ui-original-' + index, 'read_file', { path: 'README.md', fixture: 'Preserve exact historical JSON.' });
@@ -59,8 +60,9 @@ child.stderr.on('data', bytes => { errors += bytes.toString('utf8'); });
const until = async predicate => { const deadline = Date.now() + 20000; while (!await predicate()) { if (Date.now() > deadline) throw new Error('Context UI fixture timeout: ' + errors); await new Promise(resolve => setTimeout(resolve, 40)); } };
await until(() => url || child.exitCode !== null); assert.ok(url, errors);
const bootstrap = await (await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' } })).json();
assert.equal(bootstrap.version, '1.5.0'); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
assert.ok(['1.5.0', '1.5.1'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const api = async route => { const response = await fetch(url + '/api' + route, { headers: { 'X-Workbench-Token': bootstrap.token, Connection: 'close' } }); const value = await response.json(); assert.ok(response.ok, value.error); return value; };
const proofPrefix = bootstrap.version === '1.5.0' ? 'context' : 'context-fix';
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));
@@ -68,7 +70,7 @@ page.on('requestfailed', request => { if (request.resourceType() !== 'eventsourc
const mark = value => { passed.push(value); console.log('PASS ' + value); };
const panel = () => page.getByLabel('请求上下文', { exact: true }), history = () => page.getByRole('dialog', { name: '完整历史记录', exact: true });
async function screenshot(name) {
const file = '.qa/screenshots/context-' + name + '.png'; await page.screenshot({ path: file, fullPage: true }); screenshots.push(file);
const file = '.qa/screenshots/' + proofPrefix + '-' + name + '.png'; await page.screenshot({ path: file, fullPage: true }); screenshots.push(file);
}
async function choose(name) {
const select = page.getByLabel('当前项目', { exact: true });
@@ -132,13 +134,26 @@ try {
await lateFailure('**/artifacts/' + currentPlan.requestArtifactId + '?*', () => panel().getByRole('button', { name: '查看发送内容', exact: true }).click(), 'late old request-body failure');
await choose('paused'); await expect(page.locator('.run-stop')).toContainText('完整任务要求超过请求上下文预算');
await expect(page.getByRole('button', { name: '继续任务', exact: true })).toBeVisible(); mark('context-limit pause explains the intact requirement and explicit continuation');
await page.setViewportSize({ width: 390, height: 844 });
await choose('paused-repeat'); await expect(page.locator('.run-stop')).toContainText('重复读取未推进任务');
await page.locator('.run-stop').scrollIntoViewIfNeeded();
assert.equal(await page.evaluate(() => window.innerWidth), 390);
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 2));
await screenshot('mobile-read-pause');
await page.keyboard.press('Escape'); await expect(page.getByRole('button', { name: '继续任务', exact: true })).toBeVisible();
const pausedTaskId = (await api('/sessions/' + cases['paused-repeat'].session.id)).execution.task.id;
await page.getByRole('button', { name: '继续任务', exact: true }).click();
await until(async () => (await api('/sessions/' + cases['paused-repeat'].session.id)).execution.runs.length === 2);
const resumed = await api('/sessions/' + cases['paused-repeat'].session.id);
assert.equal(resumed.execution.task.id, pausedTaskId); assert.equal(resumed.execution.run.resumeOf, cases['paused-repeat'].runs[0]);
mark('390px repeated-read pause explains the cause and explicit continuation retains the same Task');
assert.deepEqual(pageErrors, []); assert.deepEqual(requestFailures, []);
const result = { success: true, version: bootstrap.version, testedAt: new Date().toISOString(), passed, pageErrors, requestFailures, screenshots, root, data,
mode: 'saved synthetic context evidence; no real model or project commands executed by this UI verifier', browser: browser.version() };
fs.writeFileSync('.qa/context-ui-validation.json', JSON.stringify(result, null, 2) + '\n'); console.log(JSON.stringify(result, null, 2));
fs.writeFileSync('.qa/' + proofPrefix + '-ui-validation.json', JSON.stringify(result, null, 2) + '\n'); console.log(JSON.stringify(result, null, 2));
} catch (error) {
await screenshot('failure').catch(() => {});
fs.writeFileSync('.qa/context-ui-validation.json', JSON.stringify({ success: false, version: bootstrap.version, passed, pageErrors, requestFailures, error: error.message, screenshots }, null, 2) + '\n');
fs.writeFileSync('.qa/' + proofPrefix + '-ui-validation.json', JSON.stringify({ success: false, version: bootstrap.version, passed, pageErrors, requestFailures, error: error.message, screenshots }, null, 2) + '\n');
throw error;
} finally {
await browser.close();
+1 -1
View File
@@ -7,7 +7,7 @@ import { DeliveryPanel } from './DeliveryPanel';
import { RequestContextPanel } from './RequestContextPanel';
import './TaskPanel.css';
const stopReasons: Record<string, string> = { context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
const stopReasons: Record<string, string> = { no_progress: '重复读取未推进任务,请核对后继续', context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
const number = (value: number | undefined) => (value ?? 0).toLocaleString('zh-CN');
const time = (value: string | null | undefined) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '执行中';
+64
View File
@@ -0,0 +1,64 @@
import { createHash } from 'node:crypto';
const messageBytes = (result, callId) => Buffer.byteLength(JSON.stringify({ role: 'tool', tool_call_id: callId, content: JSON.stringify(result) }), 'utf8');
const boundary = (text, end) => end > 0 && end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]) ? end - 1 : end;
// This is the actual tool page, not a rewrite of a historical result. Count
// the escaped JSON tool message which will be present in the next request.
export function artifactPage(artifact, text, args, { maximumMessageBytes = 16000, callId = '' } = {}) {
const requestedOffset = args.offset ?? 0, requestedLimit = args.limit ?? 2000;
let offset = Math.min(requestedOffset, text.length);
if (offset > 0 && /[\uDC00-\uDFFF]/.test(text[offset]) && /[\uD800-\uDBFF]/.test(text[offset - 1])) offset--;
let maximumEnd = boundary(text, Math.min(offset + requestedLimit, text.length));
if (maximumEnd === offset && offset < text.length) maximumEnd = boundary(text, Math.min(offset + 2, text.length));
const make = end => ({ artifact_id: artifact.id, kind: artifact.kind, sha256: artifact.sha256,
content: text.slice(offset, end), offset, next_offset: end, returned_characters: end - offset,
total_characters: text.length, truncated: end < text.length, requested_offset: requestedOffset, requested_limit: requestedLimit,
budget_limited: end < maximumEnd, maximum_message_bytes: maximumMessageBytes });
let low = offset, high = maximumEnd;
if (messageBytes(make(low), callId) > maximumMessageBytes) throw new Error('当前请求预算无法容纳工件读取元数据,请先核对任务预算。');
while (low < high) {
const middle = Math.ceil((low + high) / 2), end = boundary(text, middle);
if (messageBytes(make(end), callId) <= maximumMessageBytes) low = middle; else high = middle - 1;
}
const end = boundary(text, low), result = make(end);
if (offset < maximumEnd && end <= offset) throw new Error('当前请求预算无法容纳下一个完整字符,请先核对任务预算。');
return result;
}
export function readMessageBudget(plan, message) {
const calls = message.tool_calls?.length ?? 1;
const assistantTokens = Math.ceil(Buffer.byteLength(JSON.stringify(message), 'utf8') / 3) + 8;
// Reserve space for the current call's framing and the next state/notice.
const tokens = plan.budget.inputBudget - plan.mandatoryInputTokens - assistantTokens - calls * 8 - 512;
return Math.max(1024, Math.floor(tokens * 3 / calls));
}
export function recordArtifactRead(task, artifact, result, invocationId) {
const progress = task.readProgress ??= { schemaVersion: 1, reads: [], repeated: 0, changingIndexes: [], warning: null, pause: false };
const identity = artifact.id + ':' + artifact.sha256, start = result.offset, end = result.next_offset;
let read = progress.reads.find(value => value.identity === identity);
if (!read) { read = { identity, ranges: [] }; progress.reads.push(read); if (progress.reads.length > 128) progress.reads.shift(); }
const covered = read.ranges.some(range => start >= range[0] && end <= range[1]);
progress.repeated = covered ? progress.repeated + 1 : 0;
if (!covered) {
const ranges = [...read.ranges, [start, end]].sort((a, b) => a[0] - b[0]), merged = [];
for (const range of ranges) { const previous = merged.at(-1); if (previous && range[0] <= previous[1]) previous[1] = Math.max(previous[1], range[1]); else merged.push(range); }
read.ranges = merged.slice(-64);
}
if (artifact.kind === 'context-history-index') {
if (!progress.changingIndexes.includes(identity)) progress.changingIndexes.push(identity);
progress.changingIndexes = progress.changingIndexes.slice(-8);
} else progress.changingIndexes = [];
progress.warning = progress.repeated >= 1 ? '刚才读取的工件区间已完整读取,请使用已返回内容,或按next_offset读取新的区间。'
: progress.changingIndexes.length >= 3 ? '连续读取更新的历史索引没有推进工程;请直接读取实际结果或项目文件,依据已有信息继续任务。' : null;
progress.pause = progress.repeated >= 3 || progress.changingIndexes.length >= 6;
progress.last = { artifactId: artifact.id, sha256: artifact.sha256, offset: start, nextOffset: end, invocationId,
contentSha256: createHash('sha256').update(result.content, 'utf8').digest('hex') };
return progress;
}
export function clearReadStreak(task) {
if (!task.readProgress) return;
task.readProgress.repeated = 0; task.readProgress.changingIndexes = []; task.readProgress.warning = null; task.readProgress.pause = false;
}
+25 -6
View File
@@ -74,7 +74,10 @@ function describe(group, ledger, artifacts) {
const assistant = group.messages[0], tools = (assistant.tool_calls ?? []).map(call => {
const result = group.messages.find(message => message.role === 'tool' && message.tool_call_id === call.id);
const invocation = ledger.get(call.id), artifact = artifacts.get(invocation?.resultArtifactId);
return { call_id: call.id, name: call.function.name, result: compactResult(result),
let input = {}; try { const args = JSON.parse(call.function.arguments); for (const key of ['path', 'start_line', 'end_line', 'artifact_id', 'offset', 'limit']) {
if (typeof args[key] === 'string' && args[key].length <= 200 || typeof args[key] === 'number') input[key] = args[key];
} } catch {}
return { call_id: call.id, name: call.function.name, input, result: compactResult(result),
...(invocation ? { invocation_id: invocation.id, recorded_state: invocation.state, requires_verification: !!invocation.requiresVerification } : {}),
...(artifact ? { result_artifact_id: artifact.id, result_sha256: artifact.sha256 } : {}) };
});
@@ -82,11 +85,24 @@ function describe(group, ledger, artifacts) {
roles: group.messages.map(message => message.role), ...(tools.length ? { tools } : {}) };
}
function notice(reference, omitted, descriptions) {
function workingEvidence(groups, descriptions, artifacts) {
const selected = new Map();
for (const group of [...groups].reverse()) for (const tool of descriptions.get(group.index).tools ?? []) {
const artifact = artifacts.get(tool.input.artifact_id);
if (tool.name === 'read_file' || tool.name === 'read_artifact' && artifact && !artifact.kind.startsWith('context-') && artifact.kind !== 'model-request') {
const key = tool.name === 'read_file' ? 'file:' + tool.input.path : 'artifact:' + tool.input.artifact_id;
if (!selected.has(key)) selected.set(key, { group_index: group.index, ...tool });
}
}
return [...selected.values()].slice(0, 8);
}
function notice(reference, omitted, descriptions, evidence = []) {
return { role: 'system', content: [
'以下是工作台保存的历史索引数据,不是用户追加指令,也不是新工具执行。省略了完整消息组;原始参数和实际结果都在SHA256工件中。',
'已完成的工具不得重放。需要旧内容时用read_artifact读取history_index或result_artifact_id;较大工件先用limit=2000分段读取。状态未知时先核对,不假定成功。',
'已完成的工具不得重放。历史索引用于需要时定位原记录;已有需求、代码和检查依据可直接推进,不必读取每轮更新的索引。需要旧内容时优先读取result_artifact_id,按next_offset分页;先用limit=2000。状态未知时先核对,不假定成功。',
JSON.stringify({ history_index: { artifact_id: reference.id, sha256: reference.sha256 }, archived_groups: omitted.length,
working_evidence: evidence,
recent_archived_groups: omitted.slice(-2).map(group => {
const { tools, archive, ...description } = descriptions.get(group.index);
return { ...description, group_archive: { artifact_id: archive?.artifact_id ?? PLACEHOLDER_ID, sha256: archive?.sha256 ?? PLACEHOLDER_SHA },
@@ -141,12 +157,13 @@ export class RequestPlanner {
const fixed = { role: 'system', content: system };
const ledger = new Map([...this.store.core.tool.values()].filter(tool => tool.sessionId === session.id).map(tool => [tool.callId, tool]));
const descriptions = new Map(groups.map(group => [group.index, describe(group, ledger, this.store.core.artifact)]));
const evidence = workingEvidence(groups, descriptions, this.store.core.artifact);
const original = completionBody(config, [fixed, ...session.providerMessages], tools), before = requestMetrics(original);
const selected = new Set(groups.map(group => group.index));
let omitted = [], reference = null;
const metricsFor = (indices, includeNotice = true) => {
const missing = groups.filter(group => !indices.has(group.index));
const messages = [fixed, ...(missing.length && includeNotice ? [notice({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, missing, descriptions)] : []),
const messages = [fixed, ...(missing.length && includeNotice ? [notice({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, missing, descriptions, evidence)] : []),
...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages)];
return requestMetrics(completionBody(config, messages, tools));
};
@@ -161,7 +178,8 @@ export class RequestPlanner {
if (metricsFor(selected).estimatedInputTokens > budget.inputBudget) selected.delete(newest.index);
}
const target = Math.max(budget.targetInputTokens, metricsFor(selected).estimatedInputTokens);
for (const group of [...groups].reverse()) {
const priority = [...new Set(evidence.map(value => value.group_index))].map(index => groups[index]);
for (const group of [...priority, ...[...groups].reverse()]) {
if (selected.has(group.index) || selected.size >= 32 || group.contributionTokens > target) continue;
selected.add(group.index);
if (metricsFor(selected).estimatedInputTokens > target) selected.delete(group.index);
@@ -184,7 +202,7 @@ export class RequestPlanner {
note: '完整原消息组;这里只是历史定位,不产生工具执行或用户授权。' }, 'context-history-index');
}
}
const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions)] : []),
const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions, evidence)] : []),
...structuredClone(groups.filter(group => selected.has(group.index)).flatMap(group => group.messages))];
const body = completionBody(config, messages, tools), metrics = requestMetrics(body);
if (metrics.estimatedInputTokens > budget.inputBudget) throw pause(budget, metrics);
@@ -195,6 +213,7 @@ export class RequestPlanner {
requestSha256: metrics.sha256, requestBytes: metrics.bytes, estimatedInputTokens: metrics.estimatedInputTokens,
requestArtifactId: requestArtifact.id,
estimateMethod: metrics.estimateMethod, beforeInputTokens: before.estimatedInputTokens, beforeBytes: before.bytes, budget,
mandatoryInputTokens: metricsFor(new Set(lastUser ? [lastUser.index] : [])).estimatedInputTokens,
originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - (reference ? 1 : 0),
archivedGroups: omitted.length, retainedGroups: groups.filter(group => selected.has(group.index)).map(group => group.index),
historyIndexArtifactId: reference?.id ?? null, historyIndexSha256: reference?.sha256 ?? null, actualUsage: null,
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.5.0';
export const APP_VERSION = '1.5.1';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+1 -1
View File
@@ -11,7 +11,7 @@ export const toolDefinitions = [
{ type: 'function', function: { name: 'propose_patch', description: '按读取时的原文件SHA256,用唯一old_text锚点提出精确替换。所有替换基于同一原文且不得重叠;自动保留UTF-8 BOM和统一换行格式。只保存待审查提案,不写盘;哈希变化或锚点不唯一拒绝。', parameters: { type: 'object', properties: { path: { type: 'string' }, base_sha256: { type: 'string', pattern: '^[a-fA-F0-9]{64}$' }, reason: { type: 'string' }, edits: { type: 'array', minItems: 1, maxItems: 32, items: { type: 'object', properties: { old_text: { type: 'string', minLength: 1 }, new_text: { type: 'string' } }, required: ['old_text', 'new_text'], additionalProperties: false } } }, required: ['path', 'base_sha256', 'reason', 'edits'] } } },
{ type: 'function', function: { name: 'plan_delivery', description: '为当前Task已经审核应用且实际检查通过的文件准备只读Git提交预览,保留其他暂存与工作区修改。只返回计划、路径、diff工件和署名,不提交;用户须在任务记录界面核对并确认。', parameters: { type: 'object', properties: { message: { type: 'string', maxLength: 1600, description: '本次本地提交说明;可省略并采用任务目标。' } } } } },
{ type: 'function', function: { name: 'delivery_report', description: '从当前Task的源码指纹、实际检查、提交和Run用量生成JSON/Markdown证据报告工件,不执行项目命令。报告注明未检查/待审核/结果未知和业务需求未验收;运行中的报告为阶段快照。', parameters: { type: 'object', properties: {} } } },
{ type: 'function', function: { name: 'read_artifact', description: '读取当前会话保存的实际执行工件或检查日志,按artifact_id校验归属和SHA256。可按offset/limit分段读取;每次最多16000字符。依据失败日志修复时使用,不重新执行检查。', parameters: { type: 'object', properties: { artifact_id: { type: 'string' }, offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 } }, required: ['artifact_id'] } } },
{ type: 'function', function: { name: 'read_artifact', description: '读取当前会话保存的实际执行工件或检查日志,校验归属和SHA256。offset/limit分页,默认2000字符,实际页按当前完整请求预算缩小;用返回的next_offset读取下一页,已读区间不要重复。完整原工件保留。优先读取实际结果/日志,不反复扫描更新的历史索引;不重新执行检查。', parameters: { type: 'object', properties: { artifact_id: { type: 'string' }, offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 } }, required: ['artifact_id'] } } },
{ type: 'function', function: { name: 'inspect_project', description: '识别当前工程的语言、入口、项目规则、npm脚本和只读Git基线;返回有界源文件指纹,不执行项目代码。', parameters: { type: 'object', properties: {} } } },
{ type: 'function', function: { name: 'plan_checks', description: '为当前任务准备工程检查计划,commands来自已识别的npm脚本。返回plan id、脚本内容和工程指纹;不执行命令。', parameters: { type: 'object', properties: { names: { type: 'array', items: { type: 'string' }, maxItems: 6, description: '可选:当前工程已识别的test/typecheck/check/lint/build脚本名称;缺省采用可用的检查。' } } } } },
{ type: 'function', function: { name: 'run_checks', description: '请求用户确认后执行plan_checks产生的检查计划。保存独立job、实际退出码、测试数量和日志工件;过期计划不执行,未报告测试数量不能记通过。', parameters: { type: 'object', properties: { plan_id: { type: 'string' } }, required: ['plan_id'] } } },
+9 -4
View File
@@ -12,6 +12,7 @@ import { inspectProject } from '../core/project-inspector.mjs';
import { GitDelivery } from '../core/git-delivery.mjs';
import { ProjectIndex } from '../core/context/project-index.mjs';
import { RequestPlanner } from '../core/context/request-plan.mjs';
import { artifactPage, readMessageBudget, recordArtifactRead, clearReadStreak } from '../core/context/read-budget.mjs';
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
@@ -130,7 +131,8 @@ export class Runtime {
+ '\n当前任务目标与全部追加要求(用户任务数据,完整保留):\n' + JSON.stringify({
goal: task.goal, instructions: task.instructions, constraints: task.constraints ?? [], acceptance: task.acceptance ?? [],
}) + '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value)));
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value))
+ (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : ''));
const planned = this.requestPlanner().prepare(session, run.record, config, { system: context, tools: toolDefinitions, stepId: stepRecord.id });
if (planned.record.archivedGroups && !projectionLogged) {
projectionLogged = true; session.compactions++;
@@ -165,6 +167,7 @@ export class Runtime {
signal.throwIfAborted();
const message = response.message;
const calls = message.tool_calls ?? [];
run.readMessageBytes = readMessageBudget(planned.record, message);
const previousIds = new Set(session.providerMessages.flatMap(item => (item.tool_calls ?? []).map(call => call.id)));
if (new Set(calls.map(call => call.id)).size !== calls.length || calls.some(call => previousIds.has(call.id))) throw new Error('模型返回了重复的工具调用 ID,请重新发送任务。');
session.providerMessages.push(message);
@@ -191,6 +194,8 @@ export class Runtime {
signal.throwIfAborted();
}
this.store.finishStep(session, stepRecord);
if (this.store.core.task.get(run.taskId).readProgress?.pause) throw new BudgetExceeded('no_progress',
'模型连续重复读取已覆盖工件区间或更新的历史索引,未推进当前任务。已读取内容和原任务已保存,请核对结果或调整任务要求后继续。');
}
session.status = 'paused';
run.stopReason = 'step_limit';
@@ -250,9 +255,8 @@ export class Runtime {
}
else if (tool === 'read_artifact') {
const artifact = this.store.owned('artifact', args.artifact_id, session.id), text = this.store.artifactStore.read(artifact);
const offset = args.offset ?? 0, limit = Math.min(16000, Math.max(1, args.limit ?? 8000));
result = { artifact_id: artifact.id, kind: artifact.kind, sha256: artifact.sha256, content: text.slice(offset, offset + limit), offset,
total_characters: text.length, truncated: offset + limit < text.length };
result = artifactPage(artifact, text, args, { callId: call.id, maximumMessageBytes: run.readMessageBytes ?? 16000 });
recordArtifactRead(this.store.core.task.get(run.taskId), artifact, result, event.invocationId);
}
else if (tool === 'prepare_change_set') {
const set = await this.changeSetManager().prepare(session, args.change_ids, { source: 'agent' });
@@ -294,6 +298,7 @@ export class Runtime {
else if (tool === 'run_command') result = await this.requestCommand(session, event, args, run);
else throw new Error('当前能力表没有工具:' + tool);
event.phase = ['denied', 'interrupted', 'unknown', 'unverified', 'stale'].includes(result.status) ? result.status : result.status === 'failed' ? 'failed' : 'completed';
if (tool !== 'read_artifact' && !['error', 'interrupted', 'unknown', 'denied'].includes(result.status)) clearReadStreak(this.store.core.task.get(run.taskId));
if (typeof result.stdout === 'string') { result.stdout = this.provider.redact(result.stdout); result.stderr = this.provider.redact(result.stderr ?? ''); }
event.output = this.provider.redact(typeof result.stdout === 'string' ? result.stdout + (result.stderr ? '\n' + result.stderr : '') : JSON.stringify(result).slice(0, 16000));
if (result.exit_code !== undefined) event.exitCode = result.exit_code;
+3
View File
@@ -337,6 +337,9 @@ export class Store extends EventEmitter {
const goal = content || session.messages.find(message => message.role === 'user')?.content || session.title;
task = createTask(session, goal, config, previous); this.core.task.set(task.id, task);
} else if (content && (!resume || instructionSource)) task.instructions.push({ id: randomUUID(), content, createdAt: now(), ...(instructionSource ? { source: instructionSource } : {}) });
if (task.readProgress) {
task.readProgress.repeated = 0; task.readProgress.changingIndexes = []; task.readProgress.warning = null; task.readProgress.pause = false;
}
const run = createRun(session, task, config, resume ? previousRunId : null);
this.core.run.set(run.id, run); task.activeRunId = run.id;
session.taskId = task.id; session.runId = run.id; session.status = 'running';
+7
View File
@@ -178,3 +178,10 @@
2. [in_progress] 单长Task、多语言/大结果、完整协议、续接/实际退出及归属验证通过,158项完整回归和62组桌面/手机界面通过;请求/原历史/深度校验报告已接入。继续独立不可变1.5包、原PID升级和真实配置模型验证。
3. [pending] 封存已提交HEAD、独立命名分支/worktree、持久准备/核对记录和稳定项目身份;保留原HEAD/index/用户改动,不隐式执行hooks或内容过滤器。
4. [pending] 继续React/TypeScript与Python工程检查,以及证据绑定的REA/Codex/DeepSeek适配和有界Purge实验;只将实测通过的切片标已实现。
## 真实工件循环修复(1.5.1,当前优先)
1. [complete] 1.5独立包/源码158项回归与保留原PID升级完成;真实首轮27请求/249537tokens、358秒超时、无提案的失败已封存,定位最新大页未进入请求的循环。
2. [complete] 工件页按双层JSON预算/Unicode边界/next_offset返回,直接代码依据优先选择;Task持久已读区间及no_progress暂停,专项4项和1项优先选择回归通过。
3. [in_progress] 完整163项回归、63组UI、独立发行与原PID升级;继续原真实失败Task,核对新请求及全部历史/源码/检查/Git证据。
4. [pending] 接续.qa中已保存的独立Git/worktree创建/核对草稿,按实际原工作区保护、退出恢复与桌面/手机流程完成内置能力。
+92
View File
@@ -0,0 +1,92 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { randomUUID, createHash } from 'node:crypto';
import { artifactPage, recordArtifactRead, clearReadStreak } from '../src/core/context/read-budget.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Store } from '../src/server/store.mjs';
import { fixture, compatibleFixture, call, completion, until, assertToolPairs } from './helpers.mjs';
const sha = text => createHash('sha256').update(text, 'utf8').digest('hex');
const bytes = (page, id) => Buffer.byteLength(JSON.stringify({ role: 'tool', tool_call_id: id, content: JSON.stringify(page) }), 'utf8');
test('budgeted artifact pages count escaped protocol bytes and reconstruct original multilingual JSON without losing characters', () => {
const text = JSON.stringify({ source: '原文🙂\r\n"\\'.repeat(4000) }), artifact = { id: randomUUID(), sha256: sha(text), kind: 'tool-result' };
let offset = 0, reconstructed = '', pages = 0;
while (offset < text.length) {
const page = artifactPage(artifact, text, { offset, limit: 16000 }, { maximumMessageBytes: 7000, callId: 'literal-read' });
assert.ok(bytes(page, 'literal-read') <= 7000); assert.ok(page.next_offset > offset); assert.equal(page.offset, offset);
assert.equal(page.content, text.slice(offset, page.next_offset)); assert.equal(page.truncated, page.next_offset < text.length);
assert.ok(!/[\uD800-\uDBFF]$/.test(page.content)); reconstructed += page.content; offset = page.next_offset; pages++;
}
assert.ok(pages > 5); assert.equal(reconstructed, text); assert.equal(sha(reconstructed), artifact.sha256);
const unicode = artifactPage({ ...artifact, sha256: sha('🙂雪') }, '🙂雪', { offset: 1, limit: 1 }, { maximumMessageBytes: 1200 });
assert.equal(unicode.offset, 0); assert.equal(unicode.content, '🙂'); assert.equal(unicode.next_offset, 2);
});
test('known artifact coverage detects semantic repeats despite changing limits, and advancing pages or direct evidence restore progress', () => {
const task = {}, text = 'Immutable engineering evidence\n'.repeat(30), artifact = { id: randomUUID(), kind: 'check-log', sha256: sha(text) };
const page = artifactPage(artifact, text, { offset: 0, limit: 200 }, { maximumMessageBytes: 2000 });
recordArtifactRead(task, artifact, page, 'first');
for (const limit of [100, 150, 180]) recordArtifactRead(task, artifact,
artifactPage(artifact, text, { offset: 0, limit }, { maximumMessageBytes: 2000 }), 'repeat-' + limit);
assert.equal(task.readProgress.pause, true); assert.equal(task.readProgress.repeated, 3);
recordArtifactRead(task, artifact, artifactPage(artifact, text, { offset: 200, limit: 200 }, { maximumMessageBytes: 2000 }), 'next');
assert.equal(task.readProgress.pause, false); assert.deepEqual(task.readProgress.reads[0].ranges, [[0, 400]]);
for (let index = 0; index < 6; index++) recordArtifactRead(task, { ...artifact, id: randomUUID(), kind: 'context-history-index' }, page, 'index-' + index);
assert.equal(task.readProgress.pause, true); clearReadStreak(task);
assert.equal(task.readProgress.pause, false); assert.equal(task.readProgress.reads[0].identity, artifact.id + ':' + artifact.sha256);
});
test('actual large artifact reads are present in the next bounded HTTP request and next_offset progresses without redoing tools', async t => {
const f = fixture(t), original = JSON.stringify({ log: '真实证据🙂\n"\\'.repeat(2200) });
const artifact = f.store.artifactStore.write(f.session, null, original, { kind: 'check-log' });
f.store.core.artifact.set(artifact.id, artifact); f.store.save(f.session);
let requests = 0, observedPages = [];
const model = await compatibleFixture(t, (route, body) => {
if (!route.endsWith('/chat/completions')) return { body: {} };
requests++;
const received = body.messages.filter(value => value.role === 'tool').map(value => JSON.parse(value.content)).filter(value => value.artifact_id === artifact.id);
if (requests > 1) {
const page = received.at(-1); assert.ok(page, 'Newest actual result must be sent, not archived before the model sees it');
assert.ok(page.budget_limited); assert.ok(page.next_offset > page.offset); assert.equal(page.content, original.slice(page.offset, page.next_offset));
observedPages.push(page);
if (requests === 4) return { body: completion([], '已根据三段实际结果完成读取验收。') };
return { body: completion([call('page-' + requests, 'read_artifact', { artifact_id: artifact.id, offset: page.next_offset, limit: 16000 })]) };
}
return { body: completion([call('page-first', 'read_artifact', { artifact_id: artifact.id, limit: 16000 })]) };
});
f.store.saveConfig({ mode: 'compatible', baseUrl: model.baseUrl, model: 'page-budget-fixture', maxSteps: 8 });
const runtime = new Runtime(f.store, new Provider()); runtime.start(f.session.id, '读取保存的原工件,分段取得真实依据,不执行命令或修改文件。');
await until(() => !runtime.isActive(f.session.id), 20000);
assert.equal(f.session.status, 'completed', JSON.stringify({ failure: f.session.failure, requests, pages: observedPages.map(value => ({ offset: value.offset, next: value.next_offset, budget: value.maximum_message_bytes })) })); assert.equal(requests, 4); assert.equal(observedPages.length, 3);
assert.equal(observedPages[1].offset, observedPages[0].next_offset); assert.equal(observedPages[2].offset, observedPages[1].next_offset);
assert.equal(f.store.artifactStore.read(artifact), original); assertToolPairs(f.session.providerMessages);
const plans = [...f.store.core.context_plan.values()];
for (const page of observedPages) assert.ok(plans.some(plan => plan.status === 'completed' && plan.retainedGroups.length > 0));
});
test('a real repeated artifact loop pauses the same Task after recorded results, survives reload and only resumes explicitly', async t => {
const f = fixture(t), artifact = f.store.artifactStore.write(f.session, null, 'Known complete evidence', { kind: 'check-log' });
f.store.core.artifact.set(artifact.id, artifact); f.store.save(f.session);
let requests = 0, resume = false;
const model = await compatibleFixture(t, () => {
requests++;
return { body: resume ? completion([], '使用已保存内容完成核对。')
: completion([call('repeat-read-' + requests, 'read_artifact', { artifact_id: artifact.id, limit: 16000 })]) };
});
f.store.saveConfig({ mode: 'compatible', baseUrl: model.baseUrl, model: 'repeat-loop-fixture', maxSteps: 12 });
const runtime = new Runtime(f.store, new Provider()); runtime.start(f.session.id, '使用不可变证据完成当前任务。');
await until(() => !runtime.isActive(f.session.id), 20000);
const taskId = f.session.taskId;
assert.equal(f.session.status, 'paused'); assert.equal(f.store.core.run.get(f.session.runId).stopReason, 'no_progress');
assert.equal(requests, 4); assert.equal([...f.store.core.tool.values()].filter(value => value.state === 'completed').length, 4);
assertToolPairs(f.session.providerMessages); f.store.close();
const reopened = new Store(f.data); f.onCleanup(() => reopened.close());
const saved = reopened.session(f.session.id); assert.equal(saved.taskId, taskId); assert.equal(requests, 4);
assert.equal(reopened.core.task.get(taskId).readProgress.pause, true); assertToolPairs(saved.providerMessages);
resume = true; const resumed = new Runtime(reopened, new Provider()); resumed.start(saved.id, '', true);
await until(() => !resumed.isActive(saved.id), 20000);
assert.equal(saved.status, 'completed'); assert.equal(saved.taskId, taskId); assert.equal(requests, 5);
assert.equal([...reopened.core.tool.values()].length, 4); assert.equal(reopened.core.task.get(taskId).readProgress.pause, false);
});
+14
View File
@@ -37,6 +37,20 @@ function assertBounded(plan) {
assertToolPairs(plan.messages);
}
test('direct code evidence remains selected while recent historical-index browsing is archived within the complete request budget', t => {
const f = setup(t, { contextLimit: 10000, maxOutputTokens: 2048 });
for (const name of ['normalize', 'summary', 'render', 'cli']) append(f, name, 'Actual implementation ' + name + '\n'.repeat(150), { path: 'src/' + name + '.mjs', start_line: 421, end_line: 450 });
const artifact = f.store.artifactStore.write(f.session, f.run, 'Index fixture', { kind: 'context-history-index' });
f.store.core.artifact.set(artifact.id, artifact);
for (let index = 0; index < 20; index++) append(f, 'index-' + index, 'metadata'.repeat(1500), { artifact_id: artifact.id, offset: index * 2000, limit: 2000 }, 'read_artifact');
append(f, 'latest-index', 'Recent bounded index page', { artifact_id: artifact.id, offset: 40000, limit: 2000 }, 'read_artifact');
const plan = f.prepare(); assertBounded(plan);
for (const name of ['normalize', 'summary', 'render', 'cli']) assert.ok(plan.messages.some(message => message.tool_calls?.some(value => value.id === 'history-' + name)), name + ' actual code group must remain');
assert.ok(plan.messages.some(message => message.tool_calls?.some(value => value.id === 'history-latest-index')));
assert.ok(plan.record.archivedGroups > 10); assert.ok(plan.record.mandatoryInputTokens < plan.record.budget.inputBudget);
assert.ok(plan.messages.some(message => message.role === 'system' && message.content.includes('working_evidence')));
});
test('one long user turn becomes bounded complete groups with exact UTF-8 history and recent JSON arguments', t => {
const f = setup(t);
for (let index = 0; index < 60; index++) append(f, index, ('行' + index + '🙂\r\n').repeat(1200), { path: 'README.md', payload: '原参数🙂'.repeat(800) });