Compare commits

...

2 Commits

Author SHA1 Message Date
Agent Workbench Dev a2c6e6f586 docs(qa): record complete request ledger evidence and migration obligations 2026-11-07 12:50:45 +08:00
Agent Workbench Dev da2e631381 feat(models): preserve complete incremental request ledger and exports 2026-11-07 12:38:44 +08:00
27 changed files with 1058 additions and 29 deletions
+4
View File
@@ -1,5 +1,9 @@
# Agent Workbench项目执行规范
M2第二批I13源码da2e6313完成完整请求账本/逐请求增量存储:原metadata原字节及完整当前/初始记录保持、schema2在迁移事务中提升、完整游标/筛选/来源下载与快照NDJSON。最终build-4独立39/39,网页与实际Electron各5组/7图/23页/1本机请求,830输入/285产品源码/29编译一致;相关源码第4轮102/102在最后公开版本修正前,分开记录。4328份1620432307字节封存及只读复核通过,见[验收](docs/QA-M2-REQUEST-LEDGER.md)与[机器记录](docs/m2-request-ledger-2026-11-07.json)。首失败/原SHA/unknown保持,源码已本地提交、验收和既有GitAtlas普通增量推送收尾中。
下一I15官方能力注册表,再I09/I11/I12/I14缓存块/亲和/状态/指纹/版本与I27/I28 CI,M3统一发行。M3需明确新表迁移增量与已激活新处理器后回退,不能直接去掉安装器逐表全等守卫;本批仅验证同步接续失败的未变初始化撤销,不能冒称正式安装/回退通过。正式未部署/重启或新health复查;不委派/真实Key/真实模型/正式写入/续旧工程,默认unrestricted/passthrough/preserve和持久ask/auto/full、W/AD/AE/AG异常/重复读取/Purge收益unknown保持。下方旧接续按原时点理解。
M2首批I10推送完成:源码cb60fb11与验收704000e9已普通增量推送至既有GitAtlas分支、远端逐SHA一致,[回执](docs/gitatlas-m2-cache-usage-push.json)随收尾提交再次核对。2948原件/822输入/29编译保持,正式未部署/重启。下一I13完整请求账本与逐请求存储,后续M2/M3和历史unknown保持。
M2首批I10源码cb60fb11完成缓存读/写/未缓存/推理及TTL来源、unknown/冲突保留和失败上下文用量;透传证据核验允许必填/显式输出字段,原SHA/归属/冻结预算不变。最终相关93/93、独立23/23、网页与实际Electron各5组/6图/1280及390通过,822输入/29编译一致;2948原件1018919970字节见[验收](docs/QA-M2-CACHE-USAGE.md)与[机器记录](docs/m2-cache-usage-2026-11-07.json)(docs内使用同级文件名)。首12/15及网页/桌面验收器失败保持。0真实模型/Key/正式写入,不委派/安装/重启或续旧工程,未作新正式health声明。下一I13完整账本/逐请求存储,再M2官方注册表/原生缓存块/状态/指纹/版本与CI、M3统一发行;手机性能/宿主原因/物理手机及历史真实异常、重复读/Purge收益unknown保持。正在验收文档提交与既有GitAtlas普通增量推送,下方按原时点理解。
+5 -1
View File
@@ -1,5 +1,7 @@
# 官方优先开发路线(2026-11-06)
2026-11-07 M2首批I10已验收推送;第二批I13源码da2e6313完整账本/逐请求存储与原metadata、初始记录、unknown保持已验。最终build-4独立39/39、两端各5组/7图/23页、830输入/29编译和4328原件核对通过,见[账本验收](QA-M2-REQUEST-LEDGER.md)。相关102/102在最后公开版本修正前,分别记录;验收/授权增量推送收尾中。下一I15,再I09/I11/I12/I14与I27/I28;M2全阶段、M3安装/发行和所有真实收益未因此完成。
本路线以[全系统审查](SYSTEM-AUDIT-OFFICIAL-FIRST-2026-11-06.md)的38项事项为输入。目标是官方直连优先、代理/兼容同样保真,用户选择的模型和权限持久生效,AI能完成实际工程并提供真实证据。原审查保留其时点结论;M1首批I01/I02/I03已由68603f9c源码修复,专项12/相关110及独立两端各7组通过,见[验收](QA-M1-MODEL-PARAMETER-FIDELITY.md)。第二批dcaecd8b已修I04自动选模与I08其余MCP/身份说明,最终47/47、相关78/78及独立两端各7组通过,见[第二批验收](QA-M1-ROUTING-PERMISSION.md)。第三、四批进展如下;尚未正式发行。
第三批32780bee已完成I05/I07/I33/I38开放模式固定总量门槛与完整记录恢复:8项新增行为分轮通过(原失败/中断保持)、首候选相关75/75、最终网页与实际Electron各6组,见[完整记录验收](QA-M1-OPEN-RECORDS.md)。产品/构建输入与最终29编译一致;尚未正式部署。手机大账本全metadata写入仍慢,宿主一次身份观察失败及迟到生命周期原因未知,均保留待办。
@@ -63,6 +65,8 @@ MCP、检查点和手机账本改为完整分页/分段记录,跨31次操作
实际隔离安装、跨正式旧版升级、关键协议wire和网页/桌面核心入口通过后才正式激活。正式安装核对原数据/配置/工件/凭据存在状态,不导出或读取真实Key;升级/回退原错误保留。此路线本身不启动安装/重启。
I13新增schema2账本:当前安装器逐表全等比较会拒绝新表/迁移标记,必须核验声明增量并保持全部原行和工件,同时验证激活新处理器后的回退。旧schema1程序fresh open拒绝schema2,旧hot模块也不了解新账本;不能只放行新表。本批只验证同步接续失败时撤销尚无新结果的初始化;已有请求/进展不能为了回退删行或回写旧metadata。M3需实际跨版安装与回退验收后才部署。
### M4:先取得新的官方真实基线
届时使用用户当前启用、明确选择的连接,另冻新样本;不沿用X/AD/AE/AG或旧工程。官方直连和代理样本分开;目录、身份声明、推理/输出参数、流式/工具、用量和错误都分别判定,不能用一个“连接成功”覆盖所有功能。
@@ -148,4 +152,4 @@ Mnemo/其他产品从双方实际原件契约实现导出、入站委托、归
M0审查和M1四批已有独立源码、验收与证据:68603f9c参数/模式、dcaecd8b自动选模/权限、32780bee完整记录/恢复、231db3a完整Schema/服务器校验。M1所列I01–I08/I33/I38均有分批源码验证;M2/M3和新的M4/M8真实实验未因此完成。本地提交/推送不代表正式发行或真实收益通过。
下一轮进入M2版本化官方能力/来源、供应商缓存控制/用量/状态与完整账本;按官方契约分小批验证,再M3统一冻结发行。后续授权范围内普通增量推送;每个真实实验另有冻结计划,历史异常始终保留。
M2 I10用量与I13完整账本已有独立候选证据,下一I15版本化官方能力/逐字段来源,再I09/I11/I12/I14缓存块/亲和/状态/指纹/版本与I27/I28 CI;按官方契约分小批验证,M3再统一冻结发行。后续授权范围内普通增量推送;每个真实实验另有冻结计划,历史异常始终保留。
+13
View File
@@ -0,0 +1,13 @@
# M2 第二批:完整请求账本与逐请求存储
2026-11-07;基线 `a93bfd6885decdbfe33c8f16c9b16771984599cb`,开始工作树干净且既有 GitAtlas 分支逐 SHA 一致。承接已完成 I10,用 I13 修正“最多保存 1000 次”过时文案、只能看最近 100 条和整数组 metadata 回写;全量加载/大型会话的总体性能仍由 M7 另验。
1. [complete] 封存旧保存/显示/重启行为;确认旧 metadata、回执身份和原工件保留。确定增量表/迁移/游标与导出契约。
2. [complete] 新增逐请求表与原 metadata 不变的迁移;生产路径只写当前尝试,兼容旧只读访问,停止/重启仍 unknown、不重放。数据库 schema 2 只在账本事务中提升,旧程序不能静默读部分历史;所属失败热接续可撤销未被修改的迁移。
3. [complete] 完整范围与身份绑定的游标查询、单条与初始来源及完整流式导出;接现有请求账本的筛选/前后页/刷新/原响应入口,历史连接也能筛选,保存说明与实际一致。
4. [complete] 最终 build-4 独立39/39,含公开数据库版本修正、三协议实际本机 JSON/SSE、完整导出/初始记录/恢复/准确旧存储源码与同步接续回退。最终网页与实际 Electron 各5组/7图/23页,1107→1108当前及初始记录逐字段/SHA一致;830输入/285产品源码/29编译对齐。相关源码第4轮102/102发生在最后公开版本修正前,分开记录。首JSON失败/HTTP中断、drain观察、网页历史筛选修复、桌面初始导航和candidate-4复制脚本失败保持。
5. [in_progress] 源码da2e6313已提交;4328份1620432307字节原件封存并只读复核,12源码原字节相同/4仅LF归一。验收、机器记录和当前入口收尾,随后既有 GitAtlas 普通增量推送。下一 I15/I09/I11/I12/I14 与 CI,M3 统一发行。
本批不委派、不读真实 Key、不请求真实模型、不改正式数据或配置、不发行/安装/重启、不续旧工程。默认 unrestricted/passthrough/preserve 和持久 ask/auto/full 不变。迁移保留原 metadata 原字节;旧实验原驱动与原件按其冻结版本理解,不自动改写/重跑。I10/W/AD/AE/AG 网络/unknown/重复读取/Purge 收益 unknown 保持。
M3 需为新 schema 明确安装数据保持与回退合同并实际验收:当前安装器的逐表完全相等守卫会拒绝新表/迁移标记,不能把本批源码接续测试称为发行安装通过或正式已迁移。禁止为了兼容旧程序而回写原 metadata、删掉新请求,或绕过安装保护。
+45
View File
@@ -0,0 +1,45 @@
# 完整请求账本
模型中心的请求账本保存全部现有请求,支持前后页、历史连接/结果/原文筛选、刷新、完整范围导出以及原请求/响应下载。每页默认 50 条是展示分页,不是模型输出额度或保存上限。旧版本已经删去且没有原件的记录不能由迁移补造。
## 保存与原始来源
`model_attempts` 位于原 `workbench.sqlite`,用递增 `seq` 区分每一条记录。旧 `metadata.modelAttempts` 在一次事务中完整迁入;原 metadata 的文字和 SHA256 保持不变。重复的旧尝试 ID 分别保存,不因 ID 相同合并或删除。详情按序号读取;只按歧义 ID 读取时要求核对原序号。
每条保存当前 `payload`、最初 `initial_payload`、双方 SHA256 和旧数组位置。正常进度只更新所属当前尝试,未变化的记录不产生提交。连接、模型、协议、pool、项目、会话、Task、Run、request 身份不能被移到另一份记录;已有另一份保存进展时不覆盖。用量 `raw`、未报告/unknown、上游原错及原请求/响应工件引用保持原值。
重启后仅把仍为 running 的尝试记为 unknown,并保存核对原因;不重发请求、不重复工具,也不补造真实计费。初始记录继续保留重启前的状态。
账本协议版本是 1;采用它的 SQLite 数据库版本是 2。数据库版本只在账本迁移事务成功时提升,公开诊断返回实际版本。以前只支持 schema 1 的程序不能重新打开 schema 2 并把旧 metadata 误当全部历史。失败的同步处理器接续只可撤销经过核对、尚无新结果的初始化迁移;已有新增/变化记录、SHA 或归属变化时不删除账本。
旧 `ModelHub.attempts` 及 `storage.meta('modelAttempts')` 在新程序里仍可取得完整兼容视图,但普通请求不全量加载或回写数组。直接 SQL 读取原 metadata 的旧实验驱动只看到其冻结历史;不改写、重跑旧实验,新驱动应使用以下接口。正式安装的数据迁移和跨版本回退仍按 M3 单独验收。
## 查询接口
接口沿用当前工作台的连接凭据和本机来源核对,不发出模型请求。
| 路径 | 返回 |
| --- | --- |
| `GET /api/model-center/attempts` | 当前页、每条序号/当前与初始 SHA、完整保存数、范围数和下一页游标 |
| `GET /api/model-center/attempts/<sequence>` | 本条当前记录与初始记录、来源和双方 SHA |
| `GET /api/model-center/attempts/export` | 当前筛选范围的全部 NDJSON 记录 |
筛选参数为 `connectionId`、`sessionId`、`taskId`、`runId`、`status`、`model`、`protocol`、`query`。`query` 查原记录文字,百分号与下划线按文字处理。重复/无效参数会指出本机查询错误。已删除或关闭的历史连接仍可在现有账本中选择;读取失败保留所选连接、结果和搜索文字。
分页另接受正整数 `limit` 与 `cursor`,没有固定最大页额度。游标绑定本次账本身份、全部筛选和序号上界,后续新请求不会挤进原页。页上的运行中字段仍可能更新,尤其状态筛选的结果可能变化;这是序号范围分页,不是不可变字段快照。游标范围或来源变化时刷新即可取得新范围,不能跨连接/筛选混用。
`/api/model-center` 继续提供最近 100 条兼容预览,同时返回真实 `attemptCount`、是否还有历史及增量保存方式。完整账本不依赖这个预览范围。运行巡检也使用真实保存数。
## 完整导出
导出使用独立只读 SQLite 连接和读事务固定记录/字段快照,期间新请求与进度更新不影响已开始的导出。服务端逐条等待实际写入回调,不因缓冲区已清空而继续等待不存在的 `drain`。接收端关闭或写入失败时释放快照,不发送伪完成结尾;没有完整 footer 的片段不能当作完整导出。
NDJSON 每行末尾是 LF:
1. `header`:格式 `orven-model-attempts-ndjson`、协议版本、筛选、序号上界、预期条数、来源和 `includesInitialReceipts: true`。
2. 每条 `attempt`:序号/来源/SHA 引用、完整当前 `item` 和完整 `initial.item`/`initial.sha256`。
3. `footer`:`complete: true`、实际条数、所有 attempt 行**含 LF**拼接的 `recordLinesSha256`。
核对 header/实际/footer 数量、每条当前与初始 JSON 的 SHA,以及所有记录行的 SHA。原始工件正文不嵌入这个导出,继续按所保存的 session/工件 ID/SHA 从原入口下载。浏览器客户端取得完整文件后下载 Blob;Electron 使用真实 DownloadItem,验收选择自有路径,Windows 保存对话框另未验证。未以这项功能宣称大规模客户端流式落盘、总体性能或真实供应商缓存收益。
实现和验收见 [切片计划](M2-REQUEST-LEDGER-PLAN.md) 与 [阶段验收](QA-M2-REQUEST-LEDGER.md)。历史真实模型失败、网络异常、unknown 用量、重复读取和 Purge 收益 unknown 均不改变。
+2
View File
@@ -1,5 +1,7 @@
# 1.25 计划:任务要求与交付复核
当前M2第二批I13源码da2e6313完成完整请求账本与逐请求增量存储,原metadata/初始记录/unknown不改。最终build-4独立39/39、网页与实际Electron各5组/7图/23页通过;830输入/29编译与candidate-app-5一致,4328原件只读验封通过,见[验收](QA-M2-REQUEST-LEDGER.md)和[机器记录](m2-request-ledger-2026-11-07.json)。相关102/102发生在最后公开数据库版本修正前,不能混称最后一轮;首失败完整保持。文档与授权GitAtlas普通增量推送收尾中。下一I15官方注册表和I09/I11/I12/I14缓存块/状态/指纹/版本、I27/I28 CI,M3统一发行须实际核验schema2安装增量及新处理器回退,不去掉数据保持守卫。本批未正式部署/重启或新health复查,历史真实异常/重复读取/Purge收益unknown保持;下方旧当前按历史时点理解。
M2首批I10源码cb60fb11完成缓存读/写/未缓存/推理及TTL来源、unknown/冲突保留和失败上下文用量;透传证据核验允许必填/显式输出字段,原SHA/归属/冻结预算不变。最终相关93/93、独立23/23、网页与实际Electron各5组/6图/1280及390通过,822输入/29编译一致;2948原件1018919970字节见[验收](QA-M2-CACHE-USAGE.md)与[机器记录](m2-cache-usage-2026-11-07.json)(docs内使用同级文件名)。首12/15及网页/桌面验收器失败保持。0真实模型/Key/正式写入,不委派/安装/重启或续旧工程,未作新正式health声明。下一I13完整账本/逐请求存储,再M2官方注册表/原生缓存块/状态/指纹/版本与CI、M3统一发行;手机性能/宿主原因/物理手机及历史真实异常、重复读/Purge收益unknown保持。正在验收文档提交与既有GitAtlas普通增量推送,下方按原时点理解。
当前源码进展(2026-11-07):M1第四批I06源码231db3a已完成完整MCP Schema/原服务器校验,实际证据复核目录旧门槛和漂移误显空目录已修;最终6/6、首候选45/46及补封静态输入后单独1/1,最终两端各5组/1280及390通过,见[Schema验收](QA-M1-MCP-SCHEMA.md)。1958原件/815输入/29编译已核对,M1所列事项均有分批源码证据;尚未正式部署/重启。下一M2官方注册表/缓存状态/完整请求账本,再M3统一发行;手机性能/宿主生命周期及历史真实异常、重复读/Purge收益unknown保持。下方旧当前按原时点理解。
+44
View File
@@ -0,0 +1,44 @@
# M2 第二批:完整请求账本验收
基线 `a93bfd6885decdbfe33c8f16c9b16771984599cb`;源码 `da2e6313818a0d527583bb539eef7e34141bda8c`。I13 的源码、独立候选和两端核心路径已通过,产品版本仍为 1.25.12,尚未发行、安装或正式部署。接口与核对方法见 [完整请求账本](MODEL-REQUEST-LEDGER.md),逐项结果见 [机器记录](m2-request-ledger-2026-11-07.json)。
旧开放模式实际保存 1107 条但仅显示 100 条,文案仍称最多保存 1000 条;有限模式只保存最后 1000 条。两个正常进度写入都重新序列化整份 metadata,分别累计 426144 与 385678 字节。这是固定夹具的行为观察,不是性能基准;旧程序已删除且没有原件的历史不能补造。
新 `model_attempts` 表完整迁移旧数组,保留原 metadata 原字节、旧数组位置、当前与初始记录及双方 SHA。重复旧 ID 分开保存。正常请求只写所属当前行,不变记录不提交、过期缓存不覆盖另一份进展;重启 running → unknown,初始记录不改、不重放模型或工具。完整游标查询、历史连接筛选、单条来源下载与 NDJSON 快照导出已接入现有模型中心;每页 50 条仅用于展示。
导出使用独立只读 SQLite 快照,含 header、所有完整当前与初始记录、数量和记录行 SHA footer。接收端中断释放快照,没有完整 footer 的片段不能当作完整导出。发现真实 HTTP 写入停滞后,改为等待实际写入回调,保留原两次 drain 观察;不以假完成 footer 掩盖断线。
| 验证 | 结果与准确范围 |
| --- | --- |
| 首源码专项 | 已输出 10 项中 7 过、3 失败,随后 HTTP 挂起并被中断,没有整轮总结。JSON 夹具中的 undefined 字段和原日志保持;修正后分轮验证。 |
| 相关源码第 4 轮 | 102/102,发生在最后公开数据库版本修正前,不描述为最终候选的单轮结果。 |
| 最终独立候选 | build-4 的 39/39,含最后版本修正、三协议实际本机 JSON/SSE、HTTP 导出、恢复、准确旧存储源码和同步接续回退。 |
| 最终构建身份 | 830 输入、285 产品源码、29 编译文件逐 SHA 与当前源码、build-4 和 candidate-app-5 对齐。 |
| 网页 | 5 组、7 图、23 页,1280/390;1107 → 1108 完整记录、当前/初始导出与重启逐字段/SHA一致,实际本机模型请求 1 次,页面错误 0。 |
| 实际 Electron | 同样 5 组、7 图、23 页、实际本机模型请求 1 次;5 个真实 DownloadItem 完成。QA 指定自有路径,Windows 保存对话框尚未验证。 |
| 原字节 | 两端旧 metadata SHA 都为 `9a35d4ebd6cb8c1bdac1a8f6f2cc8661fa98be29419ced64b3aa99df7768b6ba`;原 SSE 各 646 字节、同 SHA;完整 NDJSON 各 1625633 字节,独立运行身份不同,因此不要求两份文件整体 SHA 相同。 |
| 只读验封 | 4328 原件、830 输入、29 编译、16 源码 Git blob 重新核对通过;16 源码中 12 原字节相同、4 仅 LF 归一,双方 SHA 均保存。 |
| 范围与清理 | 最终自有路径进程观察 0;真实模型/真实 Key/正式写入均为 0,未查询新的正式 health、未安装或重启正式服务。两端共 2 次只统计最终 E2E 请求,未统计整轮单元测试的所有本机 HTTP 请求。 |
最终截图已实看:宽屏账本、保留历史连接/结果/搜索的读取错误、390px 控件与未知记录来源;品牌和现有布局保持。读失败不会把历史连接误显成全部连接,搜索文字也保持。
## 首失败与调查原件
1. 首 JSON 夹具三项失败、HTTP 中断与第二次隔离超时保留;测试专用 8 秒 Abort 用于定位,未引入产品请求额度。
2. 两次 trace 观察到 response.write 返回 false、缓冲已为 0 而 needDrain 仍为 true,之后没有 drain。实际回调写入修正后完整导出通过。
3. 网页首验虽通过,实看发现历史连接在读取错误时误显全部。修复产品状态投影并增加真实输入断言后,最终两端重新验收。
4. Electron 首验提前 page.goto 打断 main.mjs 等待的初始 loadURL,出现 ERR_ABORTED 并退出,0 模型请求。验收脚本改为等待程序自行导航完成,程序未为此改动。
5. candidate-4 复制脚本全局替换误改固定 I10 runtime 来源,ENOENT;部分候选保留,candidate-5 使用明确来源成功。该失败在工具输出及 `candidate-4-error.json` 有记录,没有单独重定向的原始 stderr 文件。
6. 收尾读取首次输出过多被截断,PowerShell 试读不存在的数组键报错;改用明确字段读取。未改产品、旧证据或正式数据。
原件位于 `.qa/m2-request-ledger-2026-11-07/`,**4328 份 / 1620432307 字节**,另有 MANIFEST 与 seal-result。四个 build 的 node_modules junction 不遍历。MANIFEST SHA256:`6ed883ec1fb3e2147795f696802b575e4508e15775c4b764bc8aea166aa34035`。后续验封和推送日志在 `.qa/m2-request-ledger-push-2026-11-07/`,不向封存根追加文件。
## M3 安装与回退待办
SQLite schema 2 只在账本迁移事务中提升,公开 storageInfo 读取实际 PRAGMA。旧 schema 1 程序重新打开会拒绝 schema 2;旧热接续模块也不了解新账本及 getter/原型,不能据此宣称跨版本回退可用。
当前 InstallationManager.activate 的原数据逐表全等守卫会拒绝新增表/迁移标记。M3 必须核验声明迁移产生的增量并保持每个原行/原工件,同时处理已经激活新处理器后的回退;不能只放行新表或删掉守卫。本批只覆盖同步接续失败时撤销尚无新结果的初始化,不覆盖正式安装后回退。已有新请求或进展不得为了回退而删行或回写旧 metadata。实际跨版、安装与回退验收通过后才能正式部署。
下一按 [官方优先路线](DEVELOPMENT-ROADMAP-OFFICIAL-FIRST.md)完成 I15 官方能力注册表和 I09/I11/I12/I14 原生缓存块、状态、指纹及版本合同,再补 I27/I28 CI 与契约来源;M2 全部事项和 M3 尚未完成。
历史 W 的 6 matched/71044 tokens/只读 no_progress 未交付及 v2 关键边界未触达;AD 的 21 请求/199250 reported+2 unknown、Claude 400/网络原错和 Node 成功;AE 的 React/Python 成功、20 请求/367365 reported 和原解释器/检查失败;AG 的 11 请求/109888 reported+3 unknown、三次 ETIMEDOUT 和唯一 ba-off 成功全部保持。手机 2001 操作约 14 分 41 秒仍是非受控观察;Windows 旧宿主身份失败/迟到原因、物理 iPhone、全球原生协议仍待。真实缓存、角色、经验和重复读取普遍收益未证明,**Purge 收益 unknown**。默认 unrestricted/passthrough/preserve 与持久 ask/auto/full 不变。
+2
View File
@@ -1,5 +1,7 @@
# Tianshu 研究后的 Agent Workbench 采用计划
当前M2第二批I13源码da2e6313完成完整请求账本与逐请求增量存储,原metadata/初始记录/unknown不改。最终build-4独立39/39、网页与实际Electron各5组/7图/23页通过;830输入/29编译与candidate-app-5一致,4328原件只读验封通过,见[验收](QA-M2-REQUEST-LEDGER.md)和[机器记录](m2-request-ledger-2026-11-07.json)。相关102/102发生在最后公开数据库版本修正前,不能混称最后一轮;首失败完整保持。文档与授权GitAtlas普通增量推送收尾中。下一I15官方注册表和I09/I11/I12/I14缓存块/状态/指纹/版本、I27/I28 CI,M3统一发行须实际核验schema2安装增量及新处理器回退,不去掉数据保持守卫。本批未正式部署/重启或新health复查,历史真实异常/重复读取/Purge收益unknown保持;下方旧当前按历史时点理解。
M2首批I10源码cb60fb11完成缓存读/写/未缓存/推理及TTL来源、unknown/冲突保留和失败上下文用量;透传证据核验允许必填/显式输出字段,原SHA/归属/冻结预算不变。最终相关93/93、独立23/23、网页与实际Electron各5组/6图/1280及390通过,822输入/29编译一致;2948原件1018919970字节见[验收](QA-M2-CACHE-USAGE.md)与[机器记录](m2-cache-usage-2026-11-07.json)(docs内使用同级文件名)。首12/15及网页/桌面验收器失败保持。0真实模型/Key/正式写入,不委派/安装/重启或续旧工程,未作新正式health声明。下一I13完整账本/逐请求存储,再M2官方注册表/原生缓存块/状态/指纹/版本与CI、M3统一发行;手机性能/宿主原因/物理手机及历史真实异常、重复读/Purge收益unknown保持。正在验收文档提交与既有GitAtlas普通增量推送,下方按原时点理解。
当前源码进展(2026-11-07):M1第四批I06源码231db3a已完成完整MCP Schema/原服务器校验,修实际证据核对旧目录门槛和漂移误显空目录;最终6/6,首候选45/46加补封静态输入后单独1/1,最终网页/实际Electron各5组通过,见[Schema验收](QA-M1-MCP-SCHEMA.md)。1958原件/815输入/29编译已核对,尚未发行/部署/重启。M1各项已有分批源码证据,下一M2官方注册表/缓存状态/请求账本,再M3统一发行;手机性能/宿主生命周期和原真实网络/unknown/重复读取/Purge收益unknown保持。下方旧当前按原时点理解。
+49
View File
@@ -0,0 +1,49 @@
{
"stage": "M2-I13",
"base": "a93bfd6885decdbfe33c8f16c9b16771984599cb",
"source": "da2e6313818a0d527583bb539eef7e34141bda8c",
"productVersion": "1.25.12",
"sourceAcceptanceComplete": true,
"productionDeployed": false,
"officialServiceHealthRechecked": false,
"evidenceRoot": ".qa/m2-request-ledger-2026-11-07",
"closingRoot": ".qa/m2-request-ledger-push-2026-11-07",
"manifestSha256": "6ed883ec1fb3e2147795f696802b575e4508e15775c4b764bc8aea166aa34035",
"evidenceFiles": 4328,
"evidenceBytes": 1620432307,
"linkedDependenciesNotTraversed": ["build-1/node_modules", "build-2/node_modules", "build-3/node_modules", "build-4/node_modules"],
"finalBuild": "build-4",
"finalCandidate": "candidate-app-5",
"inputFiles": 830,
"productSourceFiles": 285,
"compiledFiles": 29,
"sourceGitProof": { "files": 16, "byteExact": 12, "lfOnly": 4, "file": "source-git-proof.json" },
"relatedSourceRound4": { "tests": 102, "passed": 102, "failed": 0, "file": "source-4.log", "beforeLastPublicDatabaseVersionCorrection": true },
"finalIndependent": { "tests": 39, "passed": 39, "failed": 0, "file": "independent-4.log", "afterLastPublicDatabaseVersionCorrection": true },
"originalMetadataSha256": "9a35d4ebd6cb8c1bdac1a8f6f2cc8661fa98be29419ced64b3aa99df7768b6ba",
"databaseSchemaVersion": 2,
"ledgerProtocolVersion": 1,
"oldReceiptCount": 1107,
"finalReceiptCountPerEndToEnd": 1108,
"web": { "directory": "web-d7d5d997-12bc-4820-ab6e-e0b12776e1c6", "groups": 5, "screenshots": 7, "pages": 23, "syntheticModelRequests": 1, "viewportWidths": [1280, 390], "pageErrors": 0, "downloads": 5, "fullExportBytes": 1625633, "originalResponseBytes": 646 },
"electron": { "directory": "electron-85abd7c4-4b6b-484a-ae02-fa172e598b93", "groups": 5, "screenshots": 7, "pages": 23, "syntheticModelRequests": 1, "viewportWidths": [1280, 390], "pageErrors": 0, "nativeDownloads": 5, "fullExportBytes": 1625633, "originalResponseBytes": 646, "windowsSaveDialogVerified": false },
"finalEndToEndSyntheticRequestsOnly": 2,
"wholeStageSyntheticRequestTotal": "not_counted",
"realModelRequests": 0,
"realCredentialsRead": 0,
"productionWrites": 0,
"ownedProcessObservation": { "recordedAt": "2026-11-07T04:40:17.9115504Z", "count": 0, "file": "owned-process-observation-final.json", "scope": "Only processes matching owned evidence path, no production health request" },
"readOnlyRecheck": { "recordedAt": "2026-11-07T04:46:17.032Z", "success": true, "file": ".qa/m2-request-ledger-push-2026-11-07/recheck-1.json" },
"baseline": { "file": "baseline-observations.json", "open": { "input": 1107, "retained": 1107, "displayed": 100, "declaredRetention": 1000, "serializedBytesAcrossTwoWrites": 426144 }, "limited": { "input": 1107, "retained": 1000, "displayed": 100, "serializedBytesAcrossTwoWrites": 385678 }, "performanceBenchmark": false },
"failuresPreserved": [
{ "id": "initial-source", "file": "source-1.log", "observedPassed": 7, "observedFailed": 3, "totalObserved": 10, "summaryProduced": false, "reason": "JSON undefined fixtures and later HTTP hang; interrupted" },
{ "id": "http-investigation", "files": ["http-investigation-1.log", "http-investigation-2.log", "http-trace-1.log", "http-trace-2.log"], "reason": "Timeout/interruption; response.write false with zero buffer and needDrain true but no next drain" },
{ "id": "first-web", "file": "web-1.log", "reason": "Passed script then screenshot revealed historical filter displayed as all after read error; product corrected and final inputs verified" },
{ "id": "first-electron", "file": "electron-2.log", "reason": "Harness navigated before initial loadURL completed; ERR_ABORTED; model requests zero" },
{ "id": "candidate-4", "file": "candidate-4-error.json", "reason": "Script-wide replacement changed fixed runtime source; ENOENT; partial candidate preserved", "separateRawStderrFile": false }
],
"installationAndRollback": { "verified": false, "milestone": "M3", "currentExactTableGuardRejectsNewTables": true, "required": ["Verify declared migration increments and every original row/artifact", "Actual previous-version install and rollback", "Handle rollback after new handler activation", "Do not delete new requests/progress or rewrite legacy metadata for rollback"], "onlyVerifiedRollback": "Synchronous adoption failure of initialization that has no new or changed receipts" },
"historicalUnknownsRetained": ["W delivery and v2 live outlier boundary", "AD original Claude 400 and network errors", "AE original interpreter/check failures", "AG three ETIMEDOUT and unknown usage", "Purge benefit unknown", "Real cache, role, experience and general repeated-read benefit", "Mobile metadata scale performance", "Old Windows host identity failure and late arrival cause", "Physical iPhone", "Global native provider compatibility"],
"defaultsPreserved": ["unrestricted", "passthrough", "preserve", "persistent ask/auto/full"],
"next": ["M2 I15", "M2 I09/I11/I12/I14", "M2 I27/I28", "M3"]
}
+2
View File
@@ -1,5 +1,7 @@
# 汇总发现
M2 I13:1107旧记录开放实际全存但只显100,有限只存1000、文案错误。源码da2e6313改为schema2增量表、原metadata原字节/初始记录保留、当前尝试独立更新、完整seq游标/筛选/快照NDJSON。HTTP真实导出只等drain停滞改等实际写回调;首JSON undefined夹具、HTTP超时/中断、桌面初始导航、candidate-4复制失误和网页历史筛选修复均保留。最终build-4独立39/39、candidate-app-5两端各5组/7图/23页/1本机请求,830输入/285产品源码/29编译、4328原件、16源码Git blob核对通过;相关102/102在最后公开数据库版本修正前。M3需明确迁移增量及新处理器回退,不删新记录/回写旧metadata或直接去掉逐表全等守卫;仅同步接续失败的未变初始化撤销已验。真实供应商/缓存/重复读/Purge收益unknown。
M2首批I10源码cb60fb11完成缓存读/写/未缓存/推理及TTL来源、unknown/冲突保留和失败上下文用量;透传证据核验允许必填/显式输出字段,原SHA/归属/冻结预算不变。最终相关93/93、独立23/23、网页与实际Electron各5组/6图/1280及390通过,822输入/29编译一致;2948原件1018919970字节见[验收](docs/QA-M2-CACHE-USAGE.md)与[机器记录](docs/m2-cache-usage-2026-11-07.json)(docs内使用同级文件名)。首12/15及网页/桌面验收器失败保持。0真实模型/Key/正式写入,不委派/安装/重启或续旧工程,未作新正式health声明。下一I13完整账本/逐请求存储,再M2官方注册表/原生缓存块/状态/指纹/版本与CI、M3统一发行;手机性能/宿主原因/物理手机及历史真实异常、重复读/Purge收益unknown保持。正在验收文档提交与既有GitAtlas普通增量推送,下方按原时点理解。
M1 I06已完成源码231db3a:协议仅要求对象外层,完整schema与参数由服务器校验;新v2保留rawTools、旧v1原SHA不变、实际漂移仍拒发。实际发现并修复证据核对残留12项/24KB门槛及来源漂移误显空目录。最终独立6/6;首候选相关45/46因漏封静态benchmark,补6输入后该项1/1,原失败保持;815输入/29编译一致、两端各5组。1958原件见docs/QA-M1-MCP-SCHEMA.md;M2/M3与手机性能/宿主原因/真实收益待办保持。文档patch猜错标题的未应用结果已纠正,不当作写入成功。
+2
View File
@@ -1,5 +1,7 @@
# 统一执行进度
M2 I13源码da2e6313与独立候选验收完成:相关第4轮102/102在最后公开版本修正前,最后build-4独立39/39;candidate-app-5网页与实际Electron各5组/7图/23页/1本机请求、1107→1108全量下载/当前和初始SHA/重启保持。830输入/285产品源码/29编译及4328份1620432307字节原件、12原字节/4仅LF归一源码Git blob只读复核通过,原失败保持。验收文档和授权GitAtlas普通增量推送收尾中,下一I15/缓存块状态版本/CI;正式未部署/重启或新health复查,M3安装增量与新处理器回退及历史unknown保持。
M2首批I10源码cb60fb11完成缓存读/写/未缓存/推理及TTL来源、unknown/冲突保留和失败上下文用量;透传证据核验允许必填/显式输出字段,原SHA/归属/冻结预算不变。最终相关93/93、独立23/23、网页与实际Electron各5组/6图/1280及390通过,822输入/29编译一致;2948原件1018919970字节见[验收](docs/QA-M2-CACHE-USAGE.md)与[机器记录](docs/m2-cache-usage-2026-11-07.json)(docs内使用同级文件名)。首12/15及网页/桌面验收器失败保持。0真实模型/Key/正式写入,不委派/安装/重启或续旧工程,未作新正式health声明。下一I13完整账本/逐请求存储,再M2官方注册表/原生缓存块/状态/指纹/版本与CI、M3统一发行;手机性能/宿主原因/物理手机及历史真实异常、重复读/Purge收益unknown保持。正在验收文档提交与既有GitAtlas普通增量推送,下方按原时点理解。
2026-11-07 M1第四批普通增量推送已逐SHA确认:231db3a源码/8bc4453a验收至既有GitAtlas分支,1958原件/815输入/13当前链接核验通过;回执和阶段完成状态另提交后最终推送核对。不发行或重启;下一M2。接续只读搜索又误把Model*当PowerShell路径glob,已改为rg目录和-g,不据失败查询判定产品。
+176
View File
@@ -0,0 +1,176 @@
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import { chromium, _electron } from 'playwright';
import { expect } from 'playwright/test';
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { HostController } from '../src/core/desktop/host-controller.mjs';
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
import { projectEnvironment } from '../src/core/process-environment.mjs';
import { usageSamples, usageModelId, cacheUsageFixture } from '../tests/fixtures/cache-usage-model.mjs';
import { historicalAttempts, inspectExport, hash } from '../tests/fixtures/request-ledger-data.mjs';
import { openWorkbenchTool } from './ui-navigation.mjs';
assert.ok(process.argv.slice(2).every(value => value === '--desktop'));
assert.ok(process.env.AGENT_WORKBENCH_QA_APP_ROOT, 'Use a frozen independent candidate');
const desktop = process.argv.includes('--desktop'), appRoot = fs.realpathSync.native(process.env.AGENT_WORKBENCH_QA_APP_ROOT);
const directory = path.resolve('.qa/m2-request-ledger-2026-11-07', (desktop ? 'electron-' : 'web-') + randomUUID());
fs.mkdirSync(directory, { recursive: true }); console.log('EVIDENCE ' + directory);
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t, { modernDefaults: true });
const model = await cacheUsageFixture(t, { ...usageSamples.chat, streaming: true });
const hub = Object.assign(Object.create(Provider.prototype), { apiKey: '' }).modelHub(f.store);
const connection = hub.upsert({ name: '自有账本验证 · Chat', model: usageModelId, protocol: 'chat-completions', streaming: true,
baseUrl: model.baseUrl, requiresKey: false, modelIdentityPolicy: 'require-match' });
hub.select({ type: 'connection', id: connection.id });
// Config setup uses source contracts; the candidate itself receives an old
// schema-1 database with the complete original array and performs migration.
assert.equal(hub.ledger.rollbackInitialization(), true);
const historical = historicalAttempts(); historical.at(-1).status = 'running'; delete historical.at(-1).finishedAt;
historical.at(-1).usageStatus = 'unknown'; historical.at(-1).usage = null;
f.store.storage.setMeta('modelAttempts', historical);
const originalMetadata = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value;
fs.writeFileSync(path.join(directory, 'legacy-metadata.json'), originalMetadata); f.store.close();
const checks = [], screenshots = [], downloads = [], errors = [], externalBlocked = [], pages = [];
let host, controller, browser, app, page, window, port, result, desktopStdout = '', desktopStderr = '', beforeRestart, current;
const mark = value => { checks.push(value); console.log('PASS ' + value); };
const center = () => page.getByRole('dialog', { name: '模型中心', exact: true });
const ledger = () => center().getByRole('region', { name: '完整请求账本', exact: true });
const entries = () => ledger().locator('.mc-attempts article');
const pager = () => ledger().getByRole('navigation', { name: '请求账本分页 · 列表上方', exact: true });
async function openLedger() { await openWorkbenchTool(page, '打开模型中心'); await center().getByRole('button', { name: '请求账本', exact: true }).click(); await expect(ledger()).toHaveAttribute('aria-busy', 'false'); }
async function resize(width, height = 960) {
if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height }); await until(() => page.evaluate(w => innerWidth === w, width)); }
else await page.setViewportSize({ width, height });
}
async function shot(name, scope) {
await scope.scrollIntoViewIfNeeded(); assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'No unintended page overflow');
const file = path.join(directory, name + '.png'); await page.screenshot({ path: file, scale: 'css' });
screenshots.push({ file: path.basename(file), sha256: hash(fs.readFileSync(file)) }); fs.writeFileSync(path.join(directory, name + '.txt'), await scope.innerText());
}
async function download(name, action) {
const file = path.join(directory, name); let native = null;
if (app) {
const id = randomUUID();
await app.evaluate(({ session }, { id, file }) => {
globalThis.workbenchQaDownloads ??= {}; globalThis.workbenchQaDownloads[id] = { state: 'waiting' };
session.defaultSession.once('will-download', (_event, item) => {
const value = globalThis.workbenchQaDownloads[id]; value.suggestedFilename = item.getFilename(); value.state = 'started'; item.setSavePath(file);
item.once('done', (_event, state) => { value.state = state; value.bytes = item.getReceivedBytes(); value.totalBytes = item.getTotalBytes(); });
});
}, { id, file });
await action(); await expect.poll(() => app.evaluate((_electron, id) => globalThis.workbenchQaDownloads[id].state, id), { timeout: 30000 }).toBe('completed');
native = await app.evaluate((_electron, id) => globalThis.workbenchQaDownloads[id], id);
assert.equal(native.bytes, native.totalBytes); assert.equal(native.bytes, fs.statSync(file).size);
} else { const pending = page.waitForEvent('download'); await action(); await (await pending).saveAs(file); }
const bytes = fs.readFileSync(file); downloads.push({ file: name, bytes: bytes.length, sha256: hash(bytes), ...(native ? { native,
scope: 'Actual Electron DownloadItem; QA selects owned path, Windows save dialog not verified' } : { scope: 'Actual browser download' }) }); return bytes;
}
async function start() {
if (desktop) {
if (!port) { const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); port = socket.address().port; await new Promise(resolve => socket.close(resolve)); }
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
app = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path,
args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'],
cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
app.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); }); app.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
page = await app.firstWindow(); window = await app.browserWindow(page); await window.evaluate(win => win.showInactive());
} else { host = await launchWorkbench(t, f.data, {}, { appRoot }); assert.notEqual(new URL(host.url).port, '4318'); browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage({ acceptDownloads: true }); }
page.on('pageerror', error => errors.push(error.message));
await page.route('**/*', route => { const url = new URL(route.request().url()); if (url.origin === new URL(host.url).origin || ['data:', 'blob:'].includes(url.protocol)) return route.continue(); externalBlocked.push(url.origin); return route.abort(); });
await page.addInitScript(id => localStorage.setItem('awb-project', id), f.project.id);
if (desktop) {
// main.mjs awaits its initial loadURL. Replacing that navigation early
// rejects startup and closes the actual Electron app.
await page.waitForURL(url => url.origin === new URL(host.url).origin && url.searchParams.get('desktop') === '1');
await page.waitForLoadState('networkidle'); await page.reload();
} else await page.goto(host.url);
await page.waitForLoadState('networkidle');
}
async function stop() { await app?.close(); await browser?.close(); if (controller && await controller.health()) await controller.stop(); await host?.close?.(); app = null; browser = null; page = null; window = null; }
async function filter(query = '', status = '', connectionId = '') {
await ledger().getByLabel('搜索请求账本', { exact: true }).fill(query); await ledger().getByLabel('筛选账本连接', { exact: true }).selectOption(connectionId);
await ledger().getByLabel('筛选账本结果', { exact: true }).selectOption(status); await ledger().getByRole('button', { name: '筛选记录', exact: true }).click();
await expect(ledger()).toHaveAttribute('aria-busy', 'false');
}
function originalState() {
const database = new DatabaseSync(path.join(f.data, 'workbench.sqlite'), { readOnly: true });
try { const original = database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value; assert.equal(original, originalMetadata);
return { originalMetadataSha256: hash(original), databaseVersion: database.prepare('PRAGMA user_version').get().user_version }; }
finally { database.close(); }
}
try {
await start(); const initial = await host.api('/model-center/attempts?limit=2000'); assert.equal(initial.total, 1107); assert.equal(initial.items.length, 1107);
const unknown = await host.api('/model-center/attempts/1107'); assert.equal(unknown.item.status, 'unknown'); assert.deepEqual(unknown.initial.item, historical.at(-1));
assert.equal(originalState().databaseVersion, 2); assert.equal((await host.api('/bootstrap')).storage.schemaVersion, 2); assert.equal(model.requests.length, 0); fs.writeFileSync(path.join(directory, 'initial-page.json'), JSON.stringify(initial, null, 2));
await openLedger(); await resize(1280); await expect(entries()).toHaveCount(50); await expect(ledger()).toContainText('1,107 条已保存'); await shot('ledger-controls-1280', ledger().locator('.mc-ledger-filter'));
const unknownRow = entries().first(); await unknownRow.locator('.mc-ledger-source > summary').focus(); await page.keyboard.press('Enter');
const sourceBytes = await download('legacy-unknown-source.json', () => unknownRow.getByRole('button', { name: '下载本条与初始记录', exact: true }).click());
assert.deepEqual(JSON.parse(sourceBytes), unknown); await resize(390, 844); await shot('unknown-initial-source-390', unknownRow.locator('.mc-ledger-source'));
mark('Candidate migrates all 1107 old receipts, keeps metadata bytes, renders recovered unknown and downloads its unchanged initial record with keyboard expansion');
await resize(1280); const sequences = [];
while (true) {
const values = await entries().evaluateAll(rows => rows.map(row => Number(row.dataset.ledgerSequence))); pages.push(values); sequences.push(...values);
if (await pager().getByRole('button', { name: '下一页', exact: true }).isDisabled()) break;
await pager().getByRole('button', { name: '下一页', exact: true }).click(); await expect(entries().first()).toHaveAttribute('data-ledger-sequence', String(values.at(-1) - 1));
}
assert.deepEqual(sequences, Array.from({ length: 1107 }, (_, index) => 1107 - index)); assert.equal(pages.length, 23);
await pager().getByRole('button', { name: '上一页', exact: true }).click(); await expect(entries().first()).toHaveAttribute('data-ledger-sequence', '57');
await ledger().getByRole('button', { name: '刷新记录', exact: true }).click(); await expect(entries().first()).toHaveAttribute('data-ledger-sequence', '1107');
fs.writeFileSync(path.join(directory, 'ui-page-sequences.json'), JSON.stringify(pages)); mark('All 23 UI pages cross old 100/1000 boundaries exactly once; previous page and refresh retain complete ordered history without model dispatch');
await filter('owned-history', 'failed', 'owned-beta'); const filtered = historical.filter(value => value.connectionId === 'owned-beta' && value.status === 'failed');
await expect(pager()).toContainText('当前范围 ' + filtered.length + ' 条');
const filteredBytes = await download('filtered-complete.ndjson', () => ledger().getByRole('button', { name: '导出当前范围全部记录', exact: true }).click());
assert.deepEqual(inspectExport(filteredBytes).records.map(value => value.item), filtered); await shot('historical-filter-1280', ledger().locator('.mc-ledger-filter'));
await filter('owned-no-match', 'failed', 'owned-beta'); await expect(ledger()).toContainText('当前范围没有请求记录');
const emptyBytes = await download('empty-complete.ndjson', () => ledger().getByRole('button', { name: '导出当前范围全部记录', exact: true }).click()); assert.equal(inspectExport(emptyBytes).records.length, 0);
let injected = 0; const pattern = '**/api/model-center/attempts?*'; await page.route(pattern, route => { injected++; return route.fulfill({ status: 400, contentType: 'application/json', body: JSON.stringify({ error: '自有账本读取失败,原记录保留,请刷新核对。' }) }); });
await ledger().getByRole('button', { name: '刷新记录', exact: true }).click(); await expect(ledger().getByRole('alert')).toContainText('自有账本读取失败');
await expect(ledger().getByLabel('筛选账本连接', { exact: true })).toHaveValue('owned-beta');
await expect(ledger().getByLabel('搜索请求账本', { exact: true })).toHaveValue('owned-no-match');
await expect(ledger().getByLabel('筛选账本结果', { exact: true })).toHaveValue('failed');
await shot('owned-read-error-1280', ledger().getByRole('alert')); await page.unroute(pattern); assert.equal(injected, 1);
await ledger().getByRole('button', { name: '刷新记录', exact: true }).click(); await expect(ledger()).toContainText('当前范围没有请求记录');
await filter(); await expect(entries()).toHaveCount(50); assert.equal(model.requests.length, 0); await resize(390, 844); await shot('ledger-controls-390', ledger().locator('.mc-ledger-filter'));
mark('Deleted historical connection/status/text filters and complete/empty exports work; a separately injected local read failure recovers without changing history or contacting a model');
current = await host.api('/sessions', { projectId: f.project.id }); await host.api('/sessions/' + current.id + '/messages', { content: '自有账本增量验证:只回复已收到,不修改文件或调用工具。' });
await until(async () => (await host.api('/sessions/' + current.id)).status === 'completed', 30000); assert.equal(model.requests.length, 1);
for (const field of ['max_tokens', 'max_completion_tokens', 'max_output_tokens']) assert.equal(field in model.requests[0].input, false);
await ledger().getByRole('button', { name: '刷新记录', exact: true }).click(); await expect(entries().first()).toHaveAttribute('data-ledger-sequence', '1108');
const row = entries().first(); await row.locator('.model-usage-details > summary').click(); await expect(row).toContainText('300 tokens');
const responseBytes = await download('actual-local-response.sse', () => row.getByRole('button', { name: '下载已保存的响应', exact: true }).click()); assert.equal(hash(responseBytes), hash(model.responses[0]));
await resize(1280); await shot('new-incremental-receipt-1280', row.locator('.model-usage-details'));
const allBytes = await download('all-1108-complete.ndjson', () => ledger().getByRole('button', { name: '导出当前范围全部记录', exact: true }).click()); const full = inspectExport(allBytes);
assert.equal(full.records.length, 1108); assert.deepEqual(full.records.slice(0, 1107).map(value => value.initial.item), historical);
for (let index = 0; index < 1106; index++) assert.deepEqual(full.records[index].item, historical[index]); assert.equal(full.records[1106].item.status, 'unknown');
assert.equal(full.records[1107].item.sessionId, current.id); assert.equal(full.records[1107].initial.item.status, 'running');
beforeRestart = await host.api('/model-center/attempts?limit=2000'); fs.writeFileSync(path.join(directory, 'before-restart.json'), JSON.stringify(beforeRestart, null, 2));
mark('One actual local SSE request writes the new source-bound receipt, preserves I10 usage, downloads exact response bytes and exports all 1108 current/initial records with count and line SHA');
await stop(); await start(); const restored = await host.api('/model-center/attempts?limit=2000'); assert.deepEqual(restored, beforeRestart);
await openLedger(); await resize(1280); await expect(entries().first()).toHaveAttribute('data-ledger-sequence', '1108'); await expect(ledger()).toContainText('1,108 条已保存');
await shot('restart-preserved-1280', ledger().locator('.mc-ledger-filter')); assert.equal(model.requests.length, 1); assert.equal(originalState().databaseVersion, 2);
const config = (await host.api('/bootstrap')).config; assert.equal(config.executionMode, 'unrestricted'); assert.equal(config.capacityMode, 'passthrough'); assert.equal(config.historyPolicy, 'preserve');
assert.equal((await host.api('/bootstrap')).storage.schemaVersion, 2);
const finalCenter = await host.api('/model-center'); assert.equal(finalCenter.attemptCount, 1108); assert.equal(finalCenter.attempts.length, 100); assert.equal(finalCenter.storage.attemptsRetained, null);
fs.writeFileSync(path.join(directory, 'final-model-center.json'), JSON.stringify(finalCenter, null, 2)); fs.writeFileSync(path.join(directory, 'after-restart.json'), JSON.stringify(restored, null, 2));
assert.deepEqual(errors, []); assert.deepEqual(externalBlocked, []); mark('Owned host restart retains current/initial SHA, unknown/error history and default passthrough permissions exactly, with zero replay and a complete saved count');
result = { success: true, appRoot, actualElectron: desktop, checks, screenshots, downloads, pages: pages.length, ...originalState(), errors, externalBlocked,
syntheticRequests: model.requests.length, realModelRequests: 0, realCredentialsRead: 0, productionWrites: 0, viewportWidths: [1280, 390] };
} catch (cause) {
if (page) { await page.screenshot({ path: path.join(directory, 'failure.png') }).catch(() => {}); fs.writeFileSync(path.join(directory, 'failure.txt'), await page.locator('body').innerText().catch(() => '')); }
result = { success: false, appRoot, actualElectron: desktop, checks, screenshots, downloads, errors, externalBlocked, error: cause.stack, syntheticRequests: model.requests.length, realModelRequests: 0 };
} finally {
fs.writeFileSync(path.join(directory, 'requests.json'), JSON.stringify(model.requests, null, 2)); await stop();
fs.cpSync(f.data, path.join(directory, 'retained-owned-data'), { recursive: true, errorOnExist: true }); for (const dispose of disposers.reverse()) await dispose();
if (desktop) { fs.writeFileSync(path.join(directory, 'desktop-stdout.txt'), desktopStdout); fs.writeFileSync(path.join(directory, 'desktop-stderr.txt'), desktopStderr); }
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
}
console.log(JSON.stringify({ directory, ...result })); if (!result.success) process.exitCode = 1;
+4 -9
View File
@@ -1,13 +1,9 @@
import { useEffect, useRef, useState } from 'react';
import { Activity, Check, CircleHelp, KeyRound, Layers3, Plus, Power, RefreshCw, Route, Server, Settings2 } from 'lucide-react';
import { api, downloadArtifact } from './api';
import { api } from './api';
import type { Config, ModelSelection, ModelSnapshot, RuntimeFailure } from './types';
import './ModelCenter.css';
import { ModelUsageDetails } from './ModelUsageDetails';
import type { TokenUsage } from '../shared/contracts/model-usage.mjs';
import { ModelIdentityDetails } from './ModelIdentityDetails';
import { ModelRoutingDetails, type RoutingDecision } from './ModelRoutingDetails';
import type { ModelIdentity } from '../shared/contracts/model-identity.mjs';
import { ModelRequestLedger, type ModelAttempt } from './ModelRequestLedger';
import { ModelWaitSettings, type WaitSettings } from './ModelWaitSettings';
import { NativeParameters } from './NativeParameters';
import { ModelErrorDetails } from './ModelErrorDetails';
@@ -27,9 +23,8 @@ const upstreamCapacity = (value: { model: string; upstreamModel?: CatalogModel }
type Connection = { id: string; name: string; brand: string; protocol: string; parameterProfile?: string; messagesAuth?: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean; credentialSource?: { connectionId: string }; upstreamModel?: CatalogModel;
requiresKey: boolean; modelIdentityPolicy?: string; modelIdentityAliases?: string[]; modelIdentityAliasSource?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string; streaming?: boolean; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; capabilityEvidence?: { checkedAt: string }; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; savedCredential?: { status: string }; health: { state: string; reason?: string; cooldownUntil?: number } };
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; maxAttempts: number; revision?: number; queueTimeoutMs: number };
type Attempt = { routingDecision?: RoutingDecision; modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; upstreamResponse?: { requestId?: string | null; requestUrl?: string; responseUrl?: string | null; redirectMode?: string }; id: string; connectionId: string; poolId: string | null; model: string; protocol?: string; streaming?: boolean; rejections?: { connectionName: string; capability: string; reason: string }[]; status: string; startedAt: string; ordinal: number; usageStatus: string; reason?: string; taskId?: string; sessionId?: string; runId: string; requestArtifactId?: string; responseArtifactId?: string; responseSha256?: string; responseRedacted?: boolean; stream?: { bytes: number; capturedBytes?: number; frames: number; sha256: string; terminal: boolean }; usage?: TokenUsage | null };
type ImportRecord = { id: string; source: string; path: string; enabled: boolean; lastCheckedAt?: string; lastSyncedAt?: string; lastError?: string; lastResult?: { imported?: number; conflicts?: string[] } };
type Center = { revision: number; selected: { type: string; id: string }; waitSettings: WaitSettings; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: Attempt[]; waiting: number };
type Center = { revision: number; selected: { type: string; id: string }; waitSettings: WaitSettings; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: ModelAttempt[]; waiting: number };
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[];
artifacts?: { offset: number; checked: number; total: number; remaining: number; olderOffset: number | null; newerOffset: number | null; results: { id: string; passed: boolean; error?: string }[] } };
type SavedCredential = { id: string; name: string; revision: number; status: string; enabled?: boolean; savedAt?: string; message: string };
@@ -207,7 +202,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
<fieldset><legend>模型池成员与权重</legend>{connections.map(connection => { const member = pool.members.find(value => value.connectionId === connection.id); return <label key={connection.id} className="mc-member-choice"><input type="checkbox" checked={!!member} onChange={event => setPool({ ...pool, members: event.target.checked ? [...pool.members, { connectionId: connection.id, weight: 1 }] : pool.members.filter(value => value.connectionId !== connection.id) })} /><span>{connection.name}<small>{connection.model || '尚未选择模型'} · {states[connection.status]}</small></span><input type="number" aria-label={connection.name + '权重'} disabled={!member} min="1" max="10" value={member?.weight ?? 1} onChange={event => setPool({ ...pool, members: pool.members.map(value => value.connectionId === connection.id ? { ...value, weight: Number(event.target.value) } : value) })} /></label>; })}</fieldset>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => setPoolEditing(false)}>取消</button><button className="button primary" disabled={locked || !pool.members.length}>保存模型池</button></div></form>}
</>}
{tab === 'attempts' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol ? protocolLabel(value.protocol) : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p><ModelUsageDetails usage={value.usage} /><code>Run {value.runId}</code>{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}</p><code>原流 SHA256 {value.stream.sha256}</code>{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}</code>}{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.responseArtifactId!, "model-stream-" + value.id + ".sse"); })}>下载已保存的响应</button>}</div>}{value.requestUrl && <p className="mc-request-url">请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <><br />响应地址:{value.upstreamResponse.responseUrl}</>}</p>}{value.reason && <p className="mc-card-warning">{value.reason}</p>}<ModelRoutingDetails decision={value.routingDecision} /><ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model} />{value.diagnostic && <ModelErrorDetails failure={value.diagnostic} />}{!value.diagnostic && value.upstreamResponse?.requestId && <p className="mc-help">上游请求 ID:{value.upstreamResponse.requestId}</p>}{value.requestArtifactId && value.sessionId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.requestArtifactId!, "model-request-" + value.id + ".json"); })}>下载实际请求</button>}{!!value.rejections?.length && <p className="mc-route-rejections">{value.rejections.map(item => item.connectionName + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}</p>}</article>)}</div></>}
{tab === 'attempts' && <ModelRequestLedger connections={view.connections} refreshVersion={view} />}
{tab === 'imports' && <><div className="mc-section-title"><div><h3>已有配置导入</h3><p>先预览来源和模型,再导入。原客户端配置保持原样。</p></div><button className="button secondary" disabled={working} onClick={() => void act(async () => { const value = await api<{ sources: typeof discovery }>('/model-center/imports'); if (alive.current) setDiscovery(value.sources); })}>识别本机来源</button></div>
{view.imports.length > 0 && <><h4>已登记来源</h4>{view.imports.map(value => <article className="mc-import-source" key={value.id}><strong>{value.source}</strong><code>{value.path}</code><span>{value.enabled ? '每分钟检查' : '自动同步已关闭'}</span>{value.lastCheckedAt && <p>最近检查 {new Date(value.lastCheckedAt).toLocaleString()}</p>}{value.lastError && <p className="mc-card-warning">{value.lastError}</p>}{!!value.lastResult?.conflicts?.length && <p className="mc-card-warning">有 {value.lastResult.conflicts.length} 项与手动修改冲突,已保留工作台中的修改。</p>}<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/import-toggle', { id: value.id, enabled: !value.enabled }); })}>{value.enabled ? '关闭自动同步' : '启用自动同步'}</button></article>)}<button className="button secondary" disabled={locked || !view.imports.some(value => value.enabled)} onClick={() => void act(async () => { const result = await api<{ results: { imported?: string[]; conflicts?: string[]; error?: string }[] }>('/model-center/import-sync', {}); const imported = result.results.reduce((sum, value) => sum + (value.imported?.length ?? 0), 0); const conflicts = result.results.reduce((sum, value) => sum + (value.conflicts?.length ?? 0), 0); if (alive.current) setNotice(`已检查启用来源:更新 ${imported} 项,冲突 ${conflicts} 项。`); })}>立即同步已启用来源</button></>}
{discovery.map(value => <article className="mc-import-source" key={value.source}><strong>{value.source}</strong><code>{value.path || '当前版本尚无可发现的配置路径'}</code><span>{value.available ? value.supported ? '可预览' : '当前不支持' : '未发现'}</span>{value.detail && <p>{value.detail}</p>}<button className="button secondary" disabled={!value.available || !value.supported || locked} onClick={() => { setImportSource(value.source); setImportPath(value.path); }}>选择来源</button></article>)}
+13
View File
@@ -0,0 +1,13 @@
.mc-ledger { min-width: 0; }
.mc-ledger-filter { display: grid; grid-template-columns: minmax(160px, 2fr) minmax(130px, 1fr) minmax(110px, 1fr) auto; align-items: end; gap: 12px; margin: 12px 0; }
.mc-ledger-filter label { display: grid; gap: 6px; min-width: 0; font-size: 12px; color: var(--muted); }
.mc-ledger-filter input, .mc-ledger-filter select { width: 100%; min-width: 0; min-height: 40px; border: 1px solid var(--line, #c6d5d1); border-radius: 6px; background: var(--paper, white); color: var(--ink); padding: 8px; font: inherit; }
.mc-ledger-actions, .mc-ledger-pages { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 12px 0; }
.mc-ledger-actions > span, .mc-ledger-pages > span { color: var(--muted); font-size: 12px; line-height: 1.7; }
.mc-ledger-pages > span { flex: 1; }
.mc-ledger-source { margin: 8px 0; font-size: 12px; line-height: 1.6; overflow-wrap: anywhere; }
.mc-ledger-source > summary { cursor: pointer; }
.mc-ledger-source dl { display: grid; grid-template-columns: 70px minmax(0, 1fr); gap: 6px; }
.mc-ledger-source dd { margin: 0; }
.mc-ledger input:focus-visible, .mc-ledger select:focus-visible, .mc-ledger summary:focus-visible { outline: 2px solid var(--accent, #237a68); outline-offset: 2px; }
@media (max-width: 620px) { .mc-ledger-filter { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } .mc-ledger-filter > label:first-child { grid-column: 1 / -1; } .mc-ledger-filter > button { grid-column: 1 / -1; } .mc-ledger-actions > span { flex-basis: 100%; } }
+80
View File
@@ -0,0 +1,80 @@
import { useEffect, useState } from 'react';
import { api, downloadArtifact, downloadBlob, downloadModelLedger } from './api';
import { ModelUsageDetails } from './ModelUsageDetails';
import { ModelRoutingDetails, type RoutingDecision } from './ModelRoutingDetails';
import { ModelIdentityDetails } from './ModelIdentityDetails';
import { ModelErrorDetails } from './ModelErrorDetails';
import { protocolLabel } from '../shared/contracts/model-endpoint.mjs';
import type { ModelIdentity } from '../shared/contracts/model-identity.mjs';
import type { TokenUsage } from '../shared/contracts/model-usage.mjs';
import type { RuntimeFailure } from './types';
import './ModelRequestLedger.css';
export type ModelAttempt = { routingDecision?: RoutingDecision; modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string;
upstreamResponse?: { requestId?: string | null; responseUrl?: string | null }; id: string; connectionId?: string; model?: string; protocol?: string; streaming?: boolean;
rejections?: { connectionName: string; capability: string; reason: string }[]; status: string; startedAt: string; ordinal?: number; usageStatus: string; reason?: string;
taskId?: string; sessionId?: string; runId?: string; requestArtifactId?: string; responseArtifactId?: string; responseSha256?: string; responseRedacted?: boolean;
stream?: { bytes: number; capturedBytes?: number; frames: number; sha256: string; terminal: boolean }; usage?: TokenUsage | null };
type ReceiptReference = { sequence: number; payloadSha256: string; initialSha256: string; origin: string; legacyIndex?: number };
type LedgerPage = { items: ModelAttempt[]; references: ReceiptReference[]; total: number; retainedTotal: number; nextCursor: string | null; hasMore: boolean; snapshotSequence: number; connectionIds: string[] };
const states: Record<string, string> = { completed: '收到响应', failed: '请求失败', unknown: '结果未知', interrupted: '已中断', running: '请求中', rejected: '未派发' };
const address = (filters: Record<string, string>, cursor: string | null = null) => {
const params = new URLSearchParams({ ...filters, limit: '50', ...(cursor ? { cursor } : {}) }); return '/model-center/attempts?' + params.toString();
};
export function ModelRequestLedger({ connections, refreshVersion }: { connections: { id: string; name: string }[]; refreshVersion: unknown }) {
const [page, setPage] = useState<LedgerPage | null>(null), [cursor, setCursor] = useState<string | null>(null), [previous, setPrevious] = useState<(string | null)[]>([]);
const [filters, setFilters] = useState<Record<string, string>>({}), [query, setQuery] = useState(''), [status, setStatus] = useState(''), [connection, setConnection] = useState('');
const [historyConnections, setHistoryConnections] = useState<string[]>([]);
const [loading, setLoading] = useState(false), [working, setWorking] = useState(false), [error, setError] = useState(''), [revision, setRevision] = useState(0);
useEffect(() => {
let alive = true; setLoading(true); setError(''); setPage(null);
api<LedgerPage>(address(filters, cursor)).then(value => { if (alive) { setPage(value); setHistoryConnections(value.connectionIds); } }).catch(cause => { if (alive) setError(cause.message); }).finally(() => { if (alive) setLoading(false); });
return () => { alive = false; };
}, [filters, cursor, revision, refreshVersion]);
async function act(action: () => Promise<void>) { setWorking(true); setError(''); try { await action(); } catch (cause) { setError(cause instanceof Error ? cause.message : '记录未能读取,请刷新核对。'); } finally { setWorking(false); } }
const disabled = working || loading;
function reset() { setCursor(null); setPrevious([]); setRevision(value => value + 1); }
const ledgerConnections = [...connections, ...historyConnections.filter(id => !connections.some(value => value.id === id)).map(id => ({ id, name: id + '(历史连接)' }))];
function pager(location: string) { return page && <nav className="mc-ledger-pages" aria-label={'请求账本分页 · ' + location}><span>本页 {page.items.length} 条 · 当前范围 {page.total.toLocaleString('zh-CN')} 条</span>
<button className="button secondary" disabled={disabled || previous.length === 0} onClick={() => { setCursor(previous.at(-1) ?? null); setPrevious(value => value.slice(0, -1)); }}>上一页</button>
<button className="button secondary" disabled={disabled || !page.hasMore} onClick={() => { setPrevious(value => [...value, cursor]); setCursor(page.nextCursor); }}>下一页</button></nav>; }
return <section className="mc-ledger" aria-label="完整请求账本" aria-busy={loading || working}>
<div className="mc-section-title"><div><h3>请求账本</h3><p>完整保存历史请求;每页展示 50 条,可筛选和导出全部记录。未知用量保持未知。</p></div>
<span>{page ? page.retainedTotal.toLocaleString('zh-CN') + ' 条已保存' : loading ? '正在读取' : '尚未取得记录'}</span></div>
<form className="mc-ledger-filter" aria-label="筛选请求账本" onSubmit={event => { event.preventDefault(); setFilters({ ...(query ? { query } : {}), ...(status ? { status } : {}), ...(connection ? { connectionId: connection } : {}) }); reset(); }}>
<label>搜索原记录<input aria-label="搜索请求账本" value={query} onChange={event => setQuery(event.target.value)} placeholder="型号、请求 ID、Run 或错误原文" /></label>
<label>连接<select aria-label="筛选账本连接" value={connection} onChange={event => setConnection(event.target.value)}><option value="">全部连接</option>{ledgerConnections.map(value => <option key={value.id} value={value.id}>{value.name}</option>)}</select></label>
<label>结果<select aria-label="筛选账本结果" value={status} onChange={event => setStatus(event.target.value)}><option value="">全部结果</option>{Object.entries(states).map(([value, name]) => <option key={value} value={value}>{name}</option>)}</select></label>
<button className="button secondary" disabled={disabled}>筛选记录</button>
</form>
<div className="mc-ledger-actions"><button className="button secondary" disabled={disabled} onClick={reset}>刷新记录</button>
<button className="button secondary" disabled={disabled || !page} onClick={() => void act(() => downloadModelLedger(filters))}>导出当前范围全部记录</button>
{page && <span>{Object.keys(filters).length ? '本次筛选 ' : '当前范围 '}{page.total.toLocaleString('zh-CN')} 条 · 记录按序号分页,进行中的字段仍会更新</span>}</div>
{error && <p className="mc-card-warning" role="alert">{error}</p>}
{!loading && page?.items.length === 0 && <p className="mc-empty">当前范围没有请求记录。调整筛选不会发送模型请求。</p>}
{pager('列表上方')}
<div className="mc-attempts">{page?.items.map((value, index) => {
const source = page.references[index];
return <article key={source.sequence} data-ledger-sequence={source.sequence}>
<div><span className={'mc-state mc-state-' + value.status}>{states[value.status] ?? value.status}</span><strong>{value.model ?? '未派发'}</strong><time>{value.startedAt ? new Date(value.startedAt).toLocaleString() : '原记录未保存时间'}</time></div>
<p>{connections.find(connection => connection.id === value.connectionId)?.name || value.connectionId || '未派发'} · {value.protocol ? protocolLabel(value.protocol) : '原记录未保存协议'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p>
<ModelUsageDetails usage={value.usage} /><code>Run {value.runId ?? '原记录未保存'}</code>
<details className="mc-ledger-source"><summary>记录来源与 SHA256</summary><p>序号 {source.sequence} · {source.origin === 'legacy-metadata' ? '原账本完整迁移,原 metadata 保留' : '本次尝试独立保存'}</p>
<dl><dt>本条记录</dt><dd><code>{source.payloadSha256}</code></dd><dt>初始记录</dt><dd><code>{source.initialSha256}</code></dd></dl>
<button className="button secondary" disabled={disabled} onClick={() => void act(async () => { const record = await api('/model-center/attempts/' + source.sequence); downloadBlob(new Blob([JSON.stringify(record, null, 2)], { type: 'application/json' }), 'orven-model-request-' + source.sequence + '.json'); })}>下载本条与初始记录</button>
</details>
{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? '响应完整终结' : '响应未完整,片段保留待核对'} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? ' · 仅保存上限内片段' : ''}</p><code>原流 SHA256 {value.stream.sha256}</code></div>}
{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? '(已脱敏)' : ''}</code>}
{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={disabled} onClick={() => void act(() => downloadArtifact(value.sessionId!, value.responseArtifactId!, 'model-response-' + value.id + (value.streaming ? '.sse' : '.json')))}>下载已保存的响应</button>}
{value.requestUrl && <p className="mc-request-url">请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <><br />响应地址:{value.upstreamResponse.responseUrl}</>}</p>}
{value.reason && <p className="mc-card-warning">{value.reason}</p>}
<ModelRoutingDetails decision={value.routingDecision} /><ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model ?? '原记录未保存'} />
{value.diagnostic && <ModelErrorDetails failure={value.diagnostic} />}{!value.diagnostic && value.upstreamResponse?.requestId && <p className="mc-help">上游请求 ID:{value.upstreamResponse.requestId}</p>}
{value.requestArtifactId && value.sessionId && <button className="button secondary" disabled={disabled} onClick={() => void act(() => downloadArtifact(value.sessionId!, value.requestArtifactId!, 'model-request-' + value.id + '.json'))}>下载实际请求</button>}
{!!value.rejections?.length && <p className="mc-route-rejections">{value.rejections.map(item => item.connectionName + ':' + item.capability + ' · ' + item.reason).join(';')}</p>}
</article>;
})}</div>
{pager('列表下方')}
</section>;
}
+6
View File
@@ -36,6 +36,12 @@ export async function downloadArtifact(sessionId: string, artifactId: string, na
}
downloadBlob(await response.blob(), name);
}
export async function downloadModelLedger(filters: Record<string, string>) {
const params = new URLSearchParams(filters);
const response = await fetch('/api/model-center/attempts/export' + (params.size ? '?' + params.toString() : ''), { headers: { 'X-Workbench-Token': accessToken } });
if (!response.ok) { const value = await response.json().catch(() => ({})); throw new Error(value.error || '请求账本导出失败,请保留原记录并刷新核对。'); }
downloadBlob(await response.blob(), 'orven-model-requests.ndjson');
}
export async function downloadResearchDocument(sessionId: string, jobId: string, kind: 'bundle' | 'raw' = 'bundle') {
const response = await fetch('/api/sessions/' + sessionId + '/research/jobs/' + jobId + '/download?kind=' + kind, { headers: { 'X-Workbench-Token': accessToken } });
if (!response.ok) { const value = await response.json().catch(() => ({})); throw new Error(value.error || '研究证据下载失败。'); }
+34 -14
View File
@@ -16,6 +16,7 @@ import { modelIdentitySettings } from '../../shared/contracts/model-identity.mjs
import { NetworkDiagnostics } from './network-diagnostics.mjs';
import { ModelCatalog, credentialScope } from './model-catalog.mjs';
import { capacitySettings, routedCapacity } from '../../shared/contracts/model-capacity.mjs';
import { ModelRequestLedger } from './request-ledger.mjs';
const legacyId = 'legacy-default';
const stamp = () => new Date().toISOString();
@@ -34,11 +35,9 @@ export class ModelHub {
this.store = store; this.provider = provider;
this.state = store.storage.meta('modelRegistry', { schema: 1, revision: 0, selected: { type: 'legacy', id: legacyId }, connections: [], pools: [], imports: {} });
this.health = new Map(); this.leases = new Map(); this.cursors = new Map(); this.sticky = new Map(); this.waiting = 0;
this.attempts = store.storage.meta('modelAttempts', []);
this.ledger = new ModelRequestLedger(store.storage);
// A process exit leaves a request outcome unknown; never replay it here.
let recovered = false;
for (const attempt of this.attempts) if (attempt.status === 'running') { attempt.status = 'unknown'; attempt.finishedAt = stamp(); attempt.reason = '宿主重启,请求结果与用量待核对。'; recovered = true; }
if (recovered) this.saveAttempts();
this.ledger.recoverRunning();
provider.credentials ??= new Map();
if (store.storage.meta('modelCredentials', null)) this.vault().restore(this);
}
@@ -86,7 +85,27 @@ export class ModelHub {
throw cause;
} finally { this.editingRegistry = false; }
}
saveAttempts() { if (!unrestricted(this.store)) this.attempts = this.attempts.slice(-1000); this.store.storage.transaction(() => this.store.storage.setMeta('modelAttempts', this.attempts)); }
get attempts() { return this.compatAttempts ??= this.ledger.all(); }
set attempts(value) { this.compatAttempts = value; }
adoptRequestLedger() {
if (this.ledger) { Object.setPrototypeOf(this.ledger, ModelRequestLedger.prototype); return this.ledger; }
const retained = Object.getOwnPropertyDescriptor(this, 'attempts');
if (retained && (!Array.isArray(retained.value) || JSON.stringify(retained.value) !== JSON.stringify(this.store.storage.meta('modelAttempts', [])))) throw error('原内存请求账本与保存来源不同,请先核对,未重放任何请求。', 409);
const ledger = new ModelRequestLedger(this.store.storage);
if (retained) { delete this.attempts; this.compatAttempts = retained.value; }
this.ledger = ledger; return ledger;
}
saveAttempts(attempt = null) {
if (!attempt) return this.ledger.saveAll(this.attempts);
const sequence = this.ledger.save(attempt);
if (this.compatAttempts) {
const positions = this.compatAttempts.map((value, index) => ({ value, index })).filter(({ value }) => value === attempt || this.ledger.positions.get(value) === sequence);
const sameId = positions.length ? positions : this.compatAttempts.map((value, index) => ({ value, index })).filter(({ value }) => value.id === attempt.id);
if (sameId.length === 1) this.compatAttempts[sameId[0].index] = attempt;
}
return sequence;
}
addAttempt(attempt) { this.ledger.save(attempt); this.compatAttempts?.push(attempt); }
connections() {
const saved = this.state.legacyConnection;
return [{ ...saved, id: legacyId, name: saved?.name || this.store.config.model || '未配置模型', brand: saved?.brand || '自定义', protocol: saved?.protocol || 'chat-completions', baseUrl: this.store.config.baseUrl,
@@ -144,9 +163,10 @@ export class ModelHub {
...(this.state.capabilityResults?.[connection.id] ? { capabilityEvidence: this.state.capabilityResults[connection.id] } : {}),
capabilities: capabilityView({ ...connection, capabilityEvidence: this.state.capabilityResults?.[connection.id] }, credential?.revision ?? 0) };
}
view() { return { revision: this.state.revision, selected: this.state.selected, waitSettings: modelWaitSettings(this.store.config), connections: this.connections().map(value => this.status(value)), pools: this.state.pools,
imports: Object.entries(this.state.imports).map(([id, value]) => ({ id, ...value })), attempts: this.attempts.slice(-100).reverse(), waiting: this.waiting,
storage: { credentials: this.credentialVault ? 'memory-or-windows-user-dpapi' : 'memory', restart: '临时凭据在宿主退出后需要重新填写;已明确本机加密保存的连接按用户与原配置加载。', attemptsRetained: 1000 } }; }
view() { const page = this.ledger.page({ limit: 100 }); return { revision: this.state.revision, selected: this.state.selected, waitSettings: modelWaitSettings(this.store.config), connections: this.connections().map(value => this.status(value)), pools: this.state.pools,
imports: Object.entries(this.state.imports).map(([id, value]) => ({ id, ...value })), attempts: page.items, attemptCount: page.retainedTotal, attemptsHasMore: page.hasMore, waiting: this.waiting,
storage: { credentials: this.credentialVault ? 'memory-or-windows-user-dpapi' : 'memory', restart: '临时凭据在宿主退出后需要重新填写;已明确本机加密保存的连接按用户与原配置加载。', attemptsRetained: null,
attemptStorage: 'incremental-sqlite', attemptPreview: 100, originalMetadataPreserved: true } }; }
selectionView() {
const selected = this.state.selected;
const name = selected.type === 'pool' ? this.state.pools.find(value => value.id === selected.id)?.name
@@ -192,7 +212,7 @@ export class ModelHub {
const previous = this.state.capabilityResults[id];
const results = previous?.connectionRevision === connection.revision && previous.credentialRevision === member.credentialRevision ? { ...previous.results } : {};
results[scope] = 'verified';
const attempt = this.attempts.find(value => value.id === attemptId);
const attempt = this.ledger.find(attemptId);
if (!attempt || attempt.connectionId !== id || attempt.status !== 'completed') throw error('检测原请求账本不完整,未更新能力结论。');
this.state.capabilityResults[id] = { schema: 1, connectionRevision: connection.revision, credentialRevision: member.credentialRevision, results,
checkedAt: stamp(), protocol: modelProtocol(connection.protocol), attemptId: attempt?.id, source: 'explicit-model-probe',
@@ -364,9 +384,9 @@ export class ModelHub {
try { lease = await this.acquire(routing, runId, excluded, signal, deadline, requirements, { probe: config.capabilityProbe === true }); }
catch (cause) {
if (!lastError && cause.routingDecision) {
this.attempts.push({ id: randomUUID(), requestId, taskId: plan?.taskId ?? null, runId, sessionId: plan?.sessionId ?? null, projectId: plan?.projectId ?? null,
this.addAttempt({ id: randomUUID(), requestId, taskId: plan?.taskId ?? null, runId, sessionId: plan?.sessionId ?? null, projectId: plan?.projectId ?? null,
poolId: routing.type === 'pool' ? routing.id : null, status: 'rejected', reason: cause.message, routingDecision: cause.routingDecision,
startedAt: stamp(), finishedAt: stamp(), usage: null, usageStatus: 'not_dispatched' }); this.saveAttempts();
startedAt: stamp(), finishedAt: stamp(), usage: null, usageStatus: 'not_dispatched' });
}
throw lastError ?? cause;
}
@@ -388,7 +408,7 @@ export class ModelHub {
this.store.core.artifact.set(artifact.id, artifact);
this.store.save(session);
}
this.attempts.push(attempt); this.saveAttempts();
this.addAttempt(attempt);
const progress = event => {
if (event.modelIdentity) attempt.modelIdentity = event.modelIdentity;
if (event.wireAttemptId) attempt.wireAttemptId = event.wireAttemptId;
@@ -398,7 +418,7 @@ export class ModelHub {
attempt.usage = event.consumption.usage; attempt.usageStatus = event.consumption.usageStatus;
onProgress?.({ consumption: { ...event.consumption, wireAttemptId: event.consumption.attemptId, attemptId: attempt.id,
connectionId: member.id, connectionName: member.name }, connectionId: member.id, model: member.model, modelAttemptId: attempt.id });
this.saveAttempts();
this.saveAttempts(attempt);
return;
}
if (event.streamCapture !== undefined || event.responseCapture !== undefined) {
@@ -456,7 +476,7 @@ export class ModelHub {
if (config.capacityMode === 'passthrough' || (!diagnostic?.retryable && !diagnostic?.failoverAllowed) || count === routing.maxAttempts) throw cause;
onProgress?.({ phase: 'retrying', attempt: count, maxAttempts: routing.maxAttempts, connectionId: member.id, modelAttemptId: attempt.id,
diagnostic, waitMs: 0, switching: true });
} finally { attempt.finishedAt = stamp(); lease.release(); this.saveAttempts(); }
} finally { attempt.finishedAt = stamp(); lease.release(); this.saveAttempts(attempt); }
}
throw lastError ?? new ModelRequestError({ message: '模型池请求未完成。', kind: 'connection' });
}
+190
View File
@@ -0,0 +1,190 @@
import { randomUUID, createHash } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
const metadataKey = 'modelAttemptLedger';
const sha = value => createHash('sha256').update(value).digest('hex');
const invalid = (message, status = 400) => Object.assign(new Error(message), { status });
const fields = { connectionId: 'connection_id', sessionId: 'session_id', taskId: 'task_id', runId: 'run_id', status: 'status', model: 'model', protocol: 'protocol' };
const ownership = value => JSON.stringify([value.id, value.connectionId ?? null, value.poolId ?? null, value.projectId ?? null, value.sessionId ?? null, value.taskId ?? null, value.runId ?? null, value.requestId ?? null, value.model ?? null, value.protocol ?? null]);
const integer = (value, minimum = 0) => Number.isSafeInteger(value) && value >= minimum;
const reference = row => ({ sequence: row.seq, payloadSha256: row.payload_sha256, initialSha256: row.initial_sha256,
origin: row.legacy_position === null ? 'incremental-ledger' : 'legacy-metadata', ...(row.legacy_position === null ? {} : { legacyIndex: row.legacy_position }) });
export function ledgerQuery(url, { exportOnly = false } = {}) {
const allowed = [...Object.keys(fields), 'query', ...(exportOnly ? [] : ['cursor', 'limit'])], params = url.searchParams;
for (const key of params.keys()) if (!allowed.includes(key) || params.getAll(key).length !== 1) throw invalid('请求账本查询参数无效。');
return { ...(exportOnly ? {} : { cursor: params.get('cursor'), limit: params.get('limit') ?? 50 }),
filters: Object.fromEntries([...Object.keys(fields), 'query'].filter(key => params.has(key) && params.get(key) !== '').map(key => [key, params.get(key)])) };
}
function where(filters = {}) {
const terms = [], parameters = [];
for (const key of Object.keys(filters).sort()) {
const value = filters[key]; if (typeof value !== 'string' || !value || ![...Object.keys(fields), 'query'].includes(key)) throw invalid('请求账本筛选字段无效。');
if (key === 'query') { terms.push("payload LIKE ? ESCAPE '\\'"); parameters.push('%' + value.replace(/[\\%_]/g, '\\$&') + '%'); }
else { terms.push(fields[key] + '=?'); parameters.push(value); }
}
return { sql: terms.length ? ' AND ' + terms.join(' AND ') : '', parameters };
}
function decode(row) {
if (sha(row.payload) !== row.payload_sha256) throw invalid('本机请求账本原记录 SHA256 不匹配,请核对保存来源。', 409);
return JSON.parse(row.payload);
}
// The legacy metadata stays byte-for-byte in its original row. A one-time
// transaction copies its entries into an indexed table. New requests update
// only their own row; the all-records accessor is compatibility/read-only use.
export class ModelRequestLedger {
constructor(storage) {
this.storage = storage; this.database = storage.database; this.positions = new WeakMap(); this.serialized = new WeakMap();
const originalVersion = this.database.prepare('PRAGMA user_version').get().user_version;
const state = storage.meta(metadataKey);
if (state && state.schemaVersion !== 1) throw invalid('请求账本由未接入的新版本创建,请使用对应程序。', 409);
if (!state) {
const original = this.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get()?.value;
const entries = original ? JSON.parse(original) : [];
if (!Array.isArray(entries) || entries.some(value => !value || typeof value !== 'object' || Array.isArray(value) || typeof value.id !== 'string' || !value.id)) throw invalid('原请求账本格式无法完整迁移,原 metadata 已保留。', 409);
this.state = { schemaVersion: 1, id: randomUUID(), legacyEntries: entries.length, legacyMetadataSha256: original ? sha(original) : null,
originalMetadataPreserved: true, migratedAt: new Date().toISOString() };
storage.transaction(() => {
this.database.exec(`CREATE TABLE IF NOT EXISTS model_attempts (
seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, connection_id TEXT, session_id TEXT, task_id TEXT, run_id TEXT,
status TEXT, model TEXT, protocol TEXT, legacy_position INTEGER UNIQUE,
payload TEXT NOT NULL CHECK(json_valid(payload)), payload_sha256 TEXT NOT NULL,
initial_payload TEXT NOT NULL CHECK(json_valid(initial_payload)), initial_sha256 TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS model_attempts_id ON model_attempts(id);
CREATE INDEX IF NOT EXISTS model_attempts_connection ON model_attempts(connection_id,seq);
CREATE INDEX IF NOT EXISTS model_attempts_session ON model_attempts(session_id,task_id,run_id,seq);
CREATE INDEX IF NOT EXISTS model_attempts_status ON model_attempts(status,seq);`);
for (const [index, entry] of entries.entries()) this.insert(entry, JSON.stringify(entry), index);
storage.setMeta(metadataKey, this.state);
this.database.exec('PRAGMA user_version=2');
});
this.initialization = { originalVersion };
} else {
this.state = state;
if (originalVersion < 2) storage.transaction(() => this.database.exec('PRAGMA user_version=2'));
}
}
insert(value, serialized, legacyIndex = null) {
const result = this.database.prepare(`INSERT INTO model_attempts(id,connection_id,session_id,task_id,run_id,status,model,protocol,legacy_position,payload,payload_sha256,initial_payload,initial_sha256)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(value.id, value.connectionId ?? null, value.sessionId ?? null, value.taskId ?? null, value.runId ?? null,
value.status ?? null, value.model ?? null, value.protocol ?? null, legacyIndex, serialized, sha(serialized), serialized, sha(serialized));
return Number(result.lastInsertRowid);
}
attach(row) { const value = decode(row); this.positions.set(value, row.seq); this.serialized.set(value, row.payload); return value; }
all() { return this.database.prepare('SELECT * FROM model_attempts ORDER BY seq').all().map(row => this.attach(row)); }
find(id) { const rows = this.database.prepare('SELECT * FROM model_attempts WHERE id=?').all(id); if (rows.length > 1) throw invalid('请求账本原身份不唯一,请按序号核对。', 409); return rows[0] ? decode(rows[0]) : undefined; }
rollbackInitialization() {
if (!this.initialization) return false;
// A failed synchronous handler adoption has not dispatched any request.
// Revert only this verified migration, never a ledger with new outcomes.
this.storage.transaction(() => {
const state = this.storage.meta(metadataKey), original = this.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get()?.value;
const entries = original ? JSON.parse(original) : [], rows = this.database.prepare('SELECT * FROM model_attempts ORDER BY seq').all();
if (state?.id !== this.state.id || (original ? sha(original) : null) !== this.state.legacyMetadataSha256 || rows.length !== entries.length
|| rows.some((row, index) => row.legacy_position !== index || row.payload !== row.initial_payload || row.initial_payload !== JSON.stringify(entries[index])
|| sha(row.payload) !== row.payload_sha256 || sha(row.initial_payload) !== row.initial_sha256)) throw invalid('请求账本已有新记录或来源变化,不能回退原迁移,请保留现场核对。', 409);
this.database.exec('DROP TABLE model_attempts; PRAGMA user_version=' + this.initialization.originalVersion);
this.database.prepare('DELETE FROM metadata WHERE key=?').run(metadataKey);
});
this.initialization = null; return true;
}
save(value) { return this.saveAll([value])[0]; }
saveAll(values) {
if (values.every(value => value && this.serialized.get(value) === JSON.stringify(value))) return values.map(value => this.positions.get(value));
const updates = [];
this.storage.transaction(() => {
for (const value of values) {
if (!value || typeof value !== 'object' || typeof value.id !== 'string' || !value.id) throw invalid('请求账本记录需要原尝试身份。');
const serialized = JSON.stringify(value); if (this.serialized.get(value) === serialized) continue;
const sequence = this.positions.get(value), matches = sequence ? [this.database.prepare('SELECT * FROM model_attempts WHERE seq=?').get(sequence)]
: this.database.prepare('SELECT * FROM model_attempts WHERE id=?').all(value.id);
if (matches.length > 1 || sequence && !matches[0]) throw invalid('请求账本记录身份不唯一或原行已变化,请核对来源。', 409);
let savedSequence;
if (matches[0]) {
const original = decode(matches[0]);
if (this.serialized.has(value) && this.serialized.get(value) !== matches[0].payload) throw invalid('请求账本原记录已更新,请核对保存来源,不能覆盖另一份进展。', 409);
if (ownership(original) !== ownership(value)) throw invalid('请求账本记录不能移动到其他连接、型号、协议、会话或任务。', 409);
this.database.prepare('UPDATE model_attempts SET status=?,payload=?,payload_sha256=? WHERE seq=?').run(value.status ?? null, serialized, sha(serialized), matches[0].seq);
savedSequence = matches[0].seq;
} else savedSequence = this.insert(value, serialized);
updates.push({ value, serialized, sequence: savedSequence });
}
});
for (const update of updates) { this.positions.set(update.value, update.sequence); this.serialized.set(update.value, update.serialized); }
return values.map(value => this.positions.get(value));
}
recoverRunning() {
const running = this.database.prepare("SELECT * FROM model_attempts WHERE status='running' ORDER BY seq").all().map(row => this.attach(row));
for (const value of running) { value.status = 'unknown'; value.finishedAt = new Date().toISOString(); value.reason = '宿主重启,请求结果与用量待核对。'; }
if (running.length) this.saveAll(running); return running.length;
}
page({ cursor = null, limit = 50, filters = {} } = {}) {
if (!/^\d+$/.test(String(limit)) || !integer(Number(limit), 1)) throw invalid('请求账本每页数量需要正整数。');
const filtered = where(filters), scope = sha(JSON.stringify({ ledger: this.state.id, filters: Object.fromEntries(Object.entries(filters).sort()) }));
const current = this.database.prepare('SELECT COALESCE(MAX(seq),0) AS seq,COUNT(*) AS total FROM model_attempts').get();
let snapshot = current.seq, before = null;
if (cursor !== null) {
let value; try { if (typeof cursor !== 'string' || !/^[A-Za-z0-9_-]+$/.test(cursor)) throw new Error(); value = JSON.parse(Buffer.from(cursor, 'base64url').toString()); } catch { throw invalid('请求账本游标无效。'); }
if (value?.schemaVersion !== 1 || value.scope !== scope || !integer(value.snapshot) || !integer(value.before, 1) || value.before > value.snapshot || value.snapshot > current.seq) throw invalid('请求账本游标不属于当前筛选或来源。');
snapshot = value.snapshot; before = value.before;
if (!this.database.prepare('SELECT seq FROM model_attempts WHERE seq=? AND seq<=?' + filtered.sql).get(before, snapshot, ...filtered.parameters)) throw invalid('请求账本原游标已变化,请刷新记录。', 409);
}
const count = this.database.prepare('SELECT COUNT(*) AS total FROM model_attempts WHERE seq<=?' + filtered.sql).get(snapshot, ...filtered.parameters).total;
const rows = this.database.prepare('SELECT * FROM model_attempts WHERE seq<=?' + (before === null ? '' : ' AND seq<?') + filtered.sql + ' ORDER BY seq DESC LIMIT ?')
.all(snapshot, ...(before === null ? [] : [before]), ...filtered.parameters, Number(limit) < Number.MAX_SAFE_INTEGER ? Number(limit) + 1 : Number(limit));
const shown = rows.slice(0, Number(limit)), hasMore = rows.length > Number(limit);
return { schemaVersion: 1, items: shown.map(row => decode(row)), references: shown.map(reference), total: count, retainedTotal: current.total, snapshotSequence: snapshot,
connectionIds: this.database.prepare('SELECT DISTINCT connection_id FROM model_attempts WHERE connection_id IS NOT NULL ORDER BY connection_id').all().map(row => row.connection_id),
hasMore, nextCursor: hasMore ? Buffer.from(JSON.stringify({ schemaVersion: 1, scope, snapshot, before: shown.at(-1).seq })).toString('base64url') : null,
filters, source: this.state, viewSnapshot: 'sequence-watermark; running record fields can still update' };
}
record(sequence) {
if (!/^\d+$/.test(String(sequence)) || !integer(Number(sequence), 1)) throw invalid('请求账本序号无效。');
const row = this.database.prepare('SELECT * FROM model_attempts WHERE seq=?').get(Number(sequence)); if (!row) throw invalid('请求账本原记录不存在。', 404);
if (sha(row.initial_payload) !== row.initial_sha256) throw invalid('请求账本初始来源 SHA256 不匹配。', 409);
return { item: decode(row), reference: reference(row), initial: { item: JSON.parse(row.initial_payload), sha256: row.initial_sha256 } };
}
exportSnapshot(filters = {}) {
const filtered = where(filters), database = new DatabaseSync(this.storage.filename, { readOnly: true });
try {
database.exec('PRAGMA query_only=ON; PRAGMA busy_timeout=5000; BEGIN;');
const snapshot = database.prepare('SELECT COALESCE(MAX(seq),0) AS seq FROM model_attempts').get().seq;
const count = database.prepare('SELECT COUNT(*) AS total FROM model_attempts WHERE seq<=?' + filtered.sql).get(snapshot, ...filtered.parameters).total;
const rows = database.prepare('SELECT * FROM model_attempts WHERE seq<=?' + filtered.sql + ' ORDER BY seq').iterate(snapshot, ...filtered.parameters);
return { header: { schemaVersion: 1, type: 'header', format: 'orven-model-attempts-ndjson', snapshotSequence: snapshot, expectedRecords: count,
filters, source: this.state, recordedAt: new Date().toISOString(), snapshot: 'SQLite read transaction', includesInitialReceipts: true, artifactBodies: 'Original artifacts remain separately downloadable by their saved session/ID/SHA.' }, rows,
close() { try { rows.return?.(); database.exec('ROLLBACK'); } finally { database.close(); } } };
} catch (cause) { database.close(); throw cause; }
}
}
export async function streamLedgerExport(response, snapshot) {
const checksum = createHash('sha256'); let count = 0;
const write = async line => {
if (response.destroyed || response.writableEnded) throw invalid('请求账本导出连接已关闭。', 499);
// ServerResponse can report backpressure after its socket has already
// flushed, without emitting another drain. The chunk callback reports
// actual write completion and bounds queued data to this one record.
await new Promise((resolve, reject) => {
let settled = false;
const clear = () => { response.off('close', closed); response.off('error', failed); };
const finish = error => { if (settled) return; settled = true; clear(); error ? reject(error) : resolve(); };
const closed = () => finish(invalid('请求账本导出被中断,部分内容不能当作完整导出。', 499)), failed = error => finish(error);
response.once('close', closed); response.once('error', failed);
try { response.write(line, finish); } catch (cause) { finish(cause); }
});
};
try {
await write(JSON.stringify(snapshot.header) + '\n');
for (const row of snapshot.rows) {
decode(row); if (sha(row.initial_payload) !== row.initial_sha256) throw invalid('请求账本初始来源 SHA256 不匹配。', 409);
const line = '{"type":"attempt","reference":' + JSON.stringify(reference(row)) + ',"item":' + row.payload
+ ',"initial":{"sha256":' + JSON.stringify(row.initial_sha256) + ',"item":' + row.initial_payload + '}}\n';
checksum.update(line); await write(line); count++;
}
if (count !== snapshot.header.expectedRecords) throw invalid('请求账本导出数量与快照不匹配。', 409);
await write(JSON.stringify({ type: 'footer', complete: true, records: count, recordLinesSha256: checksum.digest('hex') }) + '\n'); response.end();
} finally { snapshot.close(); }
}
+11 -3
View File
@@ -1,9 +1,9 @@
import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { randomUUID } from 'node:crypto';
import { randomUUID, createHash } from 'node:crypto';
const DATABASE_SCHEMA = 1;
const DATABASE_SCHEMA = 2;
export class StateDatabase {
constructor(directory, { faultInjector } = {}) {
@@ -27,7 +27,7 @@ export class StateDatabase {
task_id TEXT, run_id TEXT, type TEXT NOT NULL, revision INTEGER NOT NULL, created_at TEXT NOT NULL, payload TEXT NOT NULL CHECK(json_valid(payload)));
CREATE INDEX IF NOT EXISTS events_session ON events(session_id,seq);
CREATE TABLE IF NOT EXISTS outbox (seq INTEGER PRIMARY KEY REFERENCES events(seq), published_at TEXT);
PRAGMA user_version=${DATABASE_SCHEMA};
PRAGMA user_version=${Math.max(version, 1)};
`);
} catch (error) { this.database.close(); throw error; }
}
@@ -39,6 +39,14 @@ export class StateDatabase {
}
meta(key, fallback = null) {
// Legacy in-process readers receive the full ledger projection. The
// original metadata row remains unchanged for archived source verification.
if (key === 'modelAttempts' && this.database.prepare("SELECT value FROM metadata WHERE key='modelAttemptLedger'").get()) {
return this.database.prepare('SELECT payload,payload_sha256 FROM model_attempts ORDER BY seq').all().map(row => {
if (createHash('sha256').update(row.payload).digest('hex') !== row.payload_sha256) throw new Error('本机请求账本原记录 SHA256 不匹配,请核对保存来源。');
return JSON.parse(row.payload);
});
}
const row = this.database.prepare('SELECT value FROM metadata WHERE key=?').get(key);
return row ? JSON.parse(row.value) : structuredClone(fallback);
}
+9
View File
@@ -26,6 +26,7 @@ import { nativeParameterSettings } from '../shared/contracts/native-parameters.m
import { localDirectories } from './local-directories.mjs';
import { readInstallationProgress } from '../core/desktop/installation-progress.mjs';
import { recordPageQuery } from '../shared/contracts/record-page.mjs';
import { ledgerQuery, streamLedgerExport } from '../core/models/request-ledger.mjs';
export function createSessionPublisher(clients) {
return session => {
@@ -204,6 +205,14 @@ return async (request, response) => {
const hub = provider.modelHub(store);
const importer = () => hub.importer ??= new ConfigImporter(hub);
if (method === 'GET' && route === '/api/model-center') return json(response, hub.view());
if (method === 'GET' && route === '/api/model-center/attempts') return json(response, hub.ledger.page(ledgerQuery(url)));
if (method === 'GET' && route === '/api/model-center/attempts/export') {
const snapshot = hub.ledger.exportSnapshot(ledgerQuery(url, { exportOnly: true }).filters);
response.writeHead(200, { 'Content-Type': 'application/x-ndjson; charset=utf-8', 'Content-Disposition': 'attachment; filename="orven-model-requests.ndjson"', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
await streamLedgerExport(response, snapshot); return;
}
const attemptRecord = route.match(/^\/api\/model-center\/attempts\/([0-9]+)$/);
if (method === 'GET' && attemptRecord) return json(response, hub.ledger.record(attemptRecord[1]));
if (method === 'GET' && route === '/api/model-center/network-diagnostics') return json(response, hub.networkDiagnostics().view());
const networkStop = route.match(/^\/api\/model-center\/network-diagnostics\/([a-f0-9-]{36})\/stop$/i);
if (method === 'POST' && networkStop) return json(response, await hub.networkDiagnostics().stop(networkStop[1], await body(request)));
+10
View File
@@ -12,6 +12,7 @@ import { APP_VERSION } from './diagnostics.mjs';
import { hostAuthority } from '../core/desktop/host-authority.mjs';
import { CredentialVault } from '../core/models/credential-vault.mjs';
import { NetworkDiagnostics } from '../core/models/network-diagnostics.mjs';
import { StateDatabase } from '../core/storage/state-database.mjs';
// Keep the existing objects and their in-memory connection. No credential is
// extracted, transferred, returned, or persisted by this operation.
@@ -34,11 +35,14 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
const oldAuthorityPrototype = oldAuthority ? Object.getPrototypeOf(oldAuthority) : null;
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
const oldModelPrototypes = { hub: provider.hub ? Object.getPrototypeOf(provider.hub) : null,
ledger: provider.hub?.ledger ? Object.getPrototypeOf(provider.hub.ledger) : null,
importer: provider.hub?.importer ? Object.getPrototypeOf(provider.hub.importer) : null,
vault: provider.hub?.credentialVault ? Object.getPrototypeOf(provider.hub.credentialVault) : null,
network: provider.hub?.networkChecks ? Object.getPrototypeOf(provider.hub.networkChecks) : null,
catalog: provider.hub?.catalog ? Object.getPrototypeOf(provider.hub.catalog) : null };
const oldStoreProperties = { ...store };
const oldHubProperties = provider.hub ? { ...provider.hub } : null, oldStoragePrototype = store.storage ? Object.getPrototypeOf(store.storage) : null;
let initializedLedger = null;
const oldRuntimeProperties = { filePreviews: runtime.filePreviews, browsing: runtime.browsing, previews: runtime.previews, evaluations:runtime.evaluations, environments: runtime.environments, appDirectory: runtime.appDirectory, workers: runtime.workers, controlledEngines: runtime.controlledEngines, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser, taskPlans: runtime.taskPlans, projectMemories: runtime.projectMemories, taskCheckpoints: runtime.taskCheckpoints, skills: runtime.skills, mcp: runtime.mcp };
const oldUpdates = store.listeners('update');
const oldInputs = runtime.inputs;
@@ -64,11 +68,13 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
runtime.results = null;
runtime.resumes = null;
store.ensureStorage();
Object.setPrototypeOf(store.storage, StateDatabase.prototype);
// A SQLite host can retain an artifact object from an earlier bundle.
// Reopen the same blobs through the new API without mutating that object;
// oldStoreProperties restores it if installing this handler fails.
store.artifactStore = new ArtifactStore(store.directory);
store.claimRuntime();
if (provider.hub) { const retainedLedger = provider.hub.ledger; provider.hub.adoptRequestLedger(); if (!retainedLedger) initializedLedger = provider.hub.ledger; }
store.removeAllListeners('update'); store.on('update', createSessionPublisher(clients));
server.removeAllListeners('request'); server.on('request', handler);
server.prependOnceListener('close', closeStorage);
@@ -79,6 +85,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
void oldRuntimeProperties.filePreviews?.stopAll();
return { version: APP_VERSION, pid: process.pid, hasKey: provider.hasKey(), projects: store.projects.length, sessions: store.sessions.size, appDirectory: root };
} catch (error) {
initializedLedger?.rollbackInitialization();
if (oldCompanion) server.workbenchCompanion = oldCompanion; else delete server.workbenchCompanion;
if (oldAuthority) {
for (const key of Object.keys(oldAuthority)) if (!Object.hasOwn(oldAuthorityProperties, key)) delete oldAuthority[key];
@@ -98,7 +105,10 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
if (oldInputs === undefined) delete runtime.inputs; else runtime.inputs = oldInputs;
if (oldResumes === undefined) delete runtime.resumes; else runtime.resumes = oldResumes;
Object.setPrototypeOf(store, oldPrototypes[0]); Object.setPrototypeOf(provider, oldPrototypes[1]); Object.setPrototypeOf(runtime, oldPrototypes[2]);
if (oldStoragePrototype && store.storage === oldStoreProperties.storage) Object.setPrototypeOf(store.storage, oldStoragePrototype);
if (oldHubProperties) { for (const key of Object.keys(provider.hub)) if (!Object.hasOwn(oldHubProperties, key)) delete provider.hub[key]; Object.assign(provider.hub, oldHubProperties); }
if (oldModelPrototypes.hub) Object.setPrototypeOf(provider.hub, oldModelPrototypes.hub);
if (oldModelPrototypes.ledger) Object.setPrototypeOf(provider.hub.ledger, oldModelPrototypes.ledger);
if (oldModelPrototypes.importer) Object.setPrototypeOf(provider.hub.importer, oldModelPrototypes.importer);
if (oldModelPrototypes.vault) Object.setPrototypeOf(provider.hub.credentialVault, oldModelPrototypes.vault);
if (oldModelPrototypes.network) Object.setPrototypeOf(provider.hub.networkChecks, oldModelPrototypes.network);
+1 -1
View File
@@ -51,7 +51,7 @@ export function inspectOperations({ store, provider, runtime, server, appDirecto
for (const directory of [...new Set([path.resolve(appDirectory), path.resolve(store.directory)])]) { const value = fs.statfsSync(directory, { bigint: true }), bytes = value.bavail * value.bsize; disk.push({ directory, freeBytes: bytes.toString(), status: bytes < 64n * 1024n * 1024n ? 'attention' : 'passed' }); }
return { status: disk.some(value => value.status === 'attention') ? 'attention' : 'passed', detail: disk.map(value => value.directory + ' · 剩余' + Number(BigInt(value.freeBytes) / (1024n * 1024n)).toLocaleString() + ' MB').join(';') };
});
return { version, checkedAt: new Date().toISOString(), checks, activeTasks: runtime.active.size, queue: center.waiting, modelAttempts: center.attempts.length, modelRequests: 0,
return { version, checkedAt: new Date().toISOString(), checks, activeTasks: runtime.active.size, queue: center.waiting, modelAttempts: center.attemptCount, modelRequests: 0,
artifacts, activity, unknown: { total: unknown.length, items: unknown.slice(0, 100), omitted: Math.max(0, unknown.length - 100) }, sources, disk,
scope: '本地只读巡检:数据库quick_check、明确分页的原工件、现有管理器与待核对归属、当前程序/已登记来源及磁盘余量;不发送模型请求、不执行项目命令或自动修复。一次分页通过不代表全部历史工件已核对。' };
}
+1 -1
View File
@@ -747,7 +747,7 @@ export class Store extends EventEmitter {
get eventCursor() { return this.storage.cursor; }
eventsAfter(cursor, options) { return this.storage.eventsAfter(cursor, options); }
storageInfo() {
return { engine: 'sqlite', schemaVersion: 1, eventCursor: this.eventCursor, pendingPublications: this.storage.pendingPublications(),
return { engine: 'sqlite', schemaVersion: this.storage.database.prepare('PRAGMA user_version').get().user_version, eventCursor: this.eventCursor, pendingPublications: this.storage.pendingPublications(),
migratedFromJson: !!this.storage.meta('migration'), recovery: 'verify-unknown-results', compatibilityExport: 'explicit-json' };
}
+2
View File
@@ -1,5 +1,7 @@
# Agent Workbench:核心代理能力研究与产品计划
当前M2第二批I13:[计划](docs/M2-REQUEST-LEDGER-PLAN.md)阶段1–4完成,源码da2e6313/最终build-4独立39/39、candidate-app-5网页与实际Electron各5组/7图/23页通过。830输入/285产品源码/29编译一致,4328原件/16源码Git blob只读验封;相关102/102发生在最后公开版本修正前,分开保留。阶段5验收文档与授权GitAtlas增量推送收尾,下一I15及I09/I11/I12/I14、CI,再M3明确schema2安装/回退。正式未部署/重启或新health复查,默认透传/持久权限和历史unknown保持。
M2首批I10:源码cb60fb11/相关93/独立23/网页与实际Electron各5组已完成,2948原件SHA封存;验收文档提交与授权GitAtlas增量推送收尾。下一I13完整请求账本/逐请求存储,再M2其余和M3,正式未部署/重启,真实收益unknown。
当前M2首批I10从ea2559df干净/远端一致基线开始,见docs/M2-CACHE-USAGE-PLAN.md。先按官方合同补缓存read/write/uncached/reasoning与来源、现有上下文/请求账本显示,保留raw/旧usage/unknown;逐阶段验收提交推送。M2注册表/原生块/状态/完整账本/CI仍另列,M3统一发行,不触真实模型/Key/正式数据或续旧实验。
+8
View File
@@ -0,0 +1,8 @@
{
"base": "a93bfd6885decdbfe33c8f16c9b16771984599cb",
"sourcePath": "src/core/storage/state-database.mjs",
"bytes": 8565,
"sha256": "2a38f7564df44c4ee5183d850064be1d46fba7e072e2b87f73afb8e1a85a1517",
"gitBlob": "75173d0872981f5eebaeca371017e3f50fe135a5",
"scope": "Exact previous committed storage source, used only with owned test data to verify schema compatibility and failed handler migration rollback."
}
+130
View File
@@ -0,0 +1,130 @@
import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { randomUUID } from 'node:crypto';
const DATABASE_SCHEMA = 1;
export class StateDatabase {
constructor(directory, { faultInjector } = {}) {
this.filename = path.join(directory, 'workbench.sqlite');
this.faultInjector = faultInjector;
this.database = new DatabaseSync(this.filename);
try {
const version = this.database.prepare('PRAGMA user_version').get().user_version;
if (version > DATABASE_SCHEMA) throw new Error('任务数据库由更新版本创建,请使用对应版本打开。');
this.database.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
this.database.exec(`
CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL CHECK(json_valid(value)));
CREATE TABLE IF NOT EXISTS projects (id TEXT PRIMARY KEY, position INTEGER NOT NULL, payload TEXT NOT NULL CHECK(json_valid(payload)));
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, project_id TEXT NOT NULL REFERENCES projects(id), revision INTEGER NOT NULL, payload TEXT NOT NULL CHECK(json_valid(payload)));
CREATE TABLE IF NOT EXISTS records (
kind TEXT NOT NULL, id TEXT NOT NULL, session_id TEXT NOT NULL REFERENCES sessions(id), project_id TEXT NOT NULL REFERENCES projects(id),
task_id TEXT, run_id TEXT, status TEXT, payload TEXT NOT NULL CHECK(json_valid(payload)), PRIMARY KEY(kind,id));
CREATE INDEX IF NOT EXISTS records_owner ON records(kind,session_id,task_id,run_id);
CREATE TABLE IF NOT EXISTS events (
seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, session_id TEXT NOT NULL REFERENCES sessions(id), project_id TEXT NOT NULL,
task_id TEXT, run_id TEXT, type TEXT NOT NULL, revision INTEGER NOT NULL, created_at TEXT NOT NULL, payload TEXT NOT NULL CHECK(json_valid(payload)));
CREATE INDEX IF NOT EXISTS events_session ON events(session_id,seq);
CREATE TABLE IF NOT EXISTS outbox (seq INTEGER PRIMARY KEY REFERENCES events(seq), published_at TEXT);
PRAGMA user_version=${DATABASE_SCHEMA};
`);
} catch (error) { this.database.close(); throw error; }
}
transaction(action) {
this.database.exec('BEGIN IMMEDIATE');
try { const result = action(); this.faultInjector?.('before_commit'); this.database.exec('COMMIT'); return result; }
catch (error) { try { this.database.exec('ROLLBACK'); } catch {} throw error; }
}
meta(key, fallback = null) {
const row = this.database.prepare('SELECT value FROM metadata WHERE key=?').get(key);
return row ? JSON.parse(row.value) : structuredClone(fallback);
}
setMeta(key, value) {
this.database.prepare('INSERT INTO metadata(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key, JSON.stringify(value));
}
get initialized() { return this.meta('initialized', false); }
get cursor() { return this.database.prepare('SELECT COALESCE(MAX(seq),0) AS seq FROM events').get().seq; }
writeProjects(projects) {
const statement = this.database.prepare('INSERT INTO projects(id,position,payload) VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET position=excluded.position,payload=excluded.payload');
projects.forEach((project, index) => statement.run(project.id, index, JSON.stringify(project)));
}
writeSession(session) {
const existing = this.database.prepare('SELECT project_id FROM sessions WHERE id=?').get(session.id);
if (existing && existing.project_id !== session.projectId) throw new Error('会话不能移动到其他项目。');
this.database.prepare('INSERT INTO sessions(id,project_id,revision,payload) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,payload=excluded.payload').run(
session.id, session.projectId, session.revision ?? 0, JSON.stringify(session));
}
writeRecords(records) {
const statement = this.database.prepare(`INSERT INTO records(kind,id,session_id,project_id,task_id,run_id,status,payload) VALUES(?,?,?,?,?,?,?,?)
ON CONFLICT(kind,id) DO UPDATE SET status=excluded.status,payload=excluded.payload`);
for (const record of records) {
const existing = this.database.prepare('SELECT session_id,project_id,task_id,run_id FROM records WHERE kind=? AND id=?').get(record.kind, record.id);
if (existing && (existing.session_id !== record.sessionId || existing.project_id !== record.projectId || existing.task_id !== record.taskId || existing.run_id !== record.runId)) {
throw new Error('持久执行记录不能移动到其他任务或项目。');
}
statement.run(record.kind, record.id, record.sessionId, record.projectId, record.taskId, record.runId, record.status, JSON.stringify(record.value));
}
}
appendEvent(session, type, payload) {
const entry = { id: randomUUID(), sessionId: session.id, projectId: session.projectId,
taskId: session.taskId ?? null, runId: session.runId ?? null, revision: session.revision ?? 0,
type, createdAt: new Date().toISOString(), payload };
const result = this.database.prepare('INSERT INTO events(id,session_id,project_id,task_id,run_id,type,revision,created_at,payload) VALUES(?,?,?,?,?,?,?,?,?)').run(
entry.id, entry.sessionId, entry.projectId, entry.taskId, entry.runId, type, entry.revision, entry.createdAt, JSON.stringify(payload));
entry.seq = Number(result.lastInsertRowid);
this.database.prepare('INSERT INTO outbox(seq) VALUES(?)').run(entry.seq);
return entry;
}
initialize({ projects, config, sessions, records, migration }) {
return this.transaction(() => {
this.writeProjects(projects); this.setMeta('config', config);
for (const session of sessions) {
this.writeSession(session);
session.eventSeq = this.appendEvent(session, 'session.imported', { status: session.status, source: migration ? 'json-v1' : 'new' }).seq;
this.writeSession(session);
}
this.writeRecords(records); this.faultInjector?.('migration_records');
this.setMeta('migration', migration); this.setMeta('initialized', true);
});
}
save(session, records, type, payload) {
return this.transaction(() => {
this.writeSession(session); this.writeRecords(records); this.faultInjector?.('after_state');
const event = this.appendEvent(session, type, payload);
session.eventSeq = event.seq; this.writeSession(session); this.faultInjector?.('after_event');
return event;
});
}
load() {
return {
projects: this.database.prepare('SELECT payload FROM projects ORDER BY position').all().map(row => JSON.parse(row.payload)),
config: this.meta('config', {}),
sessions: this.database.prepare('SELECT payload FROM sessions').all().map(row => JSON.parse(row.payload)),
records: this.database.prepare('SELECT kind,payload FROM records').all().map(row => ({ kind: row.kind, value: JSON.parse(row.payload) })),
};
}
eventsAfter(cursor = 0, { sessionId = null, limit = 100 } = {}) {
if (!Number.isSafeInteger(cursor) || cursor < 0 || !Number.isInteger(limit) || limit < 1 || limit > 500) throw new Error('事件游标或分页范围无效。');
const rows = sessionId
? this.database.prepare('SELECT * FROM events WHERE seq>? AND session_id=? ORDER BY seq LIMIT ?').all(cursor, sessionId, limit + 1)
: this.database.prepare('SELECT * FROM events WHERE seq>? ORDER BY seq LIMIT ?').all(cursor, limit + 1);
const events = rows.slice(0, limit).map(row => ({ seq: row.seq, id: row.id, sessionId: row.session_id, projectId: row.project_id,
taskId: row.task_id, runId: row.run_id, revision: row.revision, type: row.type, createdAt: row.created_at, payload: JSON.parse(row.payload) }));
return { events, nextCursor: events.at(-1)?.seq ?? cursor, hasMore: rows.length > limit, currentCursor: this.cursor };
}
published(seq) { this.database.prepare('UPDATE outbox SET published_at=? WHERE seq=?').run(new Date().toISOString(), seq); }
pendingPublications() { return this.database.prepare('SELECT COUNT(*) AS count FROM outbox WHERE published_at IS NULL').get().count; }
close() { if (this.database) { this.database.close(); this.database = null; } }
}
export function runtimeOwnerAlive(owner) {
if (!owner?.pid || owner.pid === process.pid) return false;
try { process.kill(owner.pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
}
+23
View File
@@ -0,0 +1,23 @@
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
export function historicalAttempts(count = 1107) {
return Array.from({ length: count }, (_, index) => ({ id: 'owned-history-' + index, connectionId: index % 2 ? 'owned-beta' : 'owned-alpha',
model: 'owned-history-model-' + (index % 3), protocol: 'chat-completions', runId: 'owned-run-' + index, taskId: 'owned-task-' + Math.floor(index / 3),
sessionId: 'owned-session-' + Math.floor(index / 10), projectId: 'owned-project', ordinal: 1, status: index % 7 ? 'completed' : 'failed',
startedAt: '2026-11-01T00:00:00Z', finishedAt: '2026-11-01T00:00:01Z', ...(index % 7 ? {} : { reason: '历史上游原错误 HTTP 400 · 未自动重发' }),
usageStatus: index % 5 ? 'reported' : 'unknown', usage: index % 5 ? { prompt_tokens: index, completion_tokens: 10, total_tokens: index + 10,
protocol: 'chat-completions', raw: { prompt_tokens: index, completion_tokens: 10, total_tokens: index + 10, prompt_cache_hit_tokens: 0, custom_old: ['原字段', index] } } : null }));
}
export function inspectExport(bytes) {
const lines = Buffer.isBuffer(bytes) ? bytes.toString('utf8').split('\n') : bytes.split('\n'); assert.equal(lines.pop(), '');
const values = lines.map(line => JSON.parse(line)), header = values.shift(), footer = values.pop();
assert.equal(header.format, 'orven-model-attempts-ndjson'); assert.equal(header.type, 'header'); assert.equal(footer.type, 'footer'); assert.equal(footer.complete, true);
assert.equal(header.expectedRecords, values.length); assert.equal(footer.records, values.length);
assert.equal(footer.recordLinesSha256, hash(lines.slice(1, -1).map(line => line + '\n').join('')));
for (const value of values) {
assert.equal(value.type, 'attempt'); assert.equal(hash(JSON.stringify(value.item)), value.reference.payloadSha256);
assert.equal(hash(JSON.stringify(value.initial.item)), value.reference.initialSha256); assert.equal(value.initial.sha256, value.reference.initialSha256);
}
return { header, footer, records: values };
}
+192
View File
@@ -0,0 +1,192 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { EventEmitter } from 'node:events';
import { fixture, until, workspace } from './helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { Store } from '../src/server/store.mjs';
import { createRequestHandler } from '../src/server/app.mjs';
import { ModelRequestLedger, ledgerQuery, streamLedgerExport } from '../src/core/models/request-ledger.mjs';
import { usageSamples, usageModelId, cacheUsageFixture } from './fixtures/cache-usage-model.mjs';
import { historicalAttempts, inspectExport, hash } from './fixtures/request-ledger-data.mjs';
import { StateDatabase as LegacyStateDatabase } from './fixtures/legacy-request-ledger/state-database.mjs';
import { ModelHub } from '../src/core/models/model-hub.mjs';
import { installUpgrade } from '../src/server/hot-upgrade.mjs';
const originalMeta = store => store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get()?.value;
const provider = () => Object.assign(Object.create(Provider.prototype), { apiKey: '' });
const owned = (id, status = 'completed') => ({ id, connectionId: 'owned-alpha', model: 'owned-new', runId: id, status, usageStatus: 'unknown', usage: null, startedAt: '2026-11-07T00:00:00Z' });
class Response extends EventEmitter {
constructor(onWrite = () => {}) { super(); this.chunks = []; this.onWrite = onWrite; }
write(value, callback) { this.chunks.push(value); const writable = this.onWrite(value) !== false; if (writable) queueMicrotask(() => callback?.()); return writable; }
end() { this.writableEnded = true; }
}
test('legacy >1000 entries migrate exactly in both permission modes; metadata is unchanged and lazy normal reads do not load all receipts', t => {
for (const modernDefaults of [true, false]) {
const f = fixture(t, { modernDefaults }), rows = historicalAttempts(); f.store.storage.setMeta('modelAttempts', rows); const original = originalMeta(f.store);
const hub = provider().modelHub(f.store); assert.equal(hub.compatAttempts, undefined);
assert.equal(hub.view().attemptCount, rows.length); assert.equal(hub.view().attempts.length, 100); assert.equal(hub.view().storage.attemptsRetained, null);
assert.equal(hub.compatAttempts, undefined); assert.equal(originalMeta(f.store), original); assert.deepEqual(f.store.storage.meta('modelAttempts'), rows);
assert.equal(hub.ledger.state.legacyMetadataSha256, hash(original));
const result = hub.ledger.page({ limit: 2000 }); assert.deepEqual(result.items, [...rows].reverse()); assert.equal(result.hasMore, false);
assert.equal(result.references.at(-1).legacyIndex, 0); assert.equal(hub.ledger.record(1).initial.sha256, hash(JSON.stringify(rows[0])));
}
});
test('ordinary progress writes only one current receipt, keeps older payload SHA unchanged and rolls back injected commit failures', t => {
const f = fixture(t, { modernDefaults: true }), rows = historicalAttempts(); f.store.storage.setMeta('modelAttempts', rows);
const hub = provider().modelHub(f.store), original = originalMeta(f.store), first = hub.ledger.record(1);
f.store.storage.database.exec('CREATE TEMP TABLE owned_ledger_writes(seq INTEGER,bytes INTEGER); CREATE TEMP TRIGGER owned_ledger_update AFTER UPDATE ON model_attempts BEGIN INSERT INTO owned_ledger_writes VALUES(new.seq,length(new.payload)); END;');
const current = owned('owned-current', 'running'); hub.addAttempt(current); current.status = 'completed'; current.reason = '只改当前记录'; hub.saveAttempts(current);
assert.equal(hub.compatAttempts, undefined); assert.equal(originalMeta(f.store), original); assert.deepEqual(hub.ledger.record(1), first);
const writes = f.store.storage.database.prepare('SELECT * FROM owned_ledger_writes').all(); assert.equal(writes.length, 1); assert.equal(writes[0].seq, 1108);
const final = hub.ledger.record(1108); current.reason = '未提交修改'; f.store.storage.faultInjector = phase => { if (phase === 'before_commit') throw new Error('owned ledger commit failure'); };
assert.throws(() => hub.saveAttempts(current), /owned ledger commit failure/); assert.deepEqual(hub.ledger.record(1108), final);
f.store.storage.faultInjector = null; hub.saveAttempts(current); assert.equal(hub.ledger.record(1108).item.reason, '未提交修改'); assert.equal(hub.ledger.record(1108).initial.item.status, 'running');
assert.equal(f.store.storage.database.prepare('SELECT COUNT(*) AS n FROM owned_ledger_writes').get().n, 2);
});
test('migration failure is atomic, malformed old metadata stays original, duplicate legacy IDs keep separate origins and recovery never replays', t => {
const f = fixture(t, { modernDefaults: true }), rows = [owned('owned-duplicate'), owned('owned-duplicate', 'running')]; f.store.storage.setMeta('modelAttempts', rows); const original = originalMeta(f.store);
f.store.storage.faultInjector = phase => { if (phase === 'before_commit') throw new Error('owned migration failure'); };
assert.throws(() => new ModelRequestLedger(f.store.storage), /owned migration failure/); assert.equal(originalMeta(f.store), original); assert.equal(f.store.storage.meta('modelAttemptLedger'), null);
f.store.storage.faultInjector = null; const hub = provider().modelHub(f.store); assert.equal(hub.view().attemptCount, 2);
assert.equal(hub.ledger.record(2).item.status, 'unknown'); assert.deepEqual(hub.ledger.record(2).initial.item, rows[1]); assert.equal(originalMeta(f.store), original);
assert.throws(() => hub.ledger.find('owned-duplicate'), /不唯一/); assert.equal(new ModelRequestLedger(f.store.storage).page().total, 2);
const broken = fixture(t, { modernDefaults: true }); broken.store.storage.setMeta('modelAttempts', [null]); const raw = originalMeta(broken.store);
assert.throws(() => provider().modelHub(broken.store), /完整迁移/); assert.equal(originalMeta(broken.store), raw); assert.equal(broken.store.storage.meta('modelAttemptLedger'), null);
});
test('keyset pages include every old entry once despite new arrivals and cursor scope, numeric boundaries and literal searches are validated', t => {
const f = fixture(t, { modernDefaults: true }), rows = historicalAttempts(); f.store.storage.setMeta('modelAttempts', rows); const ledger = new ModelRequestLedger(f.store.storage);
let page = ledger.page({ limit: 65 }), collected = [...page.items]; ledger.save(owned('owned-late-arrival'));
while (page.hasMore) { page = ledger.page({ cursor: page.nextCursor, limit: 65 }); collected.push(...page.items); }
assert.deepEqual(collected, [...rows].reverse()); assert.equal(page.total, rows.length); assert.equal(page.retainedTotal, rows.length + 1); assert.equal(ledger.page().items[0].id, 'owned-late-arrival');
const filtered = ledger.page({ filters: { connectionId: 'owned-beta', status: 'failed' }, limit: 1 });
assert.throws(() => ledger.page({ cursor: filtered.nextCursor, filters: { connectionId: 'owned-alpha', status: 'failed' } }), /当前筛选/);
const other = new ModelRequestLedger(fixture(t, { modernDefaults: true }).store.storage); assert.throws(() => other.page({ cursor: filtered.nextCursor, filters: { connectionId: 'owned-beta', status: 'failed' } }), /当前筛选/);
for (const limit of [0, -1, '1.5', 'Infinity', Number.MAX_SAFE_INTEGER + 1]) assert.throws(() => ledger.page({ limit }), /正整数/);
assert.equal(ledger.page({ limit: Number.MAX_SAFE_INTEGER }).items.length, 1108);
ledger.save({ ...owned('owned-literal'), reason: '仅这条记录有 100%_literal' }); assert.equal(ledger.page({ filters: { query: '100%_literal' } }).total, 1);
assert.equal(ledger.page({ filters: { query: "' OR 1=1 --" } }).total, 0);
assert.throws(() => ledgerQuery(new URL('http://localhost/?limit=1&limit=2')), /参数/); assert.throws(() => ledgerQuery(new URL('http://localhost/?cursor=bad'), { exportOnly: true }), /参数/);
});
test('record source checks reject reassignment and corrupted payload while initial and historical receipts remain intact', t => {
const f = fixture(t, { modernDefaults: true }), ledger = new ModelRequestLedger(f.store.storage), value = owned('owned-provenance'); ledger.save(value);
for (const key of ['id', 'connectionId', 'poolId', 'sessionId', 'taskId', 'runId', 'projectId', 'requestId', 'model', 'protocol']) {
const changed = { ...value, [key]: 'owned-wrong' };
if (key === 'id') continue; assert.throws(() => ledger.save(changed), /不能移动/);
}
const before = ledger.record(1); f.store.storage.database.prepare('UPDATE model_attempts SET payload=? WHERE seq=1').run(JSON.stringify({ ...value, reason: 'external corrupt payload' }));
assert.throws(() => ledger.record(1), /SHA256/); assert.throws(() => ledger.page(), /SHA256/);
assert.throws(() => f.store.storage.meta('modelAttempts'), /SHA256/);
f.store.storage.database.prepare('UPDATE model_attempts SET payload=? WHERE seq=1').run(JSON.stringify(value)); assert.deepEqual(ledger.record(1), before);
});
test('versioned migration prevents a previous storage program from silently opening a partial ledger; only untouched initialization can roll back', t => {
const f = fixture(t, { modernDefaults: true }), rows = historicalAttempts(7); f.store.storage.setMeta('modelAttempts', rows); const original = originalMeta(f.store);
assert.equal(f.store.storage.database.prepare('PRAGMA user_version').get().user_version, 1);
assert.equal(f.store.storageInfo().schemaVersion, 1);
const ledger = new ModelRequestLedger(f.store.storage); assert.equal(f.store.storage.database.prepare('PRAGMA user_version').get().user_version, 2);
assert.equal(f.store.storageInfo().schemaVersion, 2);
assert.throws(() => new LegacyStateDatabase(f.data), /更新版本/); assert.equal(ledger.page().total, rows.length);
assert.equal(ledger.rollbackInitialization(), true); assert.equal(originalMeta(f.store), original);
assert.equal(f.store.storageInfo().schemaVersion, 1);
const prior = new LegacyStateDatabase(f.data); f.onCleanup(() => prior.close()); assert.deepEqual(prior.meta('modelAttempts'), rows);
const active = new ModelRequestLedger(f.store.storage); active.save(owned('owned-after-migration'));
assert.throws(() => active.rollbackInitialization(), /已有新记录/); assert.equal(active.page().total, 8); assert.equal(originalMeta(f.store), original);
});
test('a stale cached receipt cannot overwrite another writer; unchanged progress is a read-only no-op and the full compatibility view stays current', t => {
const f = fixture(t, { modernDefaults: true }), hub = provider().modelHub(f.store), current = owned('owned-cache-current', 'running'); hub.addAttempt(current);
assert.equal(hub.attempts[0].status, 'running'); current.status = 'completed'; hub.saveAttempts(current); assert.equal(hub.attempts[0].status, 'completed');
f.store.storage.faultInjector = phase => { if (phase === 'before_commit') throw new Error('unchanged receipts must not commit'); };
assert.doesNotThrow(() => hub.saveAttempts(current)); f.store.storage.faultInjector = null;
hub.ledger.save({ ...current, reason: 'owned concurrent progress' }); current.reason = 'stale overwritten progress';
assert.throws(() => hub.saveAttempts(current), /已更新/); assert.equal(hub.ledger.record(1).item.reason, 'owned concurrent progress');
});
async function retainedLegacy(t) {
const f = fixture(t, { modernDefaults: true }); f.store.storage.close(); f.store.storage = new LegacyStateDatabase(f.data);
const rows = historicalAttempts(107); f.store.storage.setMeta('modelAttempts', rows); const actual = new Provider(), runtime = new Runtime(f.store, actual);
actual.credentials = new Map();
const hub = Object.assign(Object.create(ModelHub.prototype), { store: f.store, provider: actual,
state: { schema: 1, revision: 0, selected: { type: 'legacy', id: 'legacy-default' }, connections: [], pools: [], imports: {} },
health: new Map(), leases: new Map(), cursors: new Map(), sticky: new Map(), waiting: 0 });
Object.defineProperty(hub, 'attempts', { value: structuredClone(rows), writable: true, configurable: true, enumerable: true }); actual.hub = hub;
const originalHandler = (_request, response) => response.end('owned previous handler'), server = http.createServer(originalHandler);
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); f.onCleanup(() => runtime.stopAll());
f.onCleanup(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); }));
return { ...f, hub, rows, server, actual, originalHandler, context: { store: f.store, server, provider: actual, runtime, token: 'owned-legacy-ledger-token', clients: new Set(), started: Date.now() } };
}
test('retained legacy hub shape adopts the new ledger on the same previous source storage connection, keeping saved bytes and credential objects', async t => {
const f = await retainedLegacy(t), storage = f.store.storage, database = storage.database, original = originalMeta(f.store), credentials = f.actual.credentials;
installUpgrade(f.context, { appDirectory: workspace, updateServiceInfo: false });
assert.equal(f.store.storage, storage); assert.equal(storage.database, database); assert.equal(f.actual.hub, f.hub); assert.equal(f.actual.credentials, credentials);
assert.equal(Object.hasOwn(f.hub, 'attempts'), false); assert.equal(f.hub.view().attemptCount, 107); assert.equal(originalMeta(f.store), original);
assert.equal(database.prepare('PRAGMA user_version').get().user_version, 2); assert.deepEqual(storage.meta('modelAttempts'), f.rows);
});
test('failed retained handler adoption restores the original storage prototype, ledger shape, handler, schema and exact original metadata', async t => {
const f = await retainedLegacy(t), storage = f.store.storage, prototype = Object.getPrototypeOf(storage), attempts = f.hub.attempts, original = originalMeta(f.store);
const on = f.server.on; let failed = false; t.mock.method(f.server, 'on', function(event, handler) {
if (event === 'request' && !failed) { failed = true; throw new Error('owned failure after ledger adoption'); } return on.call(this, event, handler);
});
assert.throws(() => installUpgrade(f.context, { appDirectory: workspace, updateServiceInfo: false }), /owned failure after ledger adoption/);
assert.equal(Object.getPrototypeOf(storage), prototype); assert.equal(f.store.storage, storage); assert.equal(f.hub.attempts, attempts); assert.equal(f.hub.ledger, undefined);
assert.equal(f.server.listeners('request')[0], f.originalHandler); assert.equal(storage.database.prepare('PRAGMA user_version').get().user_version, 1);
assert.equal(originalMeta(f.store), original); assert.equal(storage.meta('modelAttemptLedger'), null);
assert.equal(storage.database.prepare("SELECT COUNT(*) AS n FROM sqlite_schema WHERE name='model_attempts'").get().n, 0);
});
test('full export holds a read snapshot while live rows change, keeps all raw fields and ends with complete count and byte checksum', async t => {
const f = fixture(t, { modernDefaults: true }), rows = historicalAttempts(); f.store.storage.setMeta('modelAttempts', rows); const ledger = new ModelRequestLedger(f.store.storage);
const snapshot = ledger.exportSnapshot(), response = new Response(line => { if (JSON.parse(line).type === 'header') { ledger.save({ ...rows[500], reason: 'export-time change' }); ledger.save(owned('owned-during-export')); } });
await streamLedgerExport(response, snapshot); const result = inspectExport(response.chunks.join(''));
assert.equal(result.records.length, 1107); assert.deepEqual(result.records.map(value => value.item), rows); assert.equal(ledger.page().retainedTotal, 1108);
const filtered = new Response(); await streamLedgerExport(filtered, ledger.exportSnapshot({ connectionId: 'owned-beta', status: 'failed' }));
assert.deepEqual(inspectExport(filtered.chunks.join('')).records.map(value => value.item), rows.filter(value => value.connectionId === 'owned-beta' && value.status === 'failed'));
});
test('cancelled export releases its snapshot and partial bytes never acquire a complete footer or cause requests', async t => {
const f = fixture(t, { modernDefaults: true }), ledger = new ModelRequestLedger(f.store.storage); ledger.save(owned('owned-partial-export'));
const response = new Response(() => false), snapshot = ledger.exportSnapshot(); let closed = false; const close = snapshot.close;
snapshot.close = () => { closed = true; close(); }; const exporting = streamLedgerExport(response, snapshot);
response.destroyed = true; response.emit('close'); await assert.rejects(exporting, /被中断/); assert.equal(closed, true); assert.doesNotMatch(response.chunks.join(''), /"complete":true/);
const complete = new Response(); await streamLedgerExport(complete, ledger.exportSnapshot()); assert.equal(inspectExport(complete.chunks.join('')).records.length, 1);
});
for (const [name, sample] of Object.entries(usageSamples)) test(`actual ${name} request uses incremental ledger, retains source-bound usage and original artifact, and restart never dispatches again`, async t => {
const f = fixture(t, { modernDefaults: true }), model = await cacheUsageFixture(t, { ...sample, streaming: true }), actual = new Provider(), hub = actual.modelHub(f.store);
const connection = hub.upsert({ name: 'Owned incremental ' + name, model: usageModelId, protocol: sample.protocol, baseUrl: model.baseUrl, streaming: true, requiresKey: false }); hub.select({ type: 'connection', id: connection.id });
const runtime = new Runtime(f.store, actual); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, '只说明已收到完整回复,不运行工具。'); await until(() => !runtime.isActive(f.session.id), 15000);
assert.equal(model.requests.length, 1); assert.equal(f.store.core.tool.size, 0); assert.equal(hub.compatAttempts, undefined);
const receipt = hub.ledger.record(1); assert.equal(receipt.item.status, 'completed'); assert.deepEqual(receipt.item.usage.raw, sample.raw);
assert.equal(receipt.item.usage.tokenAccounting.metrics.cacheWrite.tokens, name === 'chat' ? 300 : name === 'responses' ? 7000 : 248);
const artifact = f.store.owned('artifact', receipt.item.responseArtifactId, f.session.id); assert.equal(artifact.sha256, hash(model.responses[0]));
assert.equal(f.store.storage.meta('modelAttempts')[0].id, receipt.item.id); await runtime.stopAll(); f.store.close();
const restored = new Store(f.data); f.onCleanup(() => restored.close()); const fresh = provider().modelHub(restored); assert.deepEqual(fresh.ledger.record(1), receipt); assert.equal(model.requests.length, 1);
});
test('actual authenticated local HTTP pages and exports the entire ledger with source details, invalid query/origin and no model execution', async t => {
const f = fixture(t, { modernDefaults: true }), rows = historicalAttempts(), actual = new Provider(); f.store.storage.setMeta('modelAttempts', rows);
const runtime = new Runtime(f.store, actual), token = 'owned-ledger-token', server = http.createServer(); f.onCleanup(() => runtime.stopAll());
server.on('request', createRequestHandler({ appDirectory: workspace, server, store: f.store, provider: actual, runtime, token, clients: new Set(), started: Date.now(), getPort: () => server.address().port }));
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); f.onCleanup(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); }));
const base = 'http://127.0.0.1:' + server.address().port, fetchOwned = route => fetch(base + '/api/model-center' + route, { signal: AbortSignal.timeout(8000), headers: { 'X-Workbench-Token': token, Connection: 'close' } });
console.log('[request-ledger-http] reading first page');
const page = await (await fetchOwned('/attempts?limit=65')).json(); assert.equal(page.items.length, 65); assert.equal(page.total, 1107);
console.log('[request-ledger-http] reading first source record');
const record = await (await fetchOwned('/attempts/1')).json(); assert.deepEqual(record.item, rows[0]); assert.equal(record.reference.payloadSha256, hash(JSON.stringify(rows[0])));
console.log('[request-ledger-http] starting complete export');
const response = await fetchOwned('/attempts/export'); assert.equal(response.status, 200); assert.match(response.headers.get('content-type'), /ndjson/);
assert.deepEqual(inspectExport(Buffer.from(await response.arrayBuffer())).records.map(value => value.item), rows);
console.log('[request-ledger-http] complete export received, checking invalid requests');
assert.equal((await fetchOwned('/attempts?limit=0')).status, 400); assert.equal((await fetchOwned('/attempts/999999')).status, 404);
const blocked = await fetch(base + '/api/model-center/attempts', { signal: AbortSignal.timeout(8000), headers: { Origin: 'https://owned-untrusted.example', 'X-Workbench-Token': token, Connection: 'close' } }); assert.equal(blocked.status, 403);
assert.equal(actual.activeRequests ?? 0, 0); assert.equal(runtime.active.size, 0); assert.equal(originalMeta(f.store), JSON.stringify(rows));
});