修复 CAD AI 响应协议兼容和有限恢复

完善 Responses 与 Chat Completions 的响应校验、错误分类和安全诊断,保留知识库及现有模型配置。补充回归测试、行为对照和部署说明,记录全量构建结果及尚未查清的 SSE 偶发测试失败。
This commit is contained in:
2026-11-13 18:18:40 +08:00
parent aeecacef6d
commit 6b96ca1eb0
10 changed files with 1143 additions and 105 deletions
+107
View File
@@ -0,0 +1,107 @@
# CAD AI 上下文增长审计与优化建议(2026-11-13)
## 结论与证据边界
网页输入随任务增长,直接机制是保留的消息、工具参数、工具结果和参考资料在每次无状态模型请求中重新携带。顶层工具定义是固定开销,不会每一步都作为新历史再次追加。
当前证据不支持“网页工具定义比原版大一倍”:离线测得网页开启知识库后 13 个工具共 11,877 字节,原版普通 API 路径发送的 20 个工具共 31,779 字节。高风险来源是工具返回的大目录、Schema、设计状态以及它们的持续保留。
尚未取得用户桌面和网页同任务、同步骤的完整分项统计,不能把约两倍差距精确分摊给某一项。现有日志只有每次请求总 input/output/total,没有工具结果大小排行、缓存命中或推理状态占用。下面大小均为 UTF-8 字节,不冒充模型 token 数;加密推理、图片及各厂商协议开销不能按普通文本字节直接换算。
## 离线测量
测量没有调用模型、没有读取设计正文、没有修改现有设计或重启服务。Java 只离线构造模型请求;原版使用已有 CLI 的独立 headless stdio 会话,只查询 tools/list 和只读工具,结束后进程退出,不开放常驻端口。
| 项目 | 原版普通 API 路径 | 网页 OpenAI Responses 路径 |
| --- | ---: | ---: |
| 发送给模型的工具数量 | 20 | 知识库关闭 12 / 开启 13 |
| 全部工具定义 JSON | 31,779 字节 | 关闭 9,191 / 开启 11,877 字节 |
| 系统提示,无桌面自定义指令 | 10,596 字节 | 关闭 11,397 / 开启 11,702 字节 |
原版 MCP tools/list 返回 21 个工具,api_wire::openai_tools 会隐藏 crash_reports,所以模型侧为 20。网页知识库新增工具定义和系统提示合计约 3 KB,没有在每次启动时预加载 17 份正文。
同一原版只读命令目录,独立测量如下:
| 请求 | 文本结果 | 去掉 JSON 空白后 |
| --- | ---: | ---: |
| list_commands {},600 条命令 | 358,489 字节 | 322,482 字节 |
| list_commands {compact:true},600 条命令 | 43,090 字节 | 32,289 字节 |
| list_commands {filter:"extrude",compact:true},2 条命令 | 130 字节 | 93 字节 |
| describe_command {id:"solid.extrude"} | 27,844 字节 | 17,265 字节 |
这说明“工具定义列表”和“list_commands 工具返回的 CAD 命令目录”必须区分。后者一次就可能远大于所有顶层工具定义。本测量证明来源大小,不证明用户该轮一定执行了无筛选目录查询。
现有后端日志中的知识读取记录为 involute-spur-gear 和 gear-pair,对应打包正文分别 4,430、2,503 字节,合计 6,933 字节。正文外还存在 JSON 包装,但不能据此把十余万输入 token 全部归因于知识库。
测量文件位于 `target/cad-ai-context-audit-20261113/`:`native-tools.json`、`web-fixed-overhead.json`、`read-only-query-sizes.json`、`knowledge-read-sizes.json`。辅助 Java 程序也位于此被忽略目录,不是业务实现改动。
## 已确认的原版与网页差异
### 结果保留
`solidcraft-main/crates/ui-egui/src/agent_chat/api_client.rs::tool_text` 将每次工具文本统一截断到 20,000 字节,包括 JSON;其中 image 类型只转为文字占位。
网页 `agent_tools::bound_plain_tool_text` 只截断普通单块纯文本,明确排除 JSON、混合结果、Skill 和知识。`prepare_tool_result` 会压缩 JSON 空白、为大命令目录保留完整条目的分页;单次工具结果还受 32 KiB 交付预算控制。因此网页并非一次直接把 358 KB 全发给模型,但连续读取多页后仍可能在历史中保留大量内容。原版较小的一部分可能来自更激进的截断和图片占位,不能把直接砍坏 JSON 当作正确优化。
`compact_old_reference` 已有旧命令目录和 Schema 淘汰,但目前只在请求超过字节预算后触发。新轮次 240 条历史裁剪不会在同一长任务中持续压缩。512 KiB 文本预算也不是模型 token 预算。
### 固定前缀被改写
`ArkCadAiClient.body` 在历史前方插入当前文档上下文,其中包括变化的 documentRevision。
`agent.rs::platform_model_request_wire` 每次在最早一条用户消息的 wire 副本追加当前剩余预算、历史占用等 runtime note。该 note 在请求之间替换而非无限追加,因此不是同一 note 反复堆积的 bug;但它会改写历史前部,不利于精确前缀缓存和稳定重放。
缓存改进主要减少重复计算和费用,不会使 input_tokens 总量自动变小,也不能替代上下文缩减。当前 Java 只保留 input/output/total 三项 usage,无法判断第三方上游是否返回过缓存细项。供应商是否支持缓存、怎样计费,应按实际上游验证。
### 推理状态与图片
网页 Responses 请求 store=false,并请求/重放 reasoning.encrypted_content。它与原版普通 Chat 路径的推理续接形态不同,需要单独记录字节与上游用量,不把密文当作普通文本 tokenizer 输入,不为省 token 任意丢弃协议所需状态。
网页可把真实工具截图交给模型,而上述原版普通 API worker 对 image 工具结果使用占位文字。若任务涉及截图,这是另一个必须分开比较的变量;本次没有该会话逐请求图片占用统计。
## 建议的优化顺序
1. **先可观测。** 每次请求只记录系统提示、工具定义、工具参数、工具结果、Skill、知识、其他历史、密文的字节数和图片数量,按工具名统计大结果。结合厂商支持的 tokenizer 做文本估算,用上游总 usage 校准;记录可用的缓存用量。不得记录参数值、设计正文、密钥或推理明文。用相同模型和任务比较总步骤、总输入、缓存输入和未缓存输入,而非只比较最后一次 token。
2. **在查询源头减量。** 目录使用现有 filter/prefix/fields/compact/limit;描述只选要调用的命令,避免为证明任务可做而翻完全部目录。execute/batch 使用现有 verbose:false,保留 created/changed/removed、失败、必要测量,避免重复完整实体列表;inspect_design 默认查询当前需要的部分。先优化查询与结果形态,再考虑更大的框架改造。
3. **原始结果与模型有效上下文分开。** 原始完整结果保留在界面/文档会话缓存中;模型先获得可验证的简短结果及可重读句柄,必要时按字段或页读取。句柄必须绑定账号、项目、文档与修订,保留调用配对和操作状态,不能把旧结果当作当前几何真相。知识库正文和路由保留,按文档需要读取;不能只剩引用却已无正文可读。
4. **提前淘汰可重读参考。** 为模型配置可用输入预算与输出/推理预留,按 token 估算触发,而不是等到 512 KiB。优先移除已用过的命令目录、Schema、旧只读快照,保持用户约束、未完成目标、参数与单位、关键实体编码、最近错误及完整调用配对。先做确定性压缩,不需要立即引入语义摘要。
5. **恢复稳定历史与缓存布局。** 静态说明保持稳定;不要改写最早用户消息。文档修订等鉴权绑定数据继续在 Java 校验,模型不必看到与建模无关的完整散列;模型需要的变化以短的追加消息表达,并控制重复说明。不能打断工具调用/结果配对,必须验证各协议的推理续接。
## MCP 方案取舍
MCP 的 tools/list 分页、资源链接和资源读取可以承载按需发现、完整结果外置及分页重读;它们不意味着客户端会自动减少模型上下文。宿主仍须决定什么进入模型、什么留在结果存储里。
成熟思路是渐进披露/工具检索、结果过滤和外置、分阶段上下文压缩、稳定前缀缓存。当前项目已有 list_commands + describe_command + execute/batch,工具发现基础足够,优先控制结果历史;不建议先为 13 个工具搭一套复杂检索平台,也不需要为了这个问题更换 Deep Agents/LangGraph。
原生供应商的 Tool Search、Programmatic Tool Calling、Compaction 可以作为可选适配能力,不能假定当前第三方 Responses 地址、豆包及 DeepSeek 都兼容。同样,代码执行式 MCP 需要执行隔离和权限设计,当前已有 batch 应先利用。本次只是审计与建议,没有更改模型请求、上下文策略、知识库或运行服务。
参考:OpenAI 官方 Prompt caching、Reasoning、Compaction 指南;MCP 2025-11-25 Tools 规范;Anthropic 官方 Advanced tool use 与 Code execution with MCP 文章。相关网页仅用于验证通用方案,以上项目大小来自本地离线测量。
## 补充核对:工具差异与目录字段
原版模型侧 20 个工具与网页 13 个工具的交集为 12 个。原版独有 8 个,网页增加 knowledge_lookup,因此为 20 - 8 + 1 = 13。不能把数量少直接解释为没有能力差异。
| 原版独有工具 | 当前网页状态 |
| --- | --- |
| open / save / new_design / export | 桌面文件或文档生命周期工具;当前网页 AI 按既有边界未开放,保存保留手动流程。不能绕过限制通过 execute 执行文件/文档命令 |
| running / pending | 桌面桥接请求的运行状态及等待工具;网页使用已有异步工具等待、取消与代次隔离,不提供同名桌面进程工具 |
| compare_picture | 使用本地参考图片路径进行比对;网页未接入同名能力 |
| redo | 确实没有在 Java 工具 Schema 中暴露,尽管浏览器 PLATFORM_TOOLS 白名单中存在。属于具体能力缺项,不能解释为网页一定用不到;补齐需验证撤销边界与文档保护 |
list_commands、describe_command、execute/batch 等 12 个共同入口保留。工具是入口,solid.extrude、solid.fillet 等是入口后面的引擎命令,不能用顶层工具数替代命令能力数。目录测得 600 个是原版引擎目录数量,不表示网页 AI 有权执行其中所有文件、系统和跨文档命令;原有授权 gate 仍生效。
对同一 headless 目录做了额外覆盖核对:完整目录、compact 目录、fields=[id,label,enabled] 目录的命令 ID 集合完全相同,均为 600 条,未丢失任何命令编码。
| JSON 已去除空白的结果 | 大小 |
| --- | ---: |
| 完整目录 | 322,482 字节 |
| id + label | 32,289 字节,减少 89.99% |
| id + label + enabled | 41,416 字节,仍保留可用状态 |
按字段汇总键名和值、未计容器分隔符,完整目录中 params 约 223,366 字节,是最大一项;其次为 disabled_reason 约 20,707 字节。icon 和 shortcut 等界面信息也占空间。参数详情可以通过现有 describe_command 按命令读取,不必在总目录预先重复携带。
建议空参数查询默认返回精简目录,必要时按完整条目分页;保留当前筛选、显式 fields 和精确 Schema 读取。筛选没有命中时允许扩大查询,不根据关键词永久隐藏任何建模能力;部分页必须提供 total/next_offset,不能把第一页当全集,也不需要为了使用已找到的某个命令总是遍历所有后续页。
进一步复用旧目录时,静态名称与参数定义按引擎版本缓存;enabled/disabled_reason 等动态状态必须重新校验,不能使用旧文档修订的可用性结果。模型有效上下文可淘汰旧目录正文,界面记录仍保留,按需重查。以上为优化设计,本次尚未修改默认返回行为或补齐 redo。
新增测量证据:`target/cad-ai-context-audit-20261113/tool-differences.json`、`catalog-coverage.json`。
@@ -0,0 +1,63 @@
# CAD AI `list_commands` 目录优化(2026-11-13)
## 范围与行为
优化位于 `solidcraft-main` 的网页平台助手适配层,不更换 Java 模型协议、接口或工具,也不改变原版 MCP、CLI 和直连模型助手的默认行为。
平台助手默认调用 `list_commands {}` 时,通过现有 `fields` 参数读取命令索引,保留 `id`、`label`、`tab`、`panel`、`enabled`、`disabled_reason`、`planned` 中原条目具有的字段。只把参数长说明、图标和快捷键移出默认目录;建模前继续用原有 `describe_command` 获取完整参数说明和 Schema。
所有命令、原顺序、筛选条件、可用状态及不可用原因都保留,不按任务猜测并隐藏命令。模型已经找到目标命令时可直接描述该命令;只有声明穷举完成或某命令不存在时,才必须读完相关结果页。超限仍按完整条目分页,`next_arguments` 保留本页的有效字段和查询条件,不截断结构化 JSON。
显式 `fields` 或 `compact` 始终优先,包括 `compact:false` 单次请求完整目录。`batch` 中直接的默认 `list_commands` 步骤同样使用索引,不改变其他步骤。大目录应单独查询,`batch` 的结果不新增分页协议。
原始工具调用仍进入现有历史;实际执行的查询和分页使用确定的有效参数。工具执行仍经过原有 Schema、权限、文档代次及修订检查,模型请求重试不会重放已完成工具。
## 测量口径
使用真实 headless MCP 命令目录,固定同一状态,共 600 条。以下是 UTF-8 字节,不是模型精确 token 数;两组 JSON 都采用相同的无空白序列化口径。
| 指标 | 完整目录 | 默认索引 |
| --- | ---: | ---: |
| 命令数 | 600 | 600 |
| JSON 字节 | 322,482 | 77,854 |
| 相对缩减 | — | 75.86% |
32,768 字节单次工具结果预算下,索引通过 3 页交付,实际文本合计 84,465 字节(含分页信息及末页原有排版)。默认索引和完整目录逐项核对命令顺序及所有保留字段。筛选后的零匹配、越界 offset 和参数详情另有回归。
该优化减少目录重复携带的内容,不保证整项任务输入 token 固定下降 75.86%。模型仍可能按需读取多个详细 Schema;已有对话中的旧目录不追溯改写。建议保存设计并刷新引擎后开始新对话验证。
## 恢复旧行为
- 单次:模型调用 `list_commands {"compact": false, ...原筛选条件}`。
- 后续默认查询:已有控制接口 `ui.prefs {"agent_compact_catalog": false}`。该偏好默认开启,按账号的现有偏好机制存储;不修改已保留历史。
- 发布回退:恢复本次备份的旧引擎 manifest 和 worker,再仅重启 8091 前端。8993 后端不需要更换,尤其不能回退已修复的失败分类及 TLS 处理包。
当前平台隐藏助手偏好页的行为保持不变;恢复偏好可通过已有控制接口设置,或直接使用显式完整查询。
## 代码位置
- `apps/solidcraft-web/src/agent_tools.rs`:有效目录参数和只读 batch 步骤适配;复用现有完整条目分页。
- `apps/solidcraft-web/src/agent.rs`:仅平台循环启用、有效参数贯穿执行和结果分页、运行时目录约定。
- `crates/ui-egui/src/agent_chat/`、`crates/ui-egui/src/prefs.rs`:偏好同步及恢复;其他后端默认空实现。
- `apps/solidcraft-web/src/main.rs`、`crates/ui-egui/src/agent_chat/tests.rs`:既有测试文件内补充覆盖。
- `assets/locales/pending/assistant-compact-catalog.json`:偏好标签及说明。
## 验证与构建记录
验证产物保存在 `target/cad-ai-list-commands-20261113/`,包含本轮源码基线、旧 manifest、测试日志、测量 JSON、隔离浏览器脚本、构建目录及完整发布包。该目录不包含真实模型密钥。
- `cargo test -p solidcraft-web -- --nocapture`:67 项通过,包括原有恢复、历史、知识去重和结果交付测试。
- `node scripts/sync-cad-ai-skills.mjs --check ../community`:17 份 Skills 一致。
- 本轮修改文件的 `rustfmt --check` 及 `git diff --check`:通过。
- `cargo test -p solidcraft-ui-egui agent_chat`:313 项相关主测试通过(子进程测试也正常),没有失败。
- `cargo clippy -p solidcraft-web --bin solidcraft-web -- -D warnings`:通过。
- `scripts/build-vibemake-cad.mjs`:release WASM 构建及资源校验通过,新引擎 `5c72ab510046c2fb52acb109`,共 9 个发布资源。
- 主站 `npm run build:cad`:独立 CAD 发布包构建及 ZIP 校验通过,产物 `target/cad-ai-list-commands-20261113/package/cad.zip`,引擎构建号一致。
- 隔离浏览器:使用 8091 的真实新 WASM,全部业务 API 与模型响应在内存模拟,不写真实项目,不增开 TCP 服务端口。默认目录 600 条,经 3 页与同一设计状态下的完整目录逐条比较;筛选目录、关闭偏好恢复全文、开启偏好时显式 `compact:false` 均通过;每组均能读取完整 `describe_command`,确认最终回答并保持调用/结果配对。4 组用例、页面脚本错误 0,详见 `browser-results.json` 和截图 `browser-catalog.png`。
- 仅重启 8091 前端加载新引擎,更新前确认没有进行中的网络连接;旧 `_assets`、manifest 和 worker 已保留。8091 当前 PID 为 64554;8993 仍为 PID 46643,未更换后端包。8092、8994 没有监听。
浏览器测试使用显式轮询等待异步页面状态,避免当前 Playwright 将异步谓词返回的 Promise 当成条件已经成立。大型 WASM 走正常 HTTP 静态资源请求,模拟层只接管业务 API,不在路由响应中复制整个 WASM。
本地回退先将本次产物目录的 `previous-engine.json`、`previous-sw.js` 分别恢复到 `target/cad-ai-native-parity-20261113/local-8091/cad/engine.json`、`sw.js`,再执行 `python3 target/cad-ai-native-parity-20261113/local-8091/manage.py site`。回退前同样确认没有进行中的模型请求;不使用后端 restore,也不调用 site restore(该选项恢复的是更早的初始前端环境)。
本轮使用模拟模型响应,不调用真实模型;任务成功率的真实模型对照不在本轮验证结论中。
+144
View File
@@ -0,0 +1,144 @@
# CAD AI 原版行为迁移实施记录(2026-11-13)
## 范围与固定基线
本轮在当前未提交工作区上局部修改,没有重置既有改动。Java 仍执行单次模型推理,浏览器仍负责 CAD 工具循环。没有引入 Deep Agents、LangGraph、Python/Rust 服务、新数据库、联网搜索、语义摘要或任务持久化。没有修改 SQL、CAD 内核、社区 AI 实现、云端保存流程、鉴权规则或业务接口路由。
| 仓库 | 开始时 HEAD | 说明 |
| --- | --- | --- |
| community | `aeecacef6d24183601dbefb6bc9449e6e888a1f9` | 原有知识交接及报告目录改动保留 |
| solidcraft-main | `2cdf535fd1c6d74a85adf51ddbee9d6303a75f0f` | 原有助手、知识库、恢复、MCP、Skills 等未提交改动保留 |
| vibemake | `27eb30e42805d7b1f14f517ae3be20f9d5f75ed8` | 本轮仅修改两个既有 CAD 浏览器测试文件,业务 JS 未修改 |
基准是本地当前源码,包含其当时尚未提交的实现,并非只按 HEAD 推断。初始采集目录为 `/private/tmp/cad-ai-native-parity-ayjhp740/`,长期副本位于 `target/cad-ai-native-parity-20261113/baseline/`。其中 `baseline.json` 包含关键文件及知识库 SHA-256,`*-before.diff` 保存开始时的工作区差异,`implementation-only.diff` 单独列出本轮改动。无关已有 tracked diff 已逐块核对,保持不变。
| 原版文件 | 基线 SHA-256 |
| --- | --- |
| `crates/ui-egui/src/agent_chat/api_client.rs` | `2404fcedd706cd31dd384db5f2014ecd6052053038e05487e9c6710df68429e2` |
| `crates/ui-egui/src/agent_chat/api_wire.rs` | `9521a4144fb8f674544100faedc1d6a4a47f9e3da36546b2f9c6dbf47cf65877` |
这两个原版文件在本轮保持基线内容未变,既有的未提交修改也被保留。
## 行为对照与代码落点
| 原版行为 | 网页原有行为/风险 | 本轮落地 | 主要回归 |
| --- | --- | --- | --- |
| 新用户轮次清理旧历史 | 只有请求预算压缩,完整旧轮次可能持续累计 | `agent_tools::trim_history_at_turn_start` 在加入用户消息后,以 240 或更低后端有效上限删除完整旧轮次;当前轮次保留,界面记录保留 | `native_history_trimming_preserves_complete_turns_and_current_requirements` |
| 保留最近两张图片 | 已有按截图预算清理旧参考的保守策略 | 新轮次用原版说明文字替换更早图片;继续服从厂商图片能力与后端更低上限 | `native_history_images_and_plain_text_bounds_preserve_knowledge_and_json` |
| 普通工具文本限制 20,000 字节 | 仅后端预算和结构化结果交付保护 | 单块纯文本按 UTF-8 边界截断并附 `…(cut)`;JSON、混合内容、知识和 Skill 继续走已有完整结果保护 | 同上及既有工具分页测试 |
| 顺序调用、完整配对 | 已有工具白名单、Schema 和 completed 校验 | 每完成一个工具立即保存已配对历史;后续取消/失败时丢弃未回答调用,保留成功 CAD 修改 | 历史裁剪测试、模型恢复和浏览器保护回归 |
| 空参数视为空对象再校验 | Responses 要求 arguments 字符串,空字符串可能被错误拒绝 | Java 接受缺失/空白参数及对象形式参数,再执行原有 Schema 校验;损坏 JSON、重复键和非对象仍拒绝 | `nativeEmptyArgumentsAreValidatedAsObjectsWithoutAcceptingCorruptJson` |
| 可选元信息不否定有效输出 | 缺少加密 reasoning 或部分 usage 字段会整步失败 | 没有可续接状态则忽略该 reasoning 元数据;缺失 usage 数字补 0,非法值仍拒绝;Chat 可缺省 choice.index,非零或越界仍拒绝 | `optionalReasoningAndUsageMetadataDoNotDiscardValidResponses` |
| Chat 特定参数兼容重发 | 未做原版 reasoning_effort 兼容 | 仅当前 Chat 路径、默认 effort、HTTP 400 明确提及 reasoning_effort 时,重发一次 none;显式配置和 Responses 不变 | `nativeReasoningCompatibilityRetryNeverChangesExplicitEffortOrResponsesProtocol` |
| 错误有可辨原因 | 多种情况都显示模型响应异常 | 内部枚举区分 JSON、SSE 类型、断流、连接、拒绝、续接状态、usage、HTTP;截断保持原有 OUTPUT_LIMIT | `providerFailureMessagesDistinguishHttpRefusalJsonAndStreamWithoutRawDetails` |
| 桌面流式文字沿原行为显示 | 网页已读 delta,但完成校验前没有正文 | 独立 `Event::TextPreview` 与 `AgentChat.preview`;attempt 开始/失败/结束清理预览;正式文本只来自校验成功的 output | UI preview 单元测试、真实连接的 browser preview 场景 |
| 取消和迟到结果隔离 | 已有代次、修订和宿主绑定;真实连接取消可能泄漏拒绝 Promise | 保留代次与绑定;每次流读取 await 后核对代次;等待并消费 reader.cancel 的拒绝,再释放锁 | 既有停止/账号/项目/文档修订回归 |
### 保留的网页扩展与差异
- 原有浏览器有限恢复保持:每次模型请求最多重试两次,间隔 1 秒、2 秒;整轮最多六次恢复。重试冻结同一份模型请求,不重跑已经完成的 CAD 操作。Java 不执行通用网络重试。
- Chat 的 `reasoning_effort=none` 兼容只在单次请求内生效,不像桌面工作器那样缓存为后续会话状态;每个新请求仍以服务端显式配置为准,总 deadline 不延长。
- 维持各厂商原配置:OpenAI/豆包使用 Responses,DeepSeek 使用 Chat Completions;没有自动协议或厂商回退。更换到不兼容推理协议仍要求新聊天。
- 本轮不模仿桌面钥匙串、ACP Agent 或本机 MCP 进程启动。
- 网页继续严格拒绝不完整终态、非法工具、重复调用编码和损坏参数。原版宽容的非关键字段不等于放行执行所必需的数据。
- 240 是新轮次历史条目目标,不是 token 保证。当前单轮如果本身超过请求、文本或响应资源限制,仍明确结束;已完成设计不回滚。
- 账户偏好 `agent_stream_preview=false` 保留仅显示完整回复的旧行为,控制通道为 `ui.prefs`。平台助手设置区也有对应标签和说明。桌面现有 `Event::Text` 未改。
## 知识库与接口兼容
阅读目录 `generation/reading-catalog.json` 和其 17 份 Markdown 正文均与基线 SHA-256 完全一致。资源仍通过 `vibemake-service/pom.xml` 原有 Maven resources 打包,未修改正文或目录规则。
保留 `knowledge_lookup(document_id)`、`cad-knowledge-v1`、`knowledgeMode`、读取接口、权限校验、未知文档 `not_found`、旧调用兼容、模型自主选文档,以及以实际有效历史为依据的去重。裁剪后正文不在模型上下文时可以重新读取。知识正文不经过本轮普通文本 20,000 字节裁剪。
通用 Skills 同步检查仍为 17 个,revision 为 `d563936cf58580fc0da2203d30708c4869a5a5956140221e717a53d5723b6efe`。
保留 `/api/cad/ai/capabilities`、`/api/cad/ai/chat`、`/api/cad/ai/knowledge`,版本仍为 `cad-agent-v1`、`cad-knowledge-v1`。SSE 事件、包装、请求字段、retryable 和安全 correction 格式不变。`text_delta` 只作界面预览;`completed.output` 仍是正式历史与工具执行授权来源。没有新增数据库主键输出、任务接口、检查点或事件回放。
错误日志包含请求编码、文档/轮次编码、厂商、固定阶段/类别、可用的 HTTP 状态及耗时。日志不记录 Authorization、密钥、完整设计、原始推理或未经处理的上游错误正文。解析调用位置和有界异常类型链仍可用于排查。
## 构建与测试命令
本机 Maven 默认 JDK 与系统 java 可能不同,重编译需显式使用 JDK 21。集成测试的 HTTP mock 需要允许本机监听。全量测试必须在隔离配置下关闭没有配置的外部服务默认开关;测试自身显式启用的 mock 仍按其测试属性运行:
```sh
JAVA_HOME=/opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home \
AI_ENABLED=false OSS_ENABLED=false GIT_ENABLED=false CAD_AI_ENABLED=false \
mvn -pl vibemake-api -am test
```
定向测试和 Java 打包:
```sh
JAVA_HOME=/opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home \
AI_ENABLED=false OSS_ENABLED=false GIT_ENABLED=false CAD_AI_ENABLED=false \
mvn -pl vibemake-api -am \
-Dtest=ArkCadAiClientTest,CadAiProtocolTest,CadAiKnowledgeTest,CadAiSampleKnowledgeTest,CadAiKnowledgeUtilityTest,CadAiTest \
-Dsurefire.failIfNoSpecifiedTests=false package
```
Rust 与网页在各自仓库运行:
```sh
cargo test -p solidcraft-web
cargo test -p solidcraft-ui-egui agent_chat
node scripts/sync-cad-ai-skills.mjs --check ../community
VIBEMAKE_CAD_ENGINE_OUT=/private/tmp/cad-native-parity-engine node scripts/build-vibemake-cad.mjs
```
主站 CAD 测试和独立构建:
```sh
npm run test:cad
VIBEMAKE_CAD_ENGINE_DIST=/private/tmp/cad-native-parity-engine \
VIBEMAKE_CAD_PACKAGE_DIR=/private/tmp/cad-native-parity-release/cad \
VIBEMAKE_CAD_PACKAGE_ZIP=/private/tmp/cad-native-parity-release/cad.zip \
npm run build:cad
```
本轮测试服务使用独立端口 19091/19092,不重启既有共享服务。浏览器测试以 `VM_CAD_BASE_URL=http://127.0.0.1:19091` 运行现有 `test:cad:platform-agent`,通过真实 HTTP 流的 gate 在 completed 之前检查中文正文预览;覆盖成功、断流后恢复、停止、关闭预览四种场景。测试 mock 的释放接口只存在于 `tests/cad`,没有新增业务 API。
## 已完成的验证记录
| 检查 | 当前结果 | 证据 |
| --- | --- | --- |
| Java 全量 reactor(common/service/security/api) | 635 项,0 失败、0 错误、13 项外部环境用例跳过 | `/private/tmp/cad-native-parity-java-full-isolated.log` |
| CAD 定向测试及 Java JAR 打包 | 110 项通过,BUILD SUCCESS | `/private/tmp/cad-native-parity-java-package.log` |
| Rust UI 助手 | 312 项通过,含正文预览与桌面原行为回归 | `/private/tmp/cad-native-parity-rust-ui.log` |
| Rust 浏览器纯逻辑 | 63 项通过 | `/private/tmp/cad-native-parity-rust-web.log` |
| 主站 CAD Node 测试 | 75 项通过 | `/private/tmp/cad-native-parity-site-unit.log` |
| 新 WASM 完整 Chromium 回归 | 59 项检查通过,pageerror 为空;含真实 SSE 的成功、恢复、停止、关闭预览 | 交付目录 `browser-result.json`,原始日志 `/private/tmp/cad-native-parity-browser.log` |
| 独立 WASM 与 CAD ZIP 构建 | release 构建成功;9 项引擎资源与 ZIP 的尺寸、SHA 和 manifest 全部一致 | 交付目录 `release-manifest.json`、`SHA256SUMS.txt` |
| 原生 UI 助手生产库 clippy | --no-deps --lib -D warnings 通过 | `/private/tmp/cad-native-parity-clippy-ui.log` |
| 本轮 Rust 文件格式 | rustfmt --check 通过 | `/private/tmp/cad-native-parity-rust-format.log` |
| 三个仓库差异与保护检查 | git diff --check 通过;与初始工作区相比,无关已有 tracked diff 未变 | 交付目录 `implementation-only.diff`、`baseline/` |
| 源码知识目录与正文 | 18 个文件 SHA 与基线一致(目录 1 + 正文 17) | 基线 `baseline.json` |
| Java JAR 中的知识目录与正文 | 18 个打包条目 SHA 与基线一致 | `BOOT-INF/lib/vibemake-service-0.0.1-SNAPSHOT.jar` |
| 通用 Skills | 17 个一致 | sync 脚本 check,revision 见上 |
严格 WASM 全依赖 clippy 的 `-D warnings` 被未改动的 `crates/io/src/safe_write.rs:298`(`drop_non_drop`)阻断。仅检查网页包时还发现未改动的 `apps/solidcraft-web/src/files.rs:679`(`useless_conversion`)。本轮已修改的流解析文件中的 needless_borrow / while_let_loop 已修正;`cargo clippy --no-deps -p solidcraft-web --target wasm32-unknown-unknown -- -D warnings -A clippy::useless_conversion` 已通过。此豁免仅用于到达本轮代码,不表示整仓严格 CI 已通过,也没有为清理无关告警扩大业务修改。
初次全量测试未设置隔离环境开关,部分与本轮无关的 Spring 上下文因默认开启而没有外部 OSS/Git/社区 AI 凭据,配置校验失败。没有修改生产默认值或测试代码来规避;用命令行 `AI_ENABLED=false OSS_ENABLED=false GIT_ENABLED=false CAD_AI_ENABLED=false` 隔离后,全量通过。真实模型 opt-in 测试保持跳过。
真实浏览器回归发现并修复了 Stop 后未消费 `reader.cancel()` 拒绝 Promise 的问题,新构建在预览场景后立即断言无 pageerror,并完成全套回归。另将旧的“新用户轮次删除全部旧图片”测试预期对齐为保留文字、完整工具配对和预算允许的最近图片;现有图片预留逻辑释放一个位置,未删除整段历史。连续长轮次实际完成 16 次模型调用和 30 次设计修改,已成功操作没有因模型请求恢复而重复执行;这仍不意味着单轮可以无限增长。
独立 CAD ZIP 已生成于 `target/cad-ai-native-parity-20261113/cad.zip`,SHA-256 为 `4919c1e449bb159c7535c7d44ba06a3cc15974a3444834220218c035d1e654f7`。页面 buildId 为 `mwemkwjv`,engineBuildId 为 `6eb2b6d46259828ad2ef139f`;9 项引擎资源的尺寸、SHA 及 ZIP 内的目录与 manifest 已验证。ZIP 根即 `/cad/` 部署内容,不能再套一层 cad 目录。
实时预览截图为交付目录中的 `browser-stream-preview.png`,是在 completed 释放前通过浏览器捕获,已人工查看。正文位于现有助手面板中;没有独立弹层或额外外框。
已生成 Java JAR:`target/cad-ai-native-parity-20261113/vibemake-api-0.0.1-SNAPSHOT.jar`,SHA-256 为 `7b7382ce409ea18df420bdc67d8b2c758b0d8e7eb865ecc94f392ca1c5698c4d`。同目录提供 `release-manifest.json`、`SHA256SUMS.txt`、`verification.json`、`browser-result.json`、`verify-artifacts.py` 和本轮源码差异;二进制位于被 Git 忽略的 `target/` 下,没有加入版本控制。运行 `python3 target/cad-ai-native-parity-20261113/verify-artifacts.py` 可离线复核两个发布产物、9 项引擎资源和 18 个知识条目,不需要模型凭据。
## 发布、验证与回退
1. 先在独立测试环境发布 Java JAR,再合并部署完整 CAD 包至网站的 `/cad/`。本轮没有执行生产部署。
2. 原有模型 endpoint、model、thinking、effort、输出上限、密钥及知识开关保持原配置,凭据只存于服务端。
3. 核对代理 SSE 缓冲关闭,例如 Nginx `proxy_buffering off`;连接读取超时覆盖模型 deadline 与心跳周期,不能提前切断仍正常生成的流。
4. 核对 `/cad/build-info.json` 中的 engineBuildId 与 `engine.json` 一致,WASM MIME 为 `application/wasm`。HTML、manifest 和控制 JS 使用重新验证缓存;`_assets/<buildId>/` 可 immutable。
5. 保留旧 `_assets` 目录,避免正在打开的编辑器丢失旧构建资源。使用新会话检查中文实时正文、一次工具成功后断流恢复、停止及知识读取;不要只看 HTTP 200。
6. 后端仍兼容旧请求/事件结构,新前端也可使用旧后端。回退使用上一份已验证 Java JAR 和完整 CAD 包;同步核对缓存和构建号。无需数据库回退。
7. 回退代码时按本轮文件差异恢复,不要 reset 整个工作区;基线中的未提交修改属于此前工作。
## 已知限制与真实模型验收
受控 mock 证明协议、流解析、恢复边界和工具执行安全,不能等同于商业模型真实任务成功率。用户已明确选择“先交付代码和模拟回归结果”,本轮不执行真实模型对照。当前隔离测试进程未注入默认豆包模型所需的密钥,未读取 `.env` 或桌面密钥,未执行付费模型调用。后续真实模型对照必须使用同一厂商、模型、思考参数、输出上限和固定公开小样例;不得用不同模型结果推断迁移效果。
已有 `ArkCadAiLiveTest` 需显式 `VIBEMAKE_CAD_AI_LIVE_TEST=true`;CAD/MCP 长任务还需单独开关及隔离 CLI 路径。可以在已配置凭据的测试环境再执行。网络持续失败、服务端不可用、模型拒绝或当前单轮过大仍可能结束,且本轮没有服务端断点续跑和刷新恢复能力。
+103
View File
@@ -0,0 +1,103 @@
# CAD AI 响应处理与有限恢复全面审计(2026-11-13)
## 现场结论
项目 `29qyy7fzc7ds` 在 2026-11-13 16:54:40 的失败请求为 `b2d7a32feec14632a690e4012dc02887`。
运行包日志明确指向 `ArkCadAiClient.result` 当时第 630 行,即 Responses `output` 条目类型分支的默认拒绝路径。
这说明遇到了无法识别的条目(也可能是缺失类型或条目形状损坏);旧日志没有记录具体类型,不能进一步推定原始内容。
该路径被归类为 `CAD_AI_PROVIDER_FAILURE`、`retryable=false`,因此浏览器遵守返回标志立即终止,没有执行自动恢复。
当次请求耗时 9827 ms,不是超时路径,也不是日志中的上下文超限路径。
原版 `crates/ui-egui/src/agent_chat/api_client.rs` 的 Responses 转换会忽略未知输出类型。
网页实现增加了执行前完整校验,却把所有不符合预期的响应混成永久错误,导致两者容错表现不同。
本次兼容有明确语义的差异,并把不可信生成结果送入现有有限恢复;不会把包含未知操作的响应直接当成功。
## 审计与处理规则
| 入口/情况 | 处理 | 对 CAD 执行的影响 |
| --- | --- | --- |
| Responses 未知/缺失/非文本 `type`,非对象条目 | 拒绝整次响应,可恢复;记录固定规则、条目索引、形状与类型指纹 | 不返回任何部分工具 |
| 顶层/正文/工具结构损坏、非预期角色、非法状态 | 拒绝整次响应,可恢复 | 完整响应通过前不执行 |
| 正文出现在工具之前、之间或之后 | 按原版分别收集正文与工具,再规范化为正文在前;两组内部相对顺序保留 | 工具按原顺序执行 |
| reasoning 无加密状态 | 可选信息,忽略,沿用原行为 | 不影响有效回答 |
| reasoning 有加密状态但必需字段、唯一性或格式错误 | 拒绝整次响应,可恢复 | 不提交坏状态或工具 |
| usage 缺失/null | 无用量信息,正常完成 | 不影响有效回答 |
| usage 非对象、负数、浮点、数字字符串或溢出 | 丢弃整份用量计数,记录脱敏告警 | 不影响有效回答;不会使用不可信计数 |
| SSE JSON 损坏、重复键、尾随 JSON、空/非对象事件 | Java 拒绝,可恢复 | 不返回部分工具 |
| 中文 UTF-8 跨包、跨包事件、CRLF、心跳、多行 data | 正常组装 | 不提前执行 |
| 编码损坏、网络 EOF、缺终态、断流、超时 | 丢弃未确认响应,可恢复 | 已确认工具结果保留 |
| 上游/代理返回非 SSE Content-Type | 拒绝响应,可恢复 | 不把普通文本当工具 |
| Chat Completions finish-only chunk 缺省空 delta | 兼容为空对象;仍要求合法终态和 `[DONE]` | 不提前成功 |
| Chat Completions 同一工具分片重复相同 call id | 允许相同 ID,拒绝中途更换 ID | 保持完整关联 |
| Chat Completions index、delta、finish_reason 形状损坏 | 拒绝整次响应,可恢复 | 不执行部分调用 |
| 上游 `error` / `response.failed` | 按白名单错误码分类;未知生成失败可恢复 | 不记录上游自由文本或执行失败响应中的工具 |
| HTTP 408/429/5xx,临时连接/TLS record 故障 | 沿用有限恢复 | 不叠加 Java 通用重试 |
| 鉴权、权限、额度、模型配置、明确拒绝、上游上下文硬上限 | 保持终止并给出对应提示 | 不盲目重复相同无效请求 |
| 证书、TLS 握手或主机验证失败 | 保持终止 | 不降低 TLS 验证 |
| 文本、流、事件、推理字节数、输出条目/工具数量超限 | 明确 `CAD_AI_OUTPUT_LIMIT`,保持终止 | 不截断成可执行操作 |
| 输入历史转换错误 | 独立 INPUT 类,保持终止 | 不伪装成可重新生成的模型错误 |
| 浏览器 SSE envelope/字段缺失、坏 JSON/UTF-8、未知事件 | 拒绝该尝试,按相同预算恢复 | 不让 `String -> terminal` 漏掉恢复 |
| 浏览器空 text_delta | 无内容,直接忽略 | 不改变正式历史 |
| 浏览器非文本 text_delta、completed 不匹配 | 拒绝该尝试,可恢复 | 不确认临时正文或工具 |
| 明确 requestId 改变、文档/轮次不匹配、账号/项目失效 | 保持终止/取消 | 旧响应不能修改其他文档 |
| 未知工具、坏参数、重复 callCode、公告与 completed 不一致 | 沿用受约束纠错与完整校验 | 不执行被拒绝的调用 |
## 恢复约束与用户可见结果
- 每个冻结的模型请求最多重试 2 次,即最多 3 次尝试;当前任务累计最多 6 次恢复。预算、退避和开关不变。
- Java 不新增通用网络重试。原有 Chat Completions HTTP 400 `reasoning_effort` 特定兼容处理不变。
- 重试只发生在尚未执行工具的模型请求内。已确认的 CAD 调用及结果保持完整,不重放已完成操作。
- 可恢复的协议错误可以传递现有 `CadAiRecovery` 结构,只有经过校验的固定诊断会进入下一次请求。
- 请求主体、历史、模型配置、图片、推理续接和文档修订快照保持冻结,只允许附加受限纠错信息。
- 失败尝试的临时正文和工具公告不提交正式历史;实时预览在失败、重试、取消或终止时清理。
- 新提示明确区分“当前步骤重试 2 次仍失败”“任务已用完 6 次恢复”和“自动恢复已关闭”,终态日志附 `recovery_stop`。
- 保留 `completed.output` 作为正式历史来源,保留 SSE 事件名、API 路由、厂商协议、知识库和 CAD 门禁。
- 本次未改数据库、SQL、社区 AI、CAD 内核或手动保存逻辑。
## 自动化证据
证据目录:`target/cad-ai-protocol-audit-20261113/`。
- `baseline.json`、`baseline/`:开始本轮前的仓库状态和源码基线;保留原有未提交修改。
- `incident.log`:上述请求的脱敏日志。
- `java-before.log`:新增的三组测试在旧实现上失败(2 个断言失败、1 个异常),分别复现响应错误永久化、Chat 同类问题和正文/工具交错误拒绝。
- `java-package.log`、`java-results.json`:主 API 及依赖模块的 Maven package 回归;645 项,0 失败,0 错误,13 项环境跳过,不包含导入与管理后台模块。
- `rust-tests.log`:浏览器共享逻辑 70 项测试通过,包含一字节分片中文/CRLF、事件形状、身份冲突、恢复预算、冻结输入及几何不重放。
- `i18n-tests.log`:104 项翻译相关测试通过;检查发现此前助手功能缺少完整语言包文案,已在四份相关 pending 文件中补齐。
- `clippy.log`:`cargo clippy -p solidcraft-web --bin solidcraft-web -- -D warnings` 通过。
- `artifact-verification.json`:新旧后端的 40 项 CAD 资源及 3 项 application 配置哈希一致,网页 `list_commands` 优化实现与本轮基线一致。
- `wasm-build-final.log`:最终 Rust/WASM 发布构建;已有 UI crate WASM 警告单独保留,没有为了通过构建修改无关代码。
- `browser-protocol.mjs`:隔离浏览器回归入口。API 和模型均在内存中模拟,静态 JS/WASM 从 8091 实际 HTTP 加载;不使用真实账号、不访问真实模型、不启动额外 TCP 服务。
浏览器结果、发布构建编码、端口和更新后核对记录在证据目录的 `browser-results.json`、`deployment-verification.json` 以及发布包清单中。
### 提交前整个后端的补充核验
- 根项目全部 7 个后端模块及父工程,在 JDK 21 的隔离配置下完成 `mvn -Dvibemake.ai.enabled=false package`:760 项测试,0 失败、0 错误、14 项跳过。命令同时设置 `AI_ENABLED=false OSS_ENABLED=false GIT_ENABLED=false CAD_AI_ENABLED=false`,未调用真实模型,也未修改运行服务或仓库配置。
- 管理后台配置直接启用社区 AI,缺少密钥时不能只依靠主 API 的 `AI_ENABLED` 别名关闭它;上述 JVM 属性仅用于隔离测试。部署管理后台仍需独立核对社区 AI 配置。
- 首次全量构建中,`CadAiTest.forwardsOnlyValidatedProviderCorrectionForExplicitlyRecoverableErrors` 因读到空 SSE 结果失败。之后 CAD AI 定向 23 项及最终整个后端构建均通过,但首次失败的根因尚未定位,不能把复测通过视为缺陷已经修复;正式发布前仍需排查该项稳定性风险。
- 证据位于被 Git 忽略的 `target/backend-release-review-20261113/`:`verification-summary.json` 汇总所有尝试,`maven-package-isolated.log` 为最终全量构建记录。
- 本机 `.env` 不随代码提交。升级时应保留服务器外部配置;新部署要显式核对 `CAD_AI_*`,包括厂商、模型、endpoint、思考设置、输出上限及知识库模式。`CAD_AI_MODEL` 非空会覆盖所选厂商的模型;直接 `java -jar` 不会自动读取仓库根目录 `.env`。密钥由部署环境安全注入。
### 最终验收与本地更新结果
- 最终引擎:`5dfd0f20b78006f7610b3cf3`;28 组隔离浏览器场景全部通过,页面异常 0 个。
- 其中 15 组验证先完成一个真实 CAD 实体操作,再遇到不同响应故障,并在同轮恢复;实体不重复、冻结历史不变、失败工具不执行,撤销分组保持一致。
- 其余覆盖 requestId/文档/轮次冲突、权限、拒绝、资源上限、两类恢复预算耗尽、关闭恢复、空文字片段,以及可控 ReadableStream 的实时预览、失败清理和最终单份确认。
- 真实 HTTP 核对了全部 9 个引擎资源(145,267,435 字节)的长度和 SHA-256;公开 manifest 与最终构建一致,manifest `no-cache`,版本化资源 immutable。
- 当前仅本项目 8091 前端和 8993 后端监听,8092/8994 关闭。未动数据库、Redis 或其他项目服务。
- 8993 后端运行本轮 JAR,SHA-256 为 `c4320c8b9758fd8b683aa7f439b7da6a2b06ca9800e32ee9f2cbea13f46c40b4`;两个入口的未登录 CAD API 均返回 401/UNAUTHORIZED,普通 `/api/project-types` 返回 200/OK。
- 独立 CAD 发布包已构建并通过 ZIP 检查;文件、哈希及引擎对应关系见 `package-verification.json`。没有数据库迁移。
- 浏览器初始化测试中曾因开发服务器旧资源白名单导致候选资源 404;已修正更新步骤并重启核对。模拟回归脚本也修正了错误正文取值和主站提前捕获 fetch 引用的注入方式,未因此放宽产品断言。
- 已打开的编辑器需要保存当前设计并刷新,才能使用新 WASM 中的浏览器解析与恢复提示。
## 更新、验证与回退
1. 先构建独立 JAR 与版本化 WASM,保留旧包和旧 `_assets/<buildId>/`。
2. 把新版本静态资源加入 8091 的资源目录。开发静态服务器在启动时冻结资源白名单,仅复制新资源不能访问;须切换候选 manifest 并重启当前 8091 后,立即用隔离账号与模型跑浏览器回归,失败则恢复上一版 manifest 和服务。
3. 核对 8993 没有运行中的模型连接后,使用已有 `local-8091/manage.py backend <JAR>` 优雅更新,沿用私有运行环境,不打印凭据。
4. 原子替换 `engine.json`、`sw.js`;开发服务器必须重启当前记录的 8091 进程以刷新资源白名单,不启动 8092/8994。
5. 核对实际 HTTP manifest、资源校验和、健康检查及本项目监听端口。已打开页面需刷新后加载新 WASM。
6. 回退使用 `previous-engine.json`、`previous-sw.js` 和 `baseline.json` 中记录的上一版运行 JAR;不使用会恢复更老初始环境的通用 `restore` 命令。不迁移数据库。
不能保证上游永不生成无效内容、永久不断网或任务无限长。本次消除已覆盖路径中“可恢复响应被误分类为永久错误而首次失败即终止”的缺陷,同时明确持续失败和硬限制。真实厂商稳定性对照未运行,遵循用户“先交付代码和模拟回归结果”的要求。
+84
View File
@@ -0,0 +1,84 @@
# CAD AI 提前终止故障分析与修复(2026-11-13)
## 结论
本次实际日志确认两条会直接结束任务的错误处理缺陷:上游 `response.failed` 被误报为协议格式损坏,以及 TLS 数据校验异常被统一标成不可重试。浏览器已有有限恢复,但它必须收到 Java 返回的 `retryable=true`;两条路径均返回了 false,因此没有进入恢复。
这是上一轮迁移与验收的遗漏。之前的测试甚至把最小 `response.failed` 断言为永久格式错误,测试通过不能证明这条真实失败路径正确。没有证据表明本次是 CAD 命令参数校验或浏览器工具执行造成的终止。
## 实际证据
项目编码为 `00bhzgghw0az`。以下时间均为 2026-11-13,Asia/Shanghai。
| 时间 | 请求编码 | 已确认事实 |
| --- | --- | --- |
| 15:24:36 | `21f5aa6db30c44d0bff6f720eb74d79b` | 一次传输失败返回 retryable=true,随后浏览器恢复并继续,证明恢复开关并未整体失效 |
| 15:36:00 | `4cf2687bef4a4c838caef3be9bb0c2be` | 等待约 42.8 秒后收到 response.failed;Java 记为 stage=response_parse、reason=invalid_response、retryable=false |
| 15:46:33 | `3a393e4941cd49d2ac048701587d2fe1` | 后续用户尝试出现 ExecutionException -> SSLException -> AEADBadTagException;Java 记为传输失败、retryable=false |
第一轮共 46 次请求开始、44 次完成、2 次失败。其中第一次失败恢复成功,最终的失败终态导致整轮结束,并非用尽整轮六次恢复额度。原始安全证据保存在 `target/cad-ai-response-failed-20261113/incident-evidence.json` 和 `tls-incident-evidence.json`;没有保存设计正文、密钥或原始模型推理。
第一条路径的代码将 `error`、`response.failed` 和 `response.incomplete` 合并处理,除输出上限和内容过滤外最终调用通用 `failure()`。这个方法默认表示 `invalid_response` 且不可重试。合法的上游失败事件因此被错误归因。
第二条路径只检查一层异常原因,并将所有 `SSLException` 排除在重试之外;实际的 TLS 数据校验异常也随之直接终止。现有日志只能证明具体异常链,不能证明它来自某个 JDK 缺陷、代理实现或特定网络设备。
## 为什么不能认定已经与原版本地等价
此前作为基准的普通 API OpenAI 路径:
- `solidcraft-main/crates/ui-egui/src/agent_chat/api_client.rs` 的 `post()` 使用 `/chat/completions`。
- `api_wire.rs` 的普通 OpenAI 请求没有 `stream=true`,`send()` 等待完整字节后解析 JSON。
- 原版有特定的 reasoning_effort 参数兼容重发,不代表它有通用无限恢复;上游 HTTP 错误仍可能结束任务。
网页仍按已确认的配置使用 Responses SSE 和 Java HttpClient。工具循环、历史裁剪相似,不代表请求协议、流解析和传输链路相同。OpenCode Go 等特殊路径另有协议处理,不能把上述结论泛化为所有桌面助手。
本次未确认用户桌面当前实际选择的是普通 API、ACP 或其他助手配置,因此不能断言桌面与网页正在使用完全相同的模型、endpoint、参数和调用链,也不能断言原版遇到相同上游失败必定成功。本次没有切换厂商、协议、模型或思考设置。
## 上下文问题的证据边界
第一轮最后一次成功请求的输入为 98,111 token,之后一个新用户轮次又有 100,783 输入 token 的成功请求。这说明不能单凭“约 9.8 万 token”认定上游失败就是上下文超限。
旧实现未提取失败事件中的具体 error.code/type,失败时的 outputTokens=-1 仅表示没有提供这个字段。上游为什么生成失败,现有日志无法事后还原,不能把未知原因写成确定的上下文超限或网关故障。
历史裁剪目前只在新用户轮次开始执行,240 个 HistoryItem 是条目目标,不是 token 保证;它不能阻止同一长轮次持续增长。此次没有引入摘要、单轮自动压缩或任务持久化,这些既有限制仍然存在。
## 局部修复
生产代码仅修改 CAD 专用 `ArkCadAiClient.java`:
1. 单独分类上游生成失败,提取 response.error、error 对象及根 error 事件中的 code/type。
2. 临时或原因未知的失败交由浏览器已有有限恢复;上下文、额度、鉴权、权限、内容拒绝等已知永久类别保持不可重试,并返回固定中文提示。
3. 有界检查异常链,允许明确 TLS 数据标签异常和嵌套 I/O 故障进入有限恢复。证书、握手、主机身份验证、未知 SSL、损坏编码、协议错误以及循环/过深异常链不自动重试。
4. TLS 校验不放宽,失败数据不会成为模型输出。Java 不新增通用重试;每次仍只发送一次模型 HTTP 请求。
5. 错误日志只记录白名单类别和固定诊断,不记录上游自由文本、凭据、原始模型推理或完整设计。
浏览器恢复继续最多每请求两次、整轮六次;冻结同一请求,不能重跑已完成 CAD 修改。失败响应不能提交 completed.output 或执行其中工具。正文预览仍由既有前端失败清理逻辑处理。
知识库目录、17 份正文、读取接口、权限与去重实现未修改。三个 application 配置文件与修复前 JAR 字节一致;知识目录加正文共 18 个打包条目的 SHA-256 与此前基线一致。没有修改数据库、SQL、CAD 内核、社区 AI、主站业务接口、前端或 WASM。
## 验证
| 检查 | 结果 |
| --- | --- |
| 修复前实际运行 JAR 与修复后的同条件模拟对照 | 临时失败、永久失败提示、安全诊断、TLS 数据异常四组:旧 JAR 全部失败,新版全部通过 |
| TLS 回归先运行在未修复实现上 | expected true but was false,复现不可重试缺陷 |
| Java 最终全量回归与 package | 639 项,0 失败、0 错误、13 项环境用例跳过,BUILD SUCCESS |
| Rust 既有浏览器模型恢复测试 | 6 项通过,覆盖 flag、冻结历史、已应用几何、次数上限和停止/代次保护 |
| 产物、配置、知识资源 | 离线校验通过,知识 18 个条目保持一致 |
新增回归放入现有 `ArkCadAiClientTest.java`,不创建新的正式测试文件。TLS 通过 mock HttpClient 返回实际类型的异常链,测试完整 complete() 的分类出口;没有调用真实模型或在公网注入故障。对照辅助程序与产物在被忽略的 target 目录。
证据目录:`target/cad-ai-response-failed-20261113/`,包含最终测试日志、`comparison/final-result.json`、`release-manifest.json`、`local-validation.json` 和 `implementation-only.diff`。可执行 `python3 target/cad-ai-response-failed-20261113/verify-artifacts.py` 离线复核。
## 本地更新与回退
仅更新本项目 8993 Java 后端,8091 前端保持运行,8092/8994 保持关闭。最终包为 `target/cad-ai-response-failed-20261113/vibemake-api-responses-tls-20261113.jar`,SHA-256:`93e991c63f67a966bd41f83c0c9e75b7d54592ef7a1575344e05ab8062fa871d`。前端 engineBuildId 仍为 `6eb2b6d46259828ad2ef139f`。
```sh
python3 target/cad-ai-native-parity-20261113/local-8091/manage.py backend \
/Users/lk/Projects/vibemake相关项目/community/target/cad-ai-response-failed-20261113/vibemake-api-responses-tls-20261113.jar
```
回退到本次排查前的 JAR,使用同一命令并把路径替换为 `target/cad-ai-response-failed-20261113/before/vibemake-api.jar` 的绝对路径;不回退前端、不改数据库。脚本会核对端口 PID,再优雅停止指定后端,保留私有环境。原始迁移产物及其 manifest 未覆盖,仍可离线校验。
本次按用户已确认的范围,只做代码与模拟回归,没有主动发起付费模型调用。已失败的浏览器轮次不会因后端更新自动继续,需要在原页面发起后续请求。修复证明错误分类和恢复入口已纠正,不等于已经重跑该真实长任务成功,也不能保证持续上游故障或超限任务一定完成。
+6 -6
View File
@@ -1,8 +1,8 @@
# CAD Web AI Agent 前端对接
本文描述已实现的后端接口和 makeCAD 网页端需要完成的适配。后端不运行 CAD 引擎,不执行工具,也不持久保存聊天。**仅嵌入当前 makeCAD 网页构建不会自动启用 Agent**:原有模型客户端、CLI Agent 和聊天入口受桌面编译条件限制,需要前端新增网页 `ChatBackend`、工具适配器及文档生命周期管理。
本文描述现有 Java 后端与 makeCAD 平台网页助手的对接。后端不运行 CAD 引擎,不执行工具,也不持久保存聊天;网页 `PlatformBackend` 负责工具循环、有效历史及文档生命周期。2026-11-13 的原版行为迁移与验收见 [实施记录](cad-ai-native-parity-20261113.md)。
调用链:makeCAD 面板 → `/api/cad/ai/chat` → 豆包 → 浏览器执行工具 → 携带结果再次请求。一次 HTTP 请求只推进一次模型推理。设计文件的保存与续编仍使用 [CAD 工作空间接口](frontend-cad-workspace.md)。
调用链:makeCAD 面板 → `/api/cad/ai/chat` → 当前配置的模型服务 → 浏览器执行工具 → 携带结果再次请求。一次 HTTP 请求只推进一次模型推理。设计文件的保存与续编仍使用 [CAD 工作空间接口](frontend-cad-workspace.md)。
## 登录、启用和能力
@@ -71,7 +71,7 @@ interface CadAiRequest {
正常顺序示例:`用户 → 助手文字(可选) → 调用 A → 调用 B → 结果 A → 结果 B → 助手 → 新用户`。工具可以只有调用而没有说明文字;一次调用失败仍回填 `isError=true`,不要删除关联调用。
完整历史由前端持有,刷新或关闭页面后不恢复。超过总量、图片数或条目数时,裁剪最早的**完整用户轮次**,不单独删除调用或结果。当前轮次本身超限时停止并提示开启新聊天。图片限制覆盖历史图片:保留当前轮次需要的图片,必要时清理整轮旧历史。
有效模型历史由前端持有,刷新或关闭页面后不恢复。新用户消息加入后,以 `min(240, 后端有效 historyItems 上限)` 为目标删除最早的**完整用户轮次**,始终保留当前用户轮次,不拆散工具配对;界面记录不随之删除。历史图片只保留最近两张,并服从更低的后端图片上限,旧图替换为说明文字。每次请求仍保留现有 JSON 压缩、Skill/知识去重、只读参考压缩及资源检查。当前单轮仍超限时明确停止并保留已完成修改,不以删除当前任务要求来规避限额。普通单块纯文本工具结果在 UTF-8 边界按 20,000 字节截断并标注;知识、Skill、JSON/结构化及混合结果继续使用原有完整结果保护。
## SSE 事件和执行边界
@@ -79,12 +79,12 @@ interface CadAiRequest {
| event | data 其他字段 | 前端行为 |
| --- | --- | --- |
| `text_delta` | `text` | 追加助手显示文本 |
| `text_delta` | `text` | 立即更新当前请求尝试的临时正文,不写入正式历史 |
| `tool_call` | `callCode,name,arguments` | 展示待执行卡片,暂不执行 |
| `completed` | `finishReason,output,usage` | 本步成功终态;output 是规范化 HistoryItem[] |
| `error` | 无其他字段,错误在包装的 code/message | 停止本轮,保留设计;不执行待确认工具 |
| `error` | `retryable`,可选安全 `correction`;错误在包装的 code/message | 清除该次临时正文;沿用有限恢复,最终失败时停止并保留设计;不执行待确认工具 |
`completed.finishReason` 为 `stop` 或 `tool_calls`。`usage` 为 `{inputTokens,outputTokens,totalTokens}`,上游未提供时为 null。本步 `output` 是历史回填的唯一来源,不再把 text_delta 或 tool_call 额外拼进历史,避免重复。
`completed.finishReason` 为 `stop` 或 `tool_calls`。`usage` 为 `{inputTokens,outputTokens,totalTokens}`,上游未提供时为 null。本步 `output` 是历史回填的唯一来源,不再把 text_delta 或 tool_call 额外拼进历史,避免重复。临时正文按请求尝试隔离;`completed` 校验通过后用最终正文替换预览,失败、重试或停止时移除预览。账户偏好 `agent_stream_preview=false` 可恢复仅显示完整回复的旧行为;桌面 `Event::Text` 保持原行为。
**只有完整收到 `completed` 且 `finishReason=tool_calls` 后,才按 output 中的调用顺序执行。** 所有工具参数在上游完整结束后才会被后端验证和交付。截断、参数损坏、未知工具、拒绝、超时或断流不会产生成功 completed;显示过的文字不是执行依据。不要将模型自然语言中的伪工具调用作为命令运行。
@@ -443,6 +443,25 @@ class CadAiTest {
}
}
@Test void forwardsOnlyValidatedProviderCorrectionForExplicitlyRecoverableErrors() throws Exception {
CadAiRecovery safe = new CadAiRecovery("unknown", "invalid_response", "$");
for (boolean retryable : List.of(true, false)) {
for (Object detail : List.of(safe, new CadAiRecovery("unsafe\nname", "required", "$.secret"), "PRIVATE_RAW_RESPONSE")) {
model.handler = (input, text, cancellation) -> {
text.accept("unconfirmed response");
throw new BusinessException(502, "CAD_AI_PROVIDER_FAILURE", "invalid response", Map.of("retryable", retryable, "correction", detail));
};
MvcResult initial = start(input());
JsonNode failure = finish(initial).getLast();
assertThat(failure.path("data").path("retryable").asBoolean()).isEqualTo(retryable);
JsonNode correction = failure.path("data").path("correction");
if (retryable && detail == safe) assertThat(correction).isEqualTo(json.valueToTree(safe));
else assertThat(correction.isNull() || correction.isMissingNode()).isTrue();
assertThat(initial.getResponse().getContentAsString()).doesNotContain("event:completed", "event:tool_call", "PRIVATE_RAW_RESPONSE", "unsafe");
}
}
}
@Test void acceptsRecoveryMetadataWithoutChangingHistoryAndRejectsUnsafeDiagnostics() throws Exception {
CadAiChatRequest normal = input();
CadAiRecovery correction = new CadAiRecovery("set_parameter", "required", "$.value");
@@ -14,14 +14,19 @@ import java.net.URI;
import java.net.http.*;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import javax.crypto.AEADBadTagException;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
/** CAD-only provider adapters. A complete provider terminal event is required before executing tools. */
@@ -30,6 +35,46 @@ public class ArkCadAiClient implements CadAiModelClient {
private static final Logger log = LoggerFactory.getLogger(ArkCadAiClient.class);
private static final int MAX_STREAM_CHARS = 2 * 1024 * 1024;
private static final int MAX_EVENT_CHARS = 512 * 1024;
private enum ProviderFailure {
INPUT("request_encode", "invalid_history", "请求历史不符合当前协议,请开始新对话", false),
RESPONSE("response_parse", "invalid_response", "模型响应格式不符合当前协议", true),
JSON("response_parse", "invalid_json", "模型响应包含损坏的 JSON", true),
CONTENT_TYPE("response_headers", "unexpected_content_type", "模型服务未返回 SSE 流", true),
INCOMPLETE("stream", "incomplete_stream", "模型响应连接中断或缺少完整结束事件", true),
TRANSPORT("transport", "request_failed", "模型服务连接失败", true),
UPSTREAM("upstream_terminal", "generation_failed", "模型服务返回生成失败", true),
REFUSAL("response_parse", "model_refusal", "模型拒绝了本次请求", false),
REASONING("response_parse", "invalid_reasoning_state", "模型返回的推理续接状态无效", true),
HTTP("response_headers", "http_rejected", "模型服务拒绝请求", false);
private final String stage;
private final String reason;
private final String message;
private final boolean retryable;
ProviderFailure(String stage, String reason, String message, boolean retryable) {
this.stage = stage; this.reason = reason; this.message = message; this.retryable = retryable;
}
}
/** Internal diagnostics never form part of the public SSE error payload. */
private static final class ProviderException extends BusinessException {
private final ProviderFailure failure;
private final Integer httpStatus;
private ProviderException(ProviderFailure failure, boolean retryable, String message, Integer httpStatus) {
super(502, "CAD_AI_PROVIDER_FAILURE", "CAD AI " + message + ",已完成的修改会保留",
retryable ? retryDetails(failure) : null);
this.failure = failure;
this.httpStatus = httpStatus;
}
private static Map<String, Object> retryDetails(ProviderFailure failure) {
if (Set.of(ProviderFailure.RESPONSE, ProviderFailure.JSON, ProviderFailure.REASONING).contains(failure))
return Map.of("retryable", true, "correction", new CadAiRecovery("unknown", failure.reason, "$"));
return Map.of("retryable", true);
}
}
private static final String SYSTEM = """
你是 makeCAD CAD 建模助手,使用中文回复。当前设计位于用户浏览器中,后端没有 CAD 文件系统。
使用提供的工具读取和修改当前设计。先查 list_commands、describe_command,再按准确参数执行,不猜测命令。
@@ -68,6 +113,7 @@ public class ArkCadAiClient implements CadAiModelClient {
if (!properties.supportsImages() && input.history().stream().filter(item -> item.content() != null)
.flatMap(item -> item.content().stream()).anyMatch(part -> "image".equals(part.type())))
throw new BusinessException(400, "CAD_AI_IMAGE_UNSUPPORTED", "当前 CAD 模型不支持图片,请切换至支持图片的服务商");
long started = System.nanoTime();
AtomicBoolean timedOut = new AtomicBoolean();
ScheduledFuture<?> deadline = timer.schedule(() -> {
timedOut.set(true);
@@ -76,45 +122,54 @@ public class ArkCadAiClient implements CadAiModelClient {
CompletableFuture<HttpResponse<InputStream>> pending = null;
try {
cancellation.check();
byte[] payload = json.writeValueAsBytes(properties.usesChatCompletions() ? chatBody(input) : body(input));
HttpRequest request = HttpRequest.newBuilder(URI.create(selected.getEndpoint()))
.timeout(properties.getRequestTimeout())
.header("Authorization", "Bearer " + selected.getApiKey())
.header("User-Agent", selected.getUserAgent())
.header("Content-Type", "application/json").header("Accept", "text/event-stream")
.POST(HttpRequest.BodyPublishers.ofByteArray(payload)).build();
pending = http.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream());
CompletableFuture<HttpResponse<InputStream>> current = pending;
cancellation.onCancel(() -> current.cancel(true));
HttpResponse<InputStream> response = pending.get(properties.getRequestTimeout().toMillis(), TimeUnit.MILLISECONDS);
try (InputStream stream = response.body()) {
cancellation.onCancel(() -> close(stream));
ObjectNode body = properties.usesChatCompletions() ? chatBody(input) : body(input);
// Only the native, explicit HTTP-400 reasoning_effort compatibility
// retry lives here. General transport retries belong to the browser.
for (int attempt = 0; ; attempt++) {
cancellation.check();
if (response.statusCode() < 200 || response.statusCode() >= 300) {
log.warn("CAD AI 上游拒绝 provider={} httpStatus={}", properties.getProvider(), response.statusCode());
HttpRequest request = HttpRequest.newBuilder(URI.create(selected.getEndpoint()))
.timeout(properties.getRequestTimeout())
.header("Authorization", "Bearer " + selected.getApiKey())
.header("User-Agent", selected.getUserAgent())
.header("Content-Type", "application/json").header("Accept", "text/event-stream")
.POST(HttpRequest.BodyPublishers.ofByteArray(json.writeValueAsBytes(body))).build();
pending = http.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream());
CompletableFuture<HttpResponse<InputStream>> current = pending;
cancellation.onCancel(() -> current.cancel(true));
HttpResponse<InputStream> response = pending.get(properties.getRequestTimeout().toMillis(), TimeUnit.MILLISECONDS);
try (InputStream stream = response.body()) {
cancellation.onCancel(() -> close(stream));
cancellation.check();
int status = response.statusCode();
throw failure(status == 408 || status >= 500 && status <= 599);
if (status < 200 || status >= 300) {
if (attempt == 0 && status == 400 && properties.usesChatCompletions()
&& "default".equals(selected.getReasoningEffort()) && !tools.definitions().isEmpty()
&& refusesDefaultReasoning(stream)) {
body.put("reasoning_effort", "none");
log.info("CAD AI native compatibility retry provider={} stage=response_headers reason=reasoning_effort_none", properties.getProvider());
continue;
}
log.warn("CAD AI 上游拒绝 provider={} stage=response_headers reason=http_rejected httpStatus={}", properties.getProvider(), status);
throw failure(ProviderFailure.HTTP, status == 408 || status == 429 || status >= 500 && status <= 599,
"模型服务返回 HTTP " + status, status);
}
String contentType = response.headers().firstValue("Content-Type").orElse("");
if (!contentType.toLowerCase(Locale.ROOT).contains("text/event-stream")) throw failure(ProviderFailure.CONTENT_TYPE);
Set<String> previousCalls = new HashSet<>();
for (CadAiHistoryItem item : input.history()) if ("toolCall".equals(item.type())) previousCalls.add(item.callCode());
return properties.usesChatCompletions() ? consumeChat(stream, text, cancellation, previousCalls)
: consume(stream, text, cancellation, previousCalls);
}
String contentType = response.headers().firstValue("Content-Type").orElse("");
if (!contentType.toLowerCase(Locale.ROOT).contains("text/event-stream")) throw failure();
Set<String> previousCalls = new HashSet<>();
for (CadAiHistoryItem item : input.history()) if ("toolCall".equals(item.type())) previousCalls.add(item.callCode());
return properties.usesChatCompletions() ? consumeChat(stream, text, cancellation, previousCalls)
: consume(stream, text, cancellation, previousCalls);
}
} catch (Exception error) {
if (timedOut.get() || error instanceof TimeoutException
|| error instanceof ExecutionException && error.getCause() instanceof HttpTimeoutException)
throw new BusinessException(504, "CAD_AI_TIMEOUT", "CAD AI 请求超时,请保留当前修改后重试");
throw diagnose(input, new BusinessException(504, "CAD_AI_TIMEOUT", "CAD AI 请求超时,请保留当前修改后重试"), started);
if (error instanceof InterruptedException) Thread.currentThread().interrupt();
cancellation.check();
if (error instanceof BusinessException business) throw business;
if (error instanceof BusinessException business) throw diagnose(input, business, started);
logProviderException(error);
Throwable cause = error instanceof ExecutionException && error.getCause() != null ? error.getCause() : error;
boolean retryable = cause instanceof IOException
&& !(cause instanceof JsonProcessingException) && !(cause instanceof CharacterCodingException)
&& !(cause instanceof SSLException) && !(cause instanceof ProtocolException);
throw failure(retryable);
throw diagnose(input, failure(ProviderFailure.TRANSPORT, retryableTransportFailure(error), ProviderFailure.TRANSPORT.message), started);
} finally {
deadline.cancel(false);
if (pending != null) {
@@ -125,6 +180,18 @@ public class ArkCadAiClient implements CadAiModelClient {
}
}
private boolean refusesDefaultReasoning(InputStream stream) throws IOException {
byte[] bytes = stream.readNBytes(16 * 1024 + 1);
if (bytes.length > 16 * 1024) return false;
try {
JsonNode root = json.readTree(bytes);
if (root == null) return false;
JsonNode error = root.path("error");
return "reasoning_effort".equals(error.path("param").asText())
|| error.path("message").asText("").toLowerCase(Locale.ROOT).contains("reasoning_effort");
} catch (JsonProcessingException error) { return false; }
}
private ObjectNode body(CadAiChatRequest request) {
ObjectNode body = json.createObjectNode().put("model", properties.effectiveModel())
.put("stream", true).put("store", false).put("max_output_tokens", properties.getMaxOutputTokens());
@@ -163,7 +230,7 @@ public class ArkCadAiClient implements CadAiModelClient {
output.insert(0, json.createObjectNode().put("type", "input_text").put("text", "工具执行失败:"));
entry.set("output", output);
}
default -> throw failure();
default -> throw failure(ProviderFailure.INPUT);
}
}
return body;
@@ -233,7 +300,7 @@ public class ArkCadAiClient implements CadAiModelClient {
.put("content", (Boolean.TRUE.equals(item.isError()) ? "工具执行失败:\n" : "") + chatText(item.content()));
assistant = null;
}
default -> throw failure();
default -> throw failure(ProviderFailure.INPUT);
}
}
return body;
@@ -242,7 +309,7 @@ public class ArkCadAiClient implements CadAiModelClient {
private String chatText(List<CadAiContent> parts) {
StringJoiner text = new StringJoiner("\n");
for (CadAiContent part : parts) {
if (!"text".equals(part.type())) throw failure();
if (!"text".equals(part.type())) throw failure(ProviderFailure.INPUT);
text.add(part.text());
}
return text.toString();
@@ -269,11 +336,11 @@ public class ArkCadAiClient implements CadAiModelClient {
int value;
while ((value = reader.read()) != -1) {
cancellation.check();
if (++total > MAX_STREAM_CHARS) throw failure();
if (++total > MAX_STREAM_CHARS) throw outputLimit();
if (value != '\n') {
if (total == 1 && value == 0xFEFF) continue;
line.append((char) value);
if (line.length() > MAX_EVENT_CHARS) throw failure();
if (line.length() > MAX_EVENT_CHARS) throw outputLimit();
continue;
}
String current = line.toString();
@@ -283,48 +350,57 @@ public class ArkCadAiClient implements CadAiModelClient {
if (current.startsWith("data:")) {
if (!data.isEmpty()) data.append('\n');
data.append(current.substring(current.startsWith("data: ") ? 6 : 5));
if (data.length() > MAX_EVENT_CHARS) throw failure();
if (data.length() > MAX_EVENT_CHARS) throw outputLimit();
}
continue;
}
if (data.isEmpty()) continue;
String event = data.toString(); data.setLength(0);
if ("[DONE]".equals(event)) {
if (finish == null) throw failure(true);
if (finish == null) throw failure(ProviderFailure.INCOMPLETE);
return chatResult(message.toString(), reasoning.toString(), calls, finish, usage, previousCalls);
}
JsonNode chunk = read(event);
if (chunk.has("error")) throw failure();
if (chunk.hasNonNull("error")) throw upstreamFailure(chunk, "error");
JsonNode count = chunk.path("usage");
if (count.isObject()) usage = new CadAiUsage(token(count, "prompt_tokens"), token(count, "completion_tokens"), token(count, "total_tokens"));
if (!count.isMissingNode() && !count.isNull()) usage = usage(count, true);
if (!chunk.path("choices").isArray() || chunk.path("choices").size() > 1) throw failure();
if (chunk.path("choices").isEmpty()) continue;
JsonNode choice = chunk.path("choices").get(0);
if (choice.path("index").asInt(-1) != 0) throw failure();
if (choice.hasNonNull("index") && (!choice.path("index").isIntegralNumber()
|| !choice.path("index").canConvertToInt() || choice.path("index").asInt(-1) != 0)) throw failure();
if (finish != null) throw failure();
JsonNode delta = choice.path("delta");
// Some compatible providers omit the empty delta on a finish-only chunk.
if ((delta.isMissingNode() || delta.isNull()) && choice.path("finish_reason").isTextual()) delta = json.createObjectNode();
if (!delta.isObject()) throw failure();
if (delta.hasNonNull("refusal")) {
if (!delta.path("refusal").isTextual()) throw failure();
if (!delta.path("refusal").asText().isBlank()) throw failure(ProviderFailure.REFUSAL);
}
if (delta.hasNonNull("content")) {
if (!delta.path("content").isTextual()) throw failure();
String addition = delta.path("content").asText();
message.append(addition);
if (message.length() > 64 * 1024) throw failure();
if (message.length() > 64 * 1024) throw outputLimit();
text.accept(addition);
}
if (delta.hasNonNull("reasoning_content")) {
if (!delta.path("reasoning_content").isTextual()) throw failure();
reasoning.append(delta.path("reasoning_content").asText());
if (reasoning.length() > CadAiProtocol.REASONING_BYTES) throw failure();
if (reasoning.length() > CadAiProtocol.REASONING_BYTES) throw outputLimit();
}
if (delta.hasNonNull("tool_calls")) {
if (!delta.path("tool_calls").isArray()) throw failure();
for (JsonNode part : delta.path("tool_calls")) {
if (!part.path("index").isIntegralNumber() || !part.path("index").canConvertToInt()) throw failure();
int index = part.path("index").asInt(-1);
if (index < 0 || index >= 16) throw failure();
if (index < 0) throw failure();
if (index >= 16) throw outputLimit();
ChatCall call = calls.computeIfAbsent(index, ignored -> new ChatCall());
if (part.hasNonNull("id")) {
if (call.id != null || !part.path("id").isTextual()) throw invalidModelTool(null, "call_code", "$.callCode");
if (!part.path("id").isTextual() || call.id != null && !call.id.equals(part.path("id").asText()))
throw invalidModelTool(null, "call_code", "$.callCode");
call.id = part.path("id").asText();
}
if (part.hasNonNull("type") && !"function".equals(part.path("type").asText())) throw invalidModelTool(null, "tool_type", "$");
@@ -337,18 +413,22 @@ public class ArkCadAiClient implements CadAiModelClient {
if (!function.path("arguments").isTextual()) throw invalidModelTool(call.name.toString(), "arguments_json", "$");
call.arguments.append(function.path("arguments").asText());
}
if (call.name.length() > 128 || call.arguments.length() > MAX_EVENT_CHARS) throw failure();
if (call.name.length() > 128 || call.arguments.length() > MAX_EVENT_CHARS) throw outputLimit();
}
}
if (choice.hasNonNull("finish_reason")) finish = choice.path("finish_reason").asText();
if (choice.hasNonNull("finish_reason")) {
if (!choice.path("finish_reason").isTextual()) throw failure();
finish = choice.path("finish_reason").asText();
}
}
}
throw failure(true); // EOF is not a successful Chat Completions terminal event.
throw failure(ProviderFailure.INCOMPLETE); // EOF is not a successful Chat Completions terminal event.
}
private Result chatResult(String message, String reasoning, SortedMap<Integer, ChatCall> calls,
String finish, CadAiUsage usage, Set<String> previousCalls) {
if ("length".equals(finish)) throw new BusinessException(502, "CAD_AI_OUTPUT_LIMIT", "CAD AI 模型输出达到上限,已完成的修改会保留");
if (Set.of("content_filter", "refusal").contains(finish)) throw failure(ProviderFailure.REFUSAL);
if (!Set.of("stop", "tool_calls").contains(finish)) throw failure();
if ("tool_calls".equals(finish) && calls.isEmpty() || "stop".equals(finish) && !calls.isEmpty())
throw invalidModelTool(null, "finish_reason", "$");
@@ -365,8 +445,9 @@ public class ArkCadAiClient implements CadAiModelClient {
}
if (output.isEmpty()) throw invalidModelTool(null, "output_empty", "$");
if (!reasoning.isBlank()) {
if (reasoning.getBytes(StandardCharsets.UTF_8).length > CadAiProtocol.REASONING_BYTES) throw outputLimit();
try { protocol.validateReasoningContent(reasoning); }
catch (BusinessException error) { throw failure(); }
catch (BusinessException error) { throw failure(ProviderFailure.REASONING); }
output.set(0, output.getFirst().withReasoningContent(reasoning));
}
return new Result(List.copyOf(output), usage);
@@ -384,6 +465,9 @@ public class ArkCadAiClient implements CadAiModelClient {
}
private JsonNode modelArguments(String name, String source) {
// Native treats absent/blank arguments as an empty object, then validates
// the actual tool schema. Malformed and duplicate-key JSON stays rejected.
if (source == null || source.isBlank()) return json.createObjectNode();
try {
return json.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
.with(JsonParser.Feature.STRICT_DUPLICATE_DETECTION).readTree(source);
@@ -411,7 +495,7 @@ public class ArkCadAiClient implements CadAiModelClient {
int value;
while ((value = reader.read()) != -1) {
cancellation.check();
if (++total > MAX_STREAM_CHARS) throw failure();
if (++total > MAX_STREAM_CHARS) throw outputLimit();
if (value == '\n') {
String current = line.toString();
if (current.endsWith("\r")) current = current.substring(0, current.length() - 1);
@@ -420,14 +504,14 @@ public class ArkCadAiClient implements CadAiModelClient {
if (!data.isEmpty()) {
String event = data.toString();
data.setLength(0);
if ("[DONE]".equals(event)) throw failure(true); // Missing completed is a premature terminal event.
if ("[DONE]".equals(event)) throw failure(ProviderFailure.INCOMPLETE); // Missing completed is a premature terminal event.
JsonNode item = read(event);
String type = item.path("type").asText();
if ("response.output_text.delta".equals(type)) {
JsonNode delta = item.path("delta");
if (!delta.isTextual()) throw failure();
emitted += delta.asText().length();
if (emitted > 64 * 1024) throw failure();
if (emitted > 64 * 1024) throw outputLimit();
text.accept(delta.asText());
} else if ("response.completed".equals(type)) {
Result result = result(item.path("response"), previousCalls);
@@ -451,93 +535,200 @@ public class ArkCadAiClient implements CadAiModelClient {
&& ("max_output_tokens".equals(reason) || "unknown".equals(reason)
&& outputTokens >= properties.getMaxOutputTokens()))
throw new BusinessException(502, "CAD_AI_OUTPUT_LIMIT", "CAD AI 模型输出达到上限,请分阶段生成,已完成的修改会保留");
throw failure();
if ("content_filter".equals(reason)) throw failure(ProviderFailure.REFUSAL);
throw upstreamFailure(item, type);
}
}
} else if (current.startsWith("data:")) {
if (!data.isEmpty()) data.append('\n');
data.append(current.substring(current.startsWith("data: ") ? 6 : 5));
if (data.length() > MAX_EVENT_CHARS) throw failure();
if (data.length() > MAX_EVENT_CHARS) throw outputLimit();
}
} else {
if (total == 1 && value == 0xFEFF) continue;
line.append((char) value);
if (line.length() > MAX_EVENT_CHARS) throw failure();
if (line.length() > MAX_EVENT_CHARS) throw outputLimit();
}
}
throw failure(true); // Network EOF or a truncated event is not a successful terminal event.
throw failure(ProviderFailure.INCOMPLETE); // Network EOF or a truncated event is not a successful terminal event.
}
}
/** A failed generation is not corrupt JSON. Never log the provider's free-form message. */
private BusinessException upstreamFailure(JsonNode event, String eventType) {
JsonNode error = event.path("response").path("error");
if (!error.isObject()) error = event.path("error");
if (!error.isObject() && "error".equals(eventType)) error = event;
String code = safeUpstreamCategory(error.path("code"));
String type = safeUpstreamCategory(error.path("type"));
Set<String> permanent = Set.of("context_length_exceeded", "invalid_prompt", "invalid_request_error",
"invalid_api_key", "authentication_error", "permission_denied", "permission_error",
"insufficient_quota", "model_not_found", "invalid_value", "unsupported_parameter",
"invalid_encrypted_content", "content_filter", "content_policy_violation");
boolean retryable = !permanent.contains(code) && !permanent.contains(type);
List<String> categories = List.of(code, type);
String message;
if (categories.contains("context_length_exceeded")) {
message = "模型服务提示上下文超过限制,请分段继续";
} else if (categories.contains("insufficient_quota")) {
message = "模型服务额度不足,请检查服务端配置";
} else if (!Collections.disjoint(categories, Set.of("invalid_api_key", "authentication_error", "permission_denied", "permission_error"))) {
message = "模型服务鉴权或权限校验失败,请检查服务端配置";
} else if (!Collections.disjoint(categories, Set.of("content_filter", "content_policy_violation"))) {
message = "模型服务拒绝了本次生成";
} else if (!Collections.disjoint(categories, Set.of("rate_limit_exceeded", "rate_limit_error", "too_many_requests"))) {
message = "模型服务请求受限,请稍后重试";
} else {
message = "模型服务返回生成失败";
}
// Unknown upstream failures use the browser's existing bounded recovery.
// No partial output is returned and Java never repeats the HTTP request.
log.warn("CAD AI 上游生成失败 eventType={} providerErrorCode={} providerErrorType={} errorPresent={} retryable={}",
eventType, code, type, error.isObject(), retryable);
return failure(ProviderFailure.UPSTREAM, retryable, message);
}
private String safeUpstreamCategory(JsonNode value) {
if (!value.isTextual() || value.asText().isBlank()) return "missing";
String category = value.asText();
return switch (category) {
case "server_error", "internal_error", "internal_server_error", "upstream_error", "service_unavailable",
"temporarily_unavailable", "timeout", "request_timeout", "rate_limit_exceeded", "rate_limit_error",
"too_many_requests", "context_length_exceeded", "invalid_prompt", "invalid_request_error",
"invalid_api_key", "authentication_error", "permission_denied", "permission_error",
"insufficient_quota", "model_not_found", "invalid_value", "unsupported_parameter",
"invalid_encrypted_content", "content_filter", "content_policy_violation" -> category;
default -> "other";
};
}
private Result result(JsonNode response, Set<String> previousCalls) {
if (!"completed".equals(response.path("status").asText()) || !response.path("output").isArray()
|| response.path("output").size() > 32) throw failure();
if (!"completed".equals(response.path("status").asText()) || !response.path("output").isArray()) throw failure();
if (response.path("output").size() > 32) throw outputLimit();
List<CadAiHistoryItem> output = new ArrayList<>();
List<CadAiReasoning> reasoning = new ArrayList<>();
Set<String> codes = new HashSet<>();
StringBuilder message = new StringBuilder();
boolean callsStarted = false;
int index = -1;
for (JsonNode item : response.path("output")) {
if (!"completed".equals(item.path("status").asText("completed"))) throw failure();
index++;
if (!item.isObject() || item.hasNonNull("status") && !"completed".equals(item.path("status").asText()))
throw malformedOutput("output_status", index, item);
switch (item.path("type").asText()) {
case "reasoning" -> {
// The browser retains encrypted state with the visible output for stateless tool continuations.
if (!item.path("id").isTextual() || !item.path("encrypted_content").isTextual()) throw failure();
if (!item.hasNonNull("encrypted_content")) break;
if (!item.path("id").isTextual() || !item.path("encrypted_content").isTextual()) throw failure(ProviderFailure.REASONING);
if (item.path("encrypted_content").asText().getBytes(StandardCharsets.UTF_8).length > CadAiProtocol.REASONING_BYTES)
throw outputLimit();
reasoning.add(new CadAiReasoning(item.path("id").asText(null), item.path("encrypted_content").asText(null)));
}
case "message" -> {
if (callsStarted || !"assistant".equals(item.path("role").asText()) || !item.path("content").isArray()) throw failure();
if (!"assistant".equals(item.path("role").asText()) || !item.path("content").isArray())
throw malformedOutput("message_shape", index, item);
for (JsonNode part : item.path("content")) {
if ("refusal".equals(part.path("type").asText())) throw failure(ProviderFailure.REFUSAL);
if (!"output_text".equals(part.path("type").asText()) || !part.path("text").isTextual()) throw failure();
message.append(part.path("text").asText());
}
}
case "function_call" -> {
if (!callsStarted && !message.isEmpty()) output.add(CadAiHistoryItem.message("assistant", List.of(CadAiContent.text(message.toString()))));
callsStarted = true;
String code = item.path("call_id").asText();
String name = item.path("name").asText();
String code = item.path("call_id").isTextual() ? item.path("call_id").asText() : null;
String name = item.path("name").isTextual() ? item.path("name").asText() : null;
if (!protocol.callCode(code) || previousCalls.contains(code) || !codes.add(code))
throw invalidModelTool(name, "call_code", "$.callCode");
if (codes.size() > 16) throw failure();
if (!item.path("arguments").isTextual()) throw invalidModelTool(name, "arguments_json", "$");
JsonNode arguments = modelArguments(name, item.path("arguments").asText());
if (codes.size() > 16) throw outputLimit();
JsonNode raw = item.get("arguments");
if (raw != null && !raw.isNull() && !raw.isTextual() && !raw.isObject()) throw invalidModelTool(name, "arguments_json", "$");
JsonNode arguments = raw != null && raw.isObject() ? raw.deepCopy() : modelArguments(name, raw == null ? null : raw.asText(""));
validateModelTool(name, arguments);
output.add(CadAiHistoryItem.call(code, name, arguments));
}
default -> throw failure();
// Unknown output may contain an unsupported operation. Reject the
// whole attempt, rather than silently dropping it or returning partial calls.
default -> throw malformedOutput("output_type", index, item);
}
}
if (message.length() > 64 * 1024) throw failure();
if (!callsStarted && !message.isEmpty()) output.add(CadAiHistoryItem.message("assistant", List.of(CadAiContent.text(message.toString()))));
if (message.length() > 64 * 1024) throw outputLimit();
// Native collects text and calls separately. Canonical history puts the
// combined text first and preserves relative order within both groups.
if (!message.isEmpty()) output.addFirst(CadAiHistoryItem.message("assistant", List.of(CadAiContent.text(message.toString()))));
if (output.isEmpty()) throw invalidModelTool(null, "output_empty", "$");
if (!reasoning.isEmpty()) {
try { protocol.validateReasoning(reasoning); }
catch (BusinessException error) { throw failure(); }
catch (BusinessException error) { throw failure(ProviderFailure.REASONING); }
output.set(0, output.getFirst().withReasoning(List.copyOf(reasoning)));
}
JsonNode usage = response.path("usage");
CadAiUsage tokens = usage.isObject() ? new CadAiUsage(token(usage, "input_tokens"), token(usage, "output_tokens"), token(usage, "total_tokens")) : null;
return new Result(List.copyOf(output), tokens);
return new Result(List.copyOf(output), usage(response.path("usage"), false));
}
private BusinessException malformedOutput(String rule, int index, JsonNode item) {
JsonNode type = item.path("type");
String category = switch (type.asText()) {
case "message", "function_call", "reasoning" -> type.asText();
default -> type.isMissingNode() ? "missing" : "other";
};
// Shape and a non-verbatim fingerprint identify extensions without logging
// model content, tool arguments, raw reasoning or untrusted type strings.
log.warn("CAD AI response shape rejected rule={} outputIndex={} nodeKind={} outputType={} typeFingerprint={}",
rule, index, item.getNodeType(), category, type.isTextual() ? Integer.toHexString(type.asText().hashCode()) : "none");
return failure();
}
private CadAiUsage usage(JsonNode value, boolean chat) {
if (value.isMissingNode() || value.isNull()) return null;
try {
if (!value.isObject()) throw new IllegalArgumentException();
return new CadAiUsage(token(value, chat ? "prompt_tokens" : "input_tokens"),
token(value, chat ? "completion_tokens" : "output_tokens"), token(value, "total_tokens"));
} catch (IllegalArgumentException error) {
// Optional accounting must not invalidate a complete, validated reply.
log.warn("CAD AI optional metadata discarded provider={} stage=response_parse reason=invalid_usage", properties.getProvider());
return null;
}
}
private long token(JsonNode usage, String name) {
JsonNode count = usage.path(name);
if (!count.isIntegralNumber() || !count.canConvertToLong() || count.longValue() < 0) throw failure();
if (count.isMissingNode() || count.isNull()) return 0;
if (!count.isIntegralNumber() || !count.canConvertToLong() || count.longValue() < 0) throw new IllegalArgumentException();
return count.longValue();
}
private JsonNode read(String source) {
try {
return json.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
JsonNode value = json.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
.with(JsonParser.Feature.STRICT_DUPLICATE_DETECTION).readTree(source);
} catch (IOException error) { throw failure(); }
if (value == null || !value.isObject()) throw failure(ProviderFailure.JSON);
return value;
} catch (IOException error) { throw failure(ProviderFailure.JSON); }
}
private static void close(InputStream stream) {
try { stream.close(); } catch (IOException ignored) { /* 取消时仍须继续释放其他资源。 */ }
}
private static boolean retryableTransportFailure(Throwable error) {
Set<Throwable> visited = Collections.newSetFromMap(new IdentityHashMap<>());
Throwable current = error;
boolean ioFailure = false;
boolean tlsFailure = false;
boolean badRecordTag = false;
while (current != null && visited.size() < 16 && visited.add(current)) {
if (current instanceof JsonProcessingException
|| current instanceof ProtocolException || current instanceof CertificateException
|| current instanceof SSLHandshakeException || current instanceof SSLPeerUnverifiedException)
return false;
ioFailure |= current instanceof IOException;
tlsFailure |= current instanceof SSLException;
badRecordTag |= current instanceof AEADBadTagException;
current = current.getCause();
}
// A rejected TLS record never becomes model output. A fresh, fully verified
// request may recover within the browser budget; trust/handshake failures may not.
return current == null && ioFailure && (!tlsFailure || badRecordTag);
}
static void logProviderException(Throwable error) {
List<String> types = new ArrayList<>();
Set<Throwable> visited = Collections.newSetFromMap(new IdentityHashMap<>());
@@ -552,13 +743,14 @@ public class ArkCadAiClient implements CadAiModelClient {
current = current.getCause();
}
// Never log messages or exception objects: they may contain credentials, URLs or request content.
// This traversal is diagnostic only; timeout and retry decisions retain their existing semantics.
// Diagnostics and retry classification both bound untrusted exception chains.
log.warn("CAD AI 上游响应异常 exceptionType={} rootExceptionType={} rootCategory={} causeChain={} transportSignal={} causeChainComplete={}",
error.getClass().getSimpleName(), deepest.getClass().getSimpleName(), safeFailureCategory(deepest),
String.join("->", types), transportSignal, current == null);
}
private static String safeFailureCategory(Throwable error) {
if (error instanceof AEADBadTagException) return "tls_record";
if (error instanceof SSLException) return "tls";
if (error instanceof HttpTimeoutException || error instanceof TimeoutException) return "timeout";
if (error instanceof ProtocolException) return "protocol";
@@ -571,6 +763,7 @@ public class ArkCadAiClient implements CadAiModelClient {
}
private static String safeTransportSignal(Throwable error) {
if (error instanceof AEADBadTagException) return "tls_record_authentication_failed";
String detail = error.getMessage();
if (detail == null) return "none";
String message = detail.substring(0, Math.min(detail.length(), 2048)).toLowerCase(Locale.ROOT);
@@ -581,14 +774,39 @@ public class ArkCadAiClient implements CadAiModelClient {
return "none";
}
private BusinessException failure() { return failure(false); }
private BusinessException failure() { return failure(ProviderFailure.RESPONSE); }
private BusinessException failure(boolean retryable) {
BusinessException error = new BusinessException(502, "CAD_AI_PROVIDER_FAILURE", "CAD AI 模型响应异常,请保留当前修改后重试",
retryable ? Map.of("retryable", true) : null);
private BusinessException outputLimit() {
log.warn("CAD AI response resource limit provider={} stage=response_parse reason=output_limit", properties.getProvider());
return new BusinessException(502, "CAD_AI_OUTPUT_LIMIT", "CAD AI 模型输出达到安全上限,请分阶段生成,已完成的修改会保留");
}
private BusinessException diagnose(CadAiChatRequest input, BusinessException error, long started) {
ProviderException diagnostic = error instanceof ProviderException provider ? provider : null;
log.warn("CAD AI 模型请求失败 requestId={} documentSessionCode={} turnCode={} provider={} stage={} reason={} httpStatus={} durationMs={}",
MDC.get("requestId"), input.documentSessionCode(), input.turnCode(), properties.getProvider(),
diagnostic == null ? "model_inference" : diagnostic.failure.stage,
diagnostic == null ? error.code() : diagnostic.failure.reason,
diagnostic == null ? null : diagnostic.httpStatus,
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started));
return error;
}
private BusinessException failure(ProviderFailure reason) {
return failure(reason, reason.retryable, reason.message);
}
private BusinessException failure(ProviderFailure reason, boolean retryable, String message) {
return failure(reason, retryable, message, null);
}
private BusinessException failure(ProviderFailure reason, boolean retryable, String message, Integer httpStatus) {
BusinessException error = new ProviderException(reason, retryable, message, httpStatus);
StackTraceElement[] trace = error.getStackTrace();
int caller = trace.length > 1 && "failure".equals(trace[1].getMethodName()) ? 2 : 1;
log.warn("CAD AI 模型响应失败 location={} retryable={}", trace.length > caller ? trace[caller] : null, retryable);
int caller = 1;
while (caller < trace.length && "failure".equals(trace[caller].getMethodName())) caller++;
log.warn("CAD AI 模型响应失败 provider={} stage={} reason={} location={} retryable={}",
properties.getProvider(), reason.stage, reason.reason, trace.length > caller ? trace[caller] : null, retryable);
return error;
}
@@ -207,6 +207,9 @@ public class CadAiService {
if ("CAD_AI_INVALID_MODEL_TOOL".equals(error.code())) {
correction = error.details() instanceof Map<?, ?> details && details.get("correction") instanceof CadAiRecovery value && value.valid()
? value : new CadAiRecovery("unknown", "invalid_tool", "$");
} else if (retryable && "CAD_AI_PROVIDER_FAILURE".equals(error.code()) && error.details() instanceof Map<?, ?> details
&& details.get("correction") instanceof CadAiRecovery value && value.valid()) {
correction = value;
}
log.warn("CAD AI 失败 requestId={} documentSessionCode={} turnCode={} cadProjectCode={} code={} retryable={} durationMs={}",
requestId, request.documentSessionCode(), request.turnCode(), request.cadProjectCode(), error.code(), retryable, elapsed());
@@ -17,16 +17,29 @@ import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ProtocolException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import javax.crypto.AEADBadTagException;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import org.junit.jupiter.api.*;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.util.ReflectionTestUtils;
class ArkCadAiClientTest {
private final ObjectMapper json = new ObjectMapper();
@@ -39,9 +52,12 @@ class ArkCadAiClientTest {
private CadAiProperties properties;
private AiProperties shared;
private volatile String response;
private volatile String responseContentType = "text/event-stream; charset=utf-8";
private volatile byte[] responseBytes;
private volatile int status;
private volatile boolean fragment;
private volatile boolean truncateBody;
private volatile boolean rejectImplicitReasoning;
private volatile CountDownLatch headersGate;
private volatile CountDownLatch bodyGate;
private final CountDownLatch bodyStarted = new CountDownLatch(1);
@@ -65,16 +81,19 @@ class ArkCadAiClientTest {
providerRequests.incrementAndGet();
received.set(json.readTree(exchange.getRequestBody()));
try {
boolean reject = rejectImplicitReasoning && !"none".equals(received.get().path("reasoning_effort").asText());
String reply = reject ? "{\"error\":{\"message\":\"reasoning_effort must be none PRIVATE_UPSTREAM_DETAIL\"}}" : response;
int replyStatus = reject ? 400 : status;
if (headersGate != null) headersGate.await(3, TimeUnit.SECONDS);
exchange.getResponseHeaders().set("Content-Type", "text/event-stream; charset=utf-8");
exchange.sendResponseHeaders(status, truncateBody ? response.getBytes(StandardCharsets.UTF_8).length + 16L : 0);
exchange.getResponseHeaders().set("Content-Type", responseContentType);
exchange.sendResponseHeaders(replyStatus, truncateBody ? reply.getBytes(StandardCharsets.UTF_8).length + 16L : 0);
if (bodyGate != null) {
exchange.getResponseBody().write(": heartbeat\n\n".getBytes(StandardCharsets.UTF_8));
exchange.getResponseBody().flush();
bodyStarted.countDown();
bodyGate.await(3, TimeUnit.SECONDS);
}
byte[] bytes = response.getBytes(StandardCharsets.UTF_8);
byte[] bytes = responseBytes == null ? reply.getBytes(StandardCharsets.UTF_8) : responseBytes;
if (fragment) {
for (int index = 0; index < bytes.length; index += 3) {
exchange.getResponseBody().write(bytes, index, Math.min(3, bytes.length - index));
@@ -346,10 +365,10 @@ class ArkCadAiClientTest {
response = completed("[{\"type\":\"reasoning\",\"id\":\"rs_1\",\"encrypted_content\":\"state\"}]");
assertFailure("CAD_AI_INVALID_MODEL_TOOL", true);
for (String output : List.of(
"[{\"type\":\"reasoning\",\"id\":\"rs_1\"}," + message + "]",
"[{\"type\":\"reasoning\",\"encrypted_content\":\"state\"}," + message + "]",
"[{\"type\":\"reasoning\",\"id\":\"rs_1\",\"encrypted_content\":123}," + message + "]")) {
response = completed(output);
assertFailure("CAD_AI_PROVIDER_FAILURE");
assertFailure("CAD_AI_PROVIDER_FAILURE", true);
}
}
@@ -366,16 +385,102 @@ class ArkCadAiClientTest {
assertThat(history.get(4).path("output").get(0).path("image_url").asText()).isEqualTo("data:image/png;base64,test-image");
}
@Test void rejectsCorruptUnknownAndRefusedOutputAsPermanentBeforeReturningTools() {
@Test void classifiesCorruptRefusedAndOversizedOutputBeforeReturningTools() {
String good = response;
for (String bad : List.of("data: {broken}\n\n",
good.replace("\"completed\"", "\"incomplete\""),
completed("[{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"refusal\",\"refusal\":\"拒绝\"}]}]"),
"data: {\"type\":\"response.failed\"}\n\n",
"data: " + "x".repeat(513 * 1024))) {
for (String bad : List.of("data: {broken}\n\n", good.replace("\"completed\"", "\"incomplete\""))) {
response = bad;
assertFailure("CAD_AI_PROVIDER_FAILURE", false);
assertFailure("CAD_AI_PROVIDER_FAILURE", true);
}
response = completed("[{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"refusal\",\"refusal\":\"拒绝\"}]}]");
assertFailure("CAD_AI_PROVIDER_FAILURE", false);
response = "data: " + "x".repeat(513 * 1024);
assertFailure("CAD_AI_OUTPUT_LIMIT", false);
}
@Test void malformedResponseMatrixRejectsTheWholeAttemptAndEnablesBoundedBrowserRecovery() {
String validCall = modelTool("valid", "inspect_design", "{}").toString();
for (String provider : List.of("openai", "doubao")) {
selectProvider(provider);
for (String malformed : List.of("null", "{}", "[]", "{\"type\":null}", "{\"type\":123}",
"{\"type\":\"PRIVATE_UNKNOWN_TYPE\",\"text\":\"PRIVATE_RESPONSE_BODY\"}",
"{\"type\":\"message\",\"role\":\"user\",\"content\":[]}",
"{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":12}]}",
"{\"type\":\"function_call\",\"status\":\"in_progress\"}")) {
response = completed("[" + validCall + "," + malformed + "]");
int before = providerRequests.get();
withProviderLogs(events -> {
assertFailure("CAD_AI_PROVIDER_FAILURE", true);
assertThat(events).allSatisfy(event -> assertThat(event.getFormattedMessage())
.doesNotContain("PRIVATE_UNKNOWN_TYPE", "PRIVATE_RESPONSE_BODY", "test-cad-key"));
});
assertThat(providerRequests.get()).isEqualTo(before + 1);
}
for (String malformed : List.of("data: \n\n", "data: null\n\n", "data: []\n\n", "data: {broken}\n\n",
"data: {\"type\":\"response.output_text.delta\",\"delta\":[]}\n\n",
"data: {\"type\":\"response.completed\",\"response\":null}\n\n")) {
response = malformed;
assertFailure("CAD_AI_PROVIDER_FAILURE", true);
}
}
}
@Test void normalizesInterleavedResponsesTextWithoutReorderingCalls() {
String text = "{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"%s\"}]}";
response = completed("[" + text.formatted("前") + "," + modelTool("first", "inspect_design", "{}")
+ "," + text.formatted("中") + "," + modelTool("second", "inspect_design", "{}") + "," + text.formatted("后") + "]");
CadAiModelClient.Result result = call();
assertThat(result.output()).extracting(CadAiHistoryItem::type).containsExactly("message", "toolCall", "toolCall");
assertThat(result.output().getFirst().content().getFirst().text()).isEqualTo("前中后");
assertThat(result.output().subList(1, 3)).extracting(CadAiHistoryItem::callCode).containsExactly("first", "second");
}
@Test void malformedOptionalUsageNeverInvalidatesConfirmedContentInEitherProtocol() {
for (String provider : List.of("openai", "deepseek")) {
selectProvider(provider);
for (String usage : List.of("null", "[]", "\"PRIVATE_METADATA\"", "{\"total_tokens\":-1}",
"{\"total_tokens\":1.5}", "{\"total_tokens\":\"30\"}", "{\"total_tokens\":9223372036854775808}")) {
if ("openai".equals(provider)) response = completed("[{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Done\"}]}]")
.replace("{\"input_tokens\":10,\"output_tokens\":20,\"total_tokens\":30}", usage);
else response = chatEvent("{\"content\":\"Done\"}", "stop") + "data: {\"choices\":[],\"usage\":" + usage + "}\n\ndata: [DONE]\n\n";
CadAiModelClient.Result result = call();
assertThat(result.output().getFirst().content().getFirst().text()).isEqualTo("Done");
assertThat(result.usage()).isNull();
}
}
}
@Test void unexpectedHeadersAndMalformedEncodingRecoverWithoutWeakeningTlsOrReturningTools() {
for (String provider : List.of("openai", "doubao", "deepseek")) {
selectProvider(provider);
responseContentType = "application/json";
int before = providerRequests.get();
assertFailure("CAD_AI_PROVIDER_FAILURE", true);
assertThat(providerRequests.get()).isEqualTo(before + 1);
responseContentType = "text/event-stream";
responseBytes = new byte[] {'d', 'a', 't', 'a', ':', ' ', (byte) 0xc3, (byte) 0x28, '\n', '\n'};
assertFailure("CAD_AI_PROVIDER_FAILURE", true);
responseBytes = null;
}
}
@Test void chatMalformedGenerationAndOptionalMetadataFollowTheSameRecoveryPolicy() {
selectProvider("deepseek");
for (String malformed : List.of("data: {broken}\n\n", "data: null\n\n", "data: {\"choices\":{}}\n\n",
"data: {\"choices\":[{\"index\":0,\"delta\":12}]}\n\n",
chatEvent("{\"content\":[]}", "stop"), chatEvent("{}", "unknown"))) {
response = malformed + "data: [DONE]\n\n";
assertFailure("CAD_AI_PROVIDER_FAILURE", true);
}
response = "data: {\"choices\":[{\"index\":0,\"finish_reason\":\"stop\"}]}\n\n";
response = chatEvent("{\"content\":\"Done\"}", null) + response + "data: [DONE]\n\n";
assertThat(call().output().getFirst().content().getFirst().text()).isEqualTo("Done");
response = chatEvent("{\"tool_calls\":[{\"index\":0,\"id\":\"same\",\"function\":{\"name\":\"inspect_design\",\"arguments\":\"{\"}}]}", null)
+ chatEvent("{\"tool_calls\":[{\"index\":0,\"id\":\"same\",\"function\":{\"arguments\":\"}\"}}]}", "tool_calls") + "data: [DONE]\n\n";
assertThat(call().output().getFirst().callCode()).isEqualTo("same");
response = "data: {\"error\":{\"code\":\"invalid_api_key\",\"message\":\"PRIVATE_RESPONSE_BODY\"}}\n\n";
assertFailure("CAD_AI_PROVIDER_FAILURE", false);
response = "data: {\"error\":{\"code\":\"server_error\"}}\n\n";
assertFailure("CAD_AI_PROVIDER_FAILURE", true);
}
@Test void marksIncompleteResponsesStreamsAsRetryableWithoutRetryingProvider() {
@@ -490,7 +595,7 @@ class ArkCadAiClientTest {
ArrayNode overLimit = json.createArrayNode();
for (int index = 0; index < 17; index++) overLimit.add(modelTool("tool_" + index, "inspect_design", "{}"));
response = completed(overLimit.toString());
assertFailure("CAD_AI_PROVIDER_FAILURE", false);
assertFailure("CAD_AI_OUTPUT_LIMIT", false);
selectProvider("deepseek");
for (String invalid : List.of(chatEvent("{}", "stop"), chatEvent("{}", "tool_calls"),
@@ -505,7 +610,7 @@ class ArkCadAiClientTest {
response = chatEvent("{\"content\":\"refused\"}", "content_filter") + "data: [DONE]\n\n";
assertFailure("CAD_AI_PROVIDER_FAILURE", false);
response = modelToolsResponse("deepseek", overLimit);
assertFailure("CAD_AI_PROVIDER_FAILURE", false);
assertFailure("CAD_AI_OUTPUT_LIMIT", false);
}
@Test void addsRecoveryGuidanceWithoutDroppingHistoryReasoningImagesOrModelSettings() {
@@ -586,11 +691,162 @@ class ArkCadAiClientTest {
for (int statusCode : List.of(400, 401, 403, 408, 429, 500, 502, 503, 504, 599)) {
int before = providerRequests.get();
status = statusCode;
assertFailure("CAD_AI_PROVIDER_FAILURE", statusCode == 408 || statusCode >= 500);
assertFailure("CAD_AI_PROVIDER_FAILURE", statusCode == 408 || statusCode == 429 || statusCode >= 500);
assertThat(providerRequests.get()).isEqualTo(before + 1);
}
}
@Test void classifiesFailedGenerationsAsRetryableWithoutReturningPartialToolsOrRetryingProvider() {
for (String terminal : List.of(
"{\"type\":\"response.failed\",\"response\":{\"status\":\"failed\",\"error\":{\"code\":\"server_error\",\"message\":\"PRIVATE_UPSTREAM_DETAIL\"},"
+ "\"output\":[{\"type\":\"function_call\",\"call_id\":\"partial_call\",\"name\":\"inspect_design\",\"arguments\":\"{}\"}]}}",
"{\"type\":\"error\",\"code\":\"rate_limit_exceeded\",\"message\":\"PRIVATE_UPSTREAM_DETAIL\"}",
"{\"type\":\"error\",\"error\":{\"type\":\"timeout\",\"message\":\"PRIVATE_UPSTREAM_DETAIL\"}}",
"{\"type\":\"response.failed\"}",
"{\"type\":\"response.incomplete\",\"response\":{\"incomplete_details\":{\"reason\":\"unknown\"}}}")) {
int before = providerRequests.get();
response = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"temporary\"}\n\n"
+ "data: " + terminal + "\n\n";
List<String> previews = new ArrayList<>();
assertThatThrownBy(() -> client.complete(request(), previews::add, new CadAiCancellation()))
.isInstanceOfSatisfying(BusinessException.class, error -> {
assertThat(error.code()).isEqualTo("CAD_AI_PROVIDER_FAILURE");
assertThat(error.details()).isEqualTo(Map.of("retryable", true));
assertThat(error.getMessage()).contains("模型服务").doesNotContain("格式", "PRIVATE_UPSTREAM_DETAIL");
});
assertThat(previews).containsExactly("temporary");
assertThat(providerRequests.get()).isEqualTo(before + 1);
}
}
@Test void failedGenerationsWithPermanentCodesKeepAccurateMessagesAndNeverRetry() {
Map<String, String> expected = Map.of(
"context_length_exceeded", "上下文超过限制",
"insufficient_quota", "额度不足",
"authentication_error", "鉴权或权限",
"permission_denied", "鉴权或权限",
"invalid_request_error", "生成失败",
"content_policy_violation", "拒绝");
for (Map.Entry<String, String> category : expected.entrySet()) {
for (String field : List.of("code", "type")) {
int before = providerRequests.get();
response = "data: {\"type\":\"response.failed\",\"response\":{\"status\":\"failed\",\"error\":{\""
+ field + "\":\"" + category.getKey() + "\",\"message\":\"PRIVATE_UPSTREAM_DETAIL\"}}}\n\n";
assertThatThrownBy(this::call).isInstanceOfSatisfying(BusinessException.class, error -> {
assertThat(error.code()).isEqualTo("CAD_AI_PROVIDER_FAILURE");
assertThat(error.details()).isNull();
assertThat(error.getMessage()).contains(category.getValue()).doesNotContain("格式", "PRIVATE_UPSTREAM_DETAIL");
});
assertThat(providerRequests.get()).isEqualTo(before + 1);
}
}
}
@Test void logsOnlyWhitelistedFailedGenerationCategoriesAndCorrelatedDiagnostics() {
String secret = "PRIVATE_UPSTREAM_DETAIL sk-secret-private https://user:password@example.invalid/?token=private";
for (String category : List.of("server_error", secret)) {
ObjectNode event = json.createObjectNode().put("type", "response.failed");
event.putObject("response").put("status", "failed").putObject("error")
.put("code", category).put("type", category).put("message", secret);
response = "data: " + event + "\n\n";
withProviderLogs(events -> {
assertFailure("CAD_AI_PROVIDER_FAILURE", true);
String safe = "server_error".equals(category) ? "server_error" : "other";
assertThat(events.stream().map(ILoggingEvent::getFormattedMessage)
.filter(message -> message.contains("上游生成失败")).toList()).singleElement()
.asString().contains("eventType=response.failed", "providerErrorCode=" + safe,
"providerErrorType=" + safe, "errorPresent=true", "retryable=true");
assertThat(events.stream().map(ILoggingEvent::getFormattedMessage)
.filter(message -> message.contains("模型请求失败")).toList()).singleElement()
.asString().contains("documentSessionCode=doc", "turnCode=turn", "provider=doubao",
"stage=upstream_terminal", "reason=generation_failed", "durationMs=");
assertThat(events).allSatisfy(eventLog -> {
assertThat(eventLog.getFormattedMessage()).doesNotContain("PRIVATE_UPSTREAM_DETAIL", "sk-secret-private",
"password", "example.invalid", "token=private", "test-cad-key");
assertThat(eventLog.getThrowableProxy()).isNull();
});
});
}
}
@Test void nativeEmptyArgumentsAreValidatedAsObjectsWithoutAcceptingCorruptJson() {
for (String arguments : List.of("", "\"arguments\":null,", "\"arguments\":\" \",", "\"arguments\":{},")) {
response = completed("[{\"type\":\"function_call\",\"call_id\":\"empty_args\",\"name\":\"inspect_design\","
+ arguments + "\"status\":\"completed\"}]");
assertThat(call().output().getFirst().arguments()).isEqualTo(json.createObjectNode());
}
selectProvider("deepseek");
response = chatEvent("{\"tool_calls\":[{\"index\":0,\"id\":\"empty_args\",\"function\":{\"name\":\"inspect_design\",\"arguments\":\" \"}}]}", "tool_calls")
+ "data: [DONE]\n\n";
assertThat(call().output().getFirst().arguments()).isEqualTo(json.createObjectNode());
}
@Test void optionalReasoningAndUsageMetadataDoNotDiscardValidResponses() {
response = completed("[{\"type\":\"reasoning\",\"id\":\"rs_summary\",\"summary\":[]},"
+ "{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Done\"}]}]")
.replace("\"input_tokens\":10,\"output_tokens\":20,\"total_tokens\":30", "\"output_tokens\":20");
CadAiModelClient.Result result = call();
assertThat(result.output().getFirst().reasoning()).isNull();
assertThat(result.output().getFirst().content().getFirst().text()).isEqualTo("Done");
assertThat(result.usage()).isEqualTo(new CadAiUsage(0, 20, 0));
response = response.replace("\"output_tokens\":20", "\"output_tokens\":-1");
assertThat(call().usage()).isNull();
selectProvider("deepseek");
response = chatEvent("{\"content\":\"Done\",\"refusal\":\" \"}", "stop").replace("\"index\":0,", "") + "data: [DONE]\n\n";
assertThat(call().output().getFirst().content().getFirst().text()).isEqualTo("Done");
response = response.replace("\"delta\":", "\"index\":4294967296,\"delta\":");
assertFailure("CAD_AI_PROVIDER_FAILURE", true);
}
@Test void nativeReasoningCompatibilityRetryNeverChangesExplicitEffortOrResponsesProtocol() {
rejectImplicitReasoning = true;
int before = providerRequests.get();
assertFailure("CAD_AI_PROVIDER_FAILURE", false);
assertThat(providerRequests.get()).isEqualTo(before + 1);
selectProvider("deepseek");
properties.activeProvider().setReasoningEffort("high");
before = providerRequests.get();
assertFailure("CAD_AI_PROVIDER_FAILURE", false);
assertThat(providerRequests.get()).isEqualTo(before + 1);
properties.activeProvider().setReasoningEffort("default");
response = chatEvent("{\"content\":\"Compatible\"}", "stop") + "data: [DONE]\n\n";
before = providerRequests.get();
assertThat(call().output().getFirst().content().getFirst().text()).isEqualTo("Compatible");
assertThat(providerRequests.get()).isEqualTo(before + 2);
assertThat(received.get().path("reasoning_effort").asText()).isEqualTo("none");
assertThat(properties.activeProvider().getReasoningEffort()).isEqualTo("default");
}
@Test void providerFailureMessagesDistinguishHttpRefusalJsonAndStreamWithoutRawDetails() {
selectProvider("deepseek");
status = 400;
response = "";
assertThatThrownBy(this::call).isInstanceOfSatisfying(BusinessException.class,
error -> assertThat(error.getMessage()).contains("HTTP 400"));
assertThat(providerRequests.get()).isEqualTo(1);
selectProvider("doubao");
status = 401;
withProviderLogs(events -> {
assertThatThrownBy(this::call).isInstanceOfSatisfying(BusinessException.class,
error -> assertThat(error.getMessage()).contains("HTTP 401").doesNotContain("PRIVATE_UPSTREAM_DETAIL"));
assertThat(events.stream().map(ILoggingEvent::getFormattedMessage)
.filter(message -> message.contains("模型请求失败")).toList()).singleElement()
.asString().contains("documentSessionCode=doc", "turnCode=turn", "provider=doubao",
"stage=response_headers", "reason=http_rejected", "httpStatus=401", "durationMs=")
.doesNotContain("PRIVATE_UPSTREAM_DETAIL", "test-cad-key");
});
status = 200;
response = "data: {broken}\n\n";
assertThatThrownBy(this::call).isInstanceOfSatisfying(BusinessException.class,
error -> assertThat(error.getMessage()).contains("JSON"));
response = completed("[{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"refusal\",\"refusal\":\"PRIVATE_UPSTREAM_DETAIL\"}]}]");
assertThatThrownBy(this::call).isInstanceOfSatisfying(BusinessException.class,
error -> assertThat(error.getMessage()).contains("拒绝").doesNotContain("PRIVATE_UPSTREAM_DETAIL"));
response = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"unfinished\"}\n\n";
assertThatThrownBy(this::call).isInstanceOfSatisfying(BusinessException.class,
error -> assertThat(error.getMessage()).contains("中断"));
}
@Test void classifiesTruncatedNetworkBodyAsRetryableWithoutRetryingProvider() {
truncateBody = true;
response = ": heartbeat\n\n";
@@ -643,6 +899,47 @@ class ArkCadAiClientTest {
});
}
@Test void recoversTlsRecordFailuresButNeverRetriesCertificateOrHandshakeFailures() {
record FailureCase(Throwable error, boolean retryable) {}
SSLHandshakeException handshake = new SSLHandshakeException("PRIVATE_TLS_DETAIL");
handshake.initCause(new AEADBadTagException("PRIVATE_TLS_DETAIL"));
IOException cycle = new IOException("PRIVATE_TLS_DETAIL");
cycle.initCause(new IOException("PRIVATE_TLS_DETAIL", cycle));
Throwable deep = new IOException("PRIVATE_TLS_DETAIL");
for (int index = 0; index < 17; index++) deep = new CompletionException(deep);
for (FailureCase sample : List.of(
new FailureCase(new SSLException("PRIVATE_TLS_DETAIL", new AEADBadTagException("PRIVATE_TLS_DETAIL")), true),
new FailureCase(new CompletionException(new SSLException("PRIVATE_TLS_DETAIL",
new AEADBadTagException("PRIVATE_TLS_DETAIL"))), true),
new FailureCase(handshake, false),
new FailureCase(new SSLPeerUnverifiedException("PRIVATE_TLS_DETAIL"), false),
new FailureCase(new SSLException("PRIVATE_TLS_DETAIL", new CertificateException("PRIVATE_TLS_DETAIL")), false),
new FailureCase(new SSLException("PRIVATE_TLS_DETAIL"), false),
new FailureCase(new CompletionException(new IOException("PRIVATE_TLS_DETAIL")), true),
new FailureCase(new IOException(new CharacterCodingException()), true),
new FailureCase(new ProtocolException("PRIVATE_TLS_DETAIL"), false),
new FailureCase(cycle, false), new FailureCase(deep, false))) {
HttpClient transport = Mockito.mock(HttpClient.class);
CompletableFuture<HttpResponse<InputStream>> failed = CompletableFuture.failedFuture(sample.error());
Mockito.when(transport.sendAsync(ArgumentMatchers.any(HttpRequest.class),
ArgumentMatchers.<HttpResponse.BodyHandler<InputStream>>any())).thenReturn(failed);
ReflectionTestUtils.setField(client, "http", transport);
withProviderLogs(events -> {
assertFailure("CAD_AI_PROVIDER_FAILURE", sample.retryable());
assertThat(events).allSatisfy(event -> {
assertThat(event.getFormattedMessage()).doesNotContain("PRIVATE_TLS_DETAIL", "test-cad-key");
assertThat(event.getThrowableProxy()).isNull();
});
if (sample.retryable() && sample.error() instanceof SSLException)
assertThat(events).anySatisfy(event -> assertThat(event.getFormattedMessage())
.contains("rootCategory=tls_record", "transportSignal=tls_record_authentication_failed"));
});
Mockito.verify(transport, Mockito.times(1)).sendAsync(ArgumentMatchers.any(HttpRequest.class),
ArgumentMatchers.<HttpResponse.BodyHandler<InputStream>>any());
assertThat(providerRequests.get()).isZero();
}
}
@Test void connectionFailureLogsRootAndPreservesExistingRetryability() {
server.stop(0);
withProviderLogs(events -> {