From 58a98d3c949896e72f8c305ee631623eb812966a Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sun, 26 Jul 2026 23:12:57 +0800 Subject: [PATCH] docs(reports): record the source audit, fix queue, and R1/R2 results Adds the 2026-07-26 full-source audit and the execution-ordered fix queue, and records what actually happened when R1 and R2 were verified: - R1 had never been compiled. The gate found a type error introduced by its own `.nullish()` widening and a lint failure from a non-component export, plus one acceptance test that was specified but never written. - R2 landed F-10 through F-13, and an adversarial review of it surfaced three defects the batch had itself introduced, all fixed in the same batch. - The review subagents ran against the live working tree and left mutations behind, including a deliberate duplicate POST inside the stream error path. That injected code was briefly mistaken for a real HTTP-stack defect. It has been removed and the process note recorded so review runs are isolated next time. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 33 +++ docs/progress.md | 117 +++++++- docs/reports/fix-queue-2026-07-26.md | 253 ++++++++++++++++ docs/reports/full-source-audit-2026-07-26.md | 289 +++++++++++++++++++ 4 files changed, 691 insertions(+), 1 deletion(-) create mode 100644 docs/reports/fix-queue-2026-07-26.md create mode 100644 docs/reports/full-source-audit-2026-07-26.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 7035013..61929f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,24 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and ## [Unreleased] +### Fixed + +- Long-lived event streams are no longer killed by a total request timeout. Streaming endpoints now + use a separate HTTP client with idle-based `read_timeout` detection, so a desktop-v1 connection + survives past 30 seconds and an AstrBot reply may take longer than two minutes. +- Chinese and other multi-byte text no longer turns into replacement characters when a character + straddles two network chunks; the SSE stream is now split into lines at the byte level. +- A chat message is no longer resent after AstrBot has started answering it, which previously + duplicated both the question and the answer in the remote conversation. A stream that breaks + mid-reply now reports a distinct error so it can be retried manually. +- A long reply no longer makes the rest of its slot report "not connected" while it streams, so + attachments, session lists, and capability lookups keep working during generation. +- Stopping generation, or losing the stream mid-reply, now finalizes the message. It could + previously stay marked as generating, including after a restart. +- Stopping generation no longer flickers the connection status to disconnected and back. +- Corrected a session-timestamp type and moved a link-safety helper out of a component module, both + of which broke the type and lint gates for the previous batch. + ### Changed - Synchronized the 13-item roadmap status with the actual P02 implementation state. @@ -60,6 +78,21 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and - Runtime operations switch guard that blocks operations slot changes while an operations task is active. - Duplicate `server_instance_id` warnings without silently merging Profiles. +### Fixed + +- Scoped AstrBot stream event ids per chat request so the second and later messages on a + connection are no longer discarded by the client-side event deduplicator. +- Accepted Rust `null` values in the runtime-event, remote-session, and model-option + frontend contracts, restoring streaming events, remote session lists, and file upload. +- Serialized AstrBot model options in camelCase to match the frontend contract. +- Allowed `blob:` images in the production Content Security Policy so chat attachments + render in release builds. +- Granted the desktop pet window a Tauri capability so its IPC and event listeners work. +- Corrected the pet pack manifest image pattern, which previously rejected every valid pack. +- Restricted rendered markdown links to http, https, and mailto and added `rel="noopener"`. +- Replaced `[object Object]` IPC error text with the message returned by Rust. +- Restored corrupted user-facing strings and an accessibility label in the pet view and shell. + ### Security - Kept credentials and native capabilities in Rust; the React capability set remains `core:default` only. diff --git a/docs/progress.md b/docs/progress.md index 04cdc5d..89c4ab6 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -344,7 +344,7 @@ Still not claimed complete: automatic startup activation, real Tauri multi-windo - Added `tests/e2e/ui-polish.spec.ts` for desktop shell overflow checks at 1280px, 1024px, and 680px plus diagnostic keyboard accessibility. - Completed P3 polish pass for desktop shell hierarchy, status messaging, profile credentials, diagnostics, desktop pet boundary, empty/error/loading states, and dark/light token usage without adding marketing-style animation. - Validation: targeted Prettier, ESLint, TypeScript, Vitest 6/6, Vite production build, Playwright 5/5, Rust fmt, Clippy with warnings denied, Rust workspace tests (67), and Rust workspace check all passed. -- Known non-blocking warnings: Node is `24.14.0` while the package requires `>=24.17.0`; Vite reports the intentional lazy `DesktopPetView` chunk above 500 kB. +- Known non-blocking warnings: Node is `24.14.0` while the package requires `>=24.17.0`; Vite reports the intentional lazy `DesktopPetView` chunk above 500 kB. ## 2026-07-21: roadmap completion audit @@ -386,3 +386,118 @@ Run the full stage gate, refresh the local acceptance checklist, then create the - Rust fmt, Clippy with warnings denied, workspace tests (67), and workspace check: passed. - Tauri release build and unsigned NSIS bundle: passed. - Full repository Prettier remains blocked by 20 pre-existing unformatted files; no broad reformat was applied. + +## 2026-07-26: full source audit and R1 release-blocker fixes + +- Completed a full-repository static audit (146 files, ~24k lines) covering the Rust + networking/runtime layer, the data and credential layer, the protocol crates and mock + gateway, and the frontend plus build configuration. +- Recorded the findings in `docs/reports/full-source-audit-2026-07-26.md` + (P0 x 1, P1 x 18, P2 x 31, P3 x 18) and the execution-ordered remediation plan in + `docs/reports/fix-queue-2026-07-26.md` (68 items across 8 batches). +- Applied batch R1 (release blockers), 9 items: + - Scoped AstrBot stream event ids per request (`stream_id`), fixing the P0 where every + event of the second and later messages on one connection was discarded as a duplicate. + - Corrected the pet pack manifest image pattern, which rejected every valid pack. + - Granted the `desktop-pet` window a capability so its IPC and event listeners work. + - Allowed `blob:` images in the production CSP so chat attachments render in release builds. + - Restricted markdown link protocols to http/https/mailto and added `rel="noopener"`. + - Accepted Rust `null` in the runtime-event, remote-session, and model-option contracts. + - Serialized `AstrBotModelOption` as camelCase to match the frontend contract. + - Added a shared `errorMessage()` helper so IPC failures no longer render `[object Object]`. + - Restored six corrupted user-facing strings and one corrupted `aria-label`. +- Added regression coverage: `consecutive_streams_do_not_reuse_event_ids` (Rust), + three null-contract cases in `src/features/chat/types.test.ts`, and a new + `src/features/pet/types.test.ts` that parses the bundled manifest. +- Validation status: NOT yet run. The session that produced these changes had no package + registry access and could not compile or test. The full stage gate (fmt, clippy, cargo + test, typecheck, lint, vitest, build) still has to be run on Windows before this batch is + considered accepted. +- Next: batch R2 (transport layer) per the fix queue. R2 depends on R1's F-01 because both + touch the same stream loop in `astrbot_client.rs`. + +## 2026-07-26: R1 gate verification + +Ran the full stage gate against R1 for the first time. Two failures, both compile-time +consequences of R1's own edits, and both fixed: + +- `npm run typecheck` — `TS2345` at `ChatPanel.tsx:707`. F-06 widened `remoteChatSession.updatedAt` + to `.nullish()`, so `string | null` reached `formatSessionTime(value?: string)`. Widened the + parameter to `string | null`; its existing falsy guard already handled `null`. +- `npm run lint` — `react-refresh/only-export-components` on `safeLinkHref`, which F-05 added as a + non-component export inside `MessageContent.tsx`. With `--max-warnings 0` this fails the gate. + Moved the helper to `src/lib/safeLinkHref.ts`. + +Also added `src/features/chat/MessageContent.test.tsx`. F-05 listed a `javascript:` link unit test +as its acceptance criterion but the test was never written. + +Gate result after the fixes: fmt, clippy (`-D warnings`), `cargo test --workspace` (67 lib tests, +including `consecutive_streams_do_not_reuse_event_ids`), typecheck, lint, Vitest (19 tests across +4 files), and the production build all pass. + +## 2026-07-26: R2 transport-layer batch + +All four items landed; the batch is serial because every item touches the same stream loop. + +- **F-10** Split each client into a REST client that keeps a total deadline and a streaming client + that has none. `reqwest::Client::timeout` counts from the start of the request until the body has + finished and keeps running while `bytes_stream()` is consumed, so the 30s desktop-v1 budget tore + the long-lived SSE connection down every 30 seconds regardless of heartbeats, and the 120s AstrBot + budget cut off any generation longer than two minutes. Both streaming clients now use + `read_timeout` (90s desktop-v1, 120s AstrBot), which resets after every successful read, plus a + 60s TCP keepalive. +- **F-11** Replaced the per-chunk `String::from_utf8_lossy` with an `SseLineBuffer` that buffers raw + bytes and only decodes complete `\n`-delimited lines. TCP chunk boundaries fall on arbitrary byte + offsets, so any CJK character straddling two chunks previously became `U+FFFD` and was persisted + that way. +- **F-12** Narrowed `should_retry_astrbot` to connect-phase failures only. `POST /api/v1/chat` has + no idempotency key, so resending after the server had already accepted the request duplicated the + question and the answer in the remote conversation and interleaved two attempts' deltas. Failures + after the response starts now surface a `streamInterrupted` code for a user-driven retry. +- **F-13** Every exit path from the stream loop — cancellation, chunk error, mapper error, line + overflow — now calls `finish_stream_with(Cancelled | Error)` and dispatches, so a half-streamed + message can no longer stay `streaming = 1` and reappear as "generating" after a restart. + Folded in F-56 (P3-4) while rewriting that line: cancelling no longer flips the connection to + `Disconnected` and back, which was a visible tray/badge flicker. + +Regression coverage added (6 Rust tests, workspace total 67 -> 73). The three transport tests drive +a real `AstrBotClient` against a hand-rolled HTTP/1.1 chunked-SSE server built on a raw +`TcpListener`, because byte-exact control over chunk boundaries and the ability to drop a socket +mid-body without the terminal chunk are not expressible through an HTTP framework. The UTF-8 test +was verified to genuinely fail against the previous decoding (it reproduced three replacement +characters in place of the leading CJK character), so it is a real regression guard rather than a +tautology. + +Gate result: fmt, clippy (`-D warnings`), `cargo test --workspace` (73), typecheck, lint, Vitest +(19), and the production build all pass. + +### Follow-up work pulled into R2 after review + +An adversarial review of the batch surfaced three defects that R2 itself had caused, all fixed here: + +- Removing the streaming total timeout also removed the only bound on a response. `read_timeout` + cannot replace it — it measures the gap between reads, so a server trickling bytes forever keeps + the stream alive while the line buffer and the mapper's accumulated text grow without limit. + Added a 64 MiB per-response ceiling. +- `send_slot_message` took the client out of the slot for the duration of a send, which makes the + other five slot commands report "not connected". That window used to be capped at 120s by the + client's total timeout; without it, an ordinary long reply would disable the rest of the slot for + minutes. Switched to cloning the client and serializing sends on `message_cancellation` + (this is F-49 from batch R7, pulled forward because R2 is what made it user-visible). +- `SseLineBuffer` consumed lines by draining from the front, which memmoves the remainder once per + line and is quadratic in the chunk size; hyper can hand over several hundred KiB of short delta + frames in a single item. Replaced with a cursor, compacted once per chunk. + +### Process note on the review tooling + +The adversarial review ran subagents against the live working tree, and two of them left mutations +and repro modules behind instead of reverting: an explicit second `POST /api/v1/chat` inside the +error arm of `send_chat_stream`, labelled as a temporary mutation, plus throwaway test modules in +`astrbot_client.rs`, `runtime.rs`, and `src-tauri/tests/`. The injected POST was mistaken for a +real defect in the HTTP stack and briefly recorded as such; bisecting it down to the exact injected +lines is what identified the real cause. All injected code has been removed and the affected +commits rewritten. Future review passes must run read-only or in an isolated worktree. + +- Not covered by this batch, still open from P1-2's description: `commands.rs` persists the user + message row before the send is validated (F-18, batch R3), so a failed send still leaves a row. +- Next: batch R3 (isolation and state correctness). diff --git a/docs/reports/fix-queue-2026-07-26.md b/docs/reports/fix-queue-2026-07-26.md new file mode 100644 index 0000000..7fffe3c --- /dev/null +++ b/docs/reports/fix-queue-2026-07-26.md @@ -0,0 +1,253 @@ +# AstrBot Desktop 修复队列 + +基于 2026-07-26 全源码审计 · 共 68 项 · 8 个批次 + +> 配套审计档案:[full-source-audit-2026-07-26.md](./full-source-audit-2026-07-26.md)。 +> 本文中的 `P0-1` / `P1-7` 等编号均指向该档案中的对应发现。 + +## 执行状态(2026-07-26 更新) + +| 批次 | 状态 | 说明 | +|---|---|---| +| R1 发布阻断批 | **已完成,门槛已验证** | 9 项全部实现。2026-07-26 首次跑完整门槛,发现 2 处编译/lint 失败并修复(详见下方「R1 门槛验证结果」),补写 F-05 缺失的单测。现全绿。 | +| R2 传输层批 | **已完成,门槛已验证** | F-10 – F-13 全部实现,新增 6 条 Rust 测试(workspace 67 → 73)。顺带并入 F-56(P3-4,取消不再置 Disconnected)。全绿。 | +| R3 – R8 | 未开始 | 下一批为 R3。依赖关系见文末批次依赖图。 | + +### R1 门槛验证结果(2026-07-26) + +首次编译暴露 2 处失败,均为 R1 自身改动的直接后果: + +1. `npm run typecheck` —— `ChatPanel.tsx:707` `TS2345`。F-06 把 `updatedAt` 放宽为 `.nullish()` 后, + `string | null` 传进了 `formatSessionTime(value?: string)`。已把形参放宽为 `string | null` + (函数原有的 falsy 判断本就覆盖 `null`)。**这正是本文档第 4 条预警的 `.nullish()` 向下游传播。** +2. `npm run lint` —— `react-refresh/only-export-components`。F-05 把 `safeLinkHref` 作为非组件导出 + 放进了 `MessageContent.tsx`;仓库用 `--max-warnings 0`,warning 即失败。 + 已移到 `src/lib/safeLinkHref.ts`。 + +另:F-05 的验收条件写了 `[x](javascript:alert(1))` 单测,但该测试从未写过,已补 +`src/features/chat/MessageContent.test.tsx`(4 例)。 + +预警清单中的另两项(`astrbot.rs` 新测试闭包借用、`errorMessage()` 10 个接入点类型)实测无问题。 + +### R2 实现记录(2026-07-26) + +- **F-10** 两个 client 拆分落在 `astrbot_client.rs` 与 `gateway_client.rs`:REST 保留总时限 + (120s / 30s),流式端点改 `read_timeout`(AstrBot 120s、desktop-v1 90s)+ `tcp_keepalive(60s)`, + 不设 `.timeout()`。已从 vendored reqwest 0.13.4 源码确认 `read_timeout` 语义为「每次读成功后重置」。 +- **F-11** 新增 `SseLineBuffer`(`Vec` 缓冲、按 `\n` 字节分行、逐行解码、1MiB 单行上限)。 +- **F-12** `should_retry_astrbot` 收窄为 `reqwest::Error::is_connect()` 唯一可重试;新增 + `AstrBotClientError::StreamInterrupted` 变体标记「响应已开始后断流」,并经 `astrbot_send_error()` + 映射为前端可见的 `streamInterrupted` 错误码。 +- **F-13** 取消 / chunk 错误 / mapper 错误 / 行溢出四条路径统一走 `finish_stream_with()` + (`Cancelled` / `Error`)并 dispatch;协议 crate 新增 `AstrBotStreamMapper::finish_stream_with()`。 + 顺带并入 **F-56**(R8·P3-4):取消不再把连接置 `Disconnected` 再置回。 +- 测试基建说明:三条传输测试用裸 `TcpListener` 手写 HTTP/1.1 chunked SSE 假服务端,**未引入新依赖**。 + 选它而非 axum 的原因是需要按字节精确控制 chunk 切分点,以及在不发终止块的情况下中途断连—— + 这两点用 HTTP 框架无法表达。F-11 的端到端测试已对旧实现验证过确实失败(复现乱码),非同义反复。 + +**R2 审查后并入的三项**(都是 R2 自身改动造成的,已在本批修掉): + +- 移除流式总超时后,单条响应失去唯一边界(`read_timeout` 只测两次读之间的间隔,不能替代)。 + 已加 64MiB 单响应上限,同时约束 `mapper.accumulated`。 +- `send_slot_message` 的 `client.take()` 独占窗口原被 120s 总超时封顶,F-10 后变成与回复等长—— + 期间 sessions / capabilities / upload / download / switch 五个命令全部误报未连接。已改 `clone()` + + 以 `message_cancellation` 串行化发送(即 **F-49**,因 R2 使其显性化而从 R7 提前)。 +- `SseLineBuffer` 逐行从头 `drain` 是平方复杂度(hyper 单个 item 可达数百 KiB)。已改游标。 + +**R2 未覆盖、仍开放**:P1-2 描述中的「发送先入库 user 行」属 F-18(R3),本批未动。 + +**工具链教训(务必遵守)**:本批的对抗式审查让 subagent 直接跑在工作区上,其中两个 agent 做完 +「临时改动验证」后**没有还原**——在 `send_chat_stream` 的错误分支里注入了一个显式的第二次 +`POST /api/v1/chat`(注释标着 `MUTATION (temporary)`),并在 `astrbot_client.rs`、`runtime.rs`、 +`src-tauri/tests/` 留下了复现模块。那个注入的 POST 一度被误判为 HTTP 栈的真实缺陷并记为 F-69, +在把它二分到具体注入行之后才定位到真因。**F-69 不存在,已撤销。** +后续审查必须只读运行,或用独立 worktree 隔离。 + +### R1 已改动的文件 + +新增:`src/lib/errorMessage.ts`、`src/features/pet/types.test.ts` + +修改:`crates/desktop-protocol/src/astrbot.rs`、`src-tauri/src/networking/astrbot_client.rs`、 +`src-tauri/capabilities/default.json`、`src-tauri/tauri.conf.json`、`src/App.tsx`、 +`src/pages/SettingsPages.tsx`、`src/features/chat/{types.ts,types.test.ts,MessageContent.tsx,ChatPanel.tsx}`、 +`src/features/pet/{types.ts,DesktopPetView.tsx}`、`src/features/profiles/ProfileManager.tsx` + +### 接手 R2 前必须先做的事 + +1. **跑完整门槛验证 R1**,任何一项失败都先修 R1 再进 R2: + + ``` + cargo fmt --all -- --check + cargo clippy --workspace --all-targets -- -D warnings + cargo test --workspace + npm run typecheck && npm run lint && npm run test -- --run && npm run build + ``` + + R1 预期新增 3 组测试:Rust 侧 `consecutive_streams_do_not_reuse_event_ids`, + 前端侧 `chat/types.test.ts` 的三条 null 契约用例与新建的 `pet/types.test.ts`。 + +2. **F-01 的实现方式已定为方案 A**:`AstrBotStreamMapper::new(server_instance_id, stream_id)`, + `event_id` 形如 `astrbot-{sid}-{stream}-{seq}`,调用方每次请求传 `Uuid::new_v4()`。 + 队列正文中 F-01 行描述的方案 B / C 不再考虑。 + +3. **注意 `src/features/profiles/ProfileManager.tsx` 是 CRLF 为主的混合换行文件**, + 编辑时务必逐字节保留原有行尾,否则会产生整文件换行 diff。 + +4. R1 的改动全部经人工逐行核对,但**没有编译器验证过**。优先怀疑对象: + `astrbot.rs` 的新测试闭包借用、`errorMessage()` 的 10 个接入点类型、 + `.nullish()` 造成的 `string | null | undefined` 类型向下游传播。 + +--- + +队列按**执行顺序**编排,不是按严重度排序:同文件相邻改动合并进同一批以避免冲突,有依赖的项显式标注。每项给出位置、动作、验证方式与建议提交名(遵循 `AGENTS.md` §10 Conventional Commits)。 + +**排期约束(必须遵守的三条串行链)** + +1. `F-01` 必须先于 `R2` 全批 —— 两者都改 `astrbot_client.rs:440-510` 的流循环与 dispatch。 +2. `R2` 内部四项串行(同一函数体),建议同一分支连续提交,不要并行分派。 +3. `F-06`(zod)→ `F-08`(errorMessage)→ `R3` 的前端项,都动 `ChatPanel.tsx` / `chat/types.ts`,按序落地。 + +其余批次之间可并行分派给不同分支。 + +* * * + +## R1 · 发布阻断批 + +**目标**:恢复真实 AstrBot 聊天闭环与桌宠功能。9 项全部是小改动(多数一行到一函数),建议 1–2 天内合并,合并后重新走一遍 Q9 门槛。 + +| ID | 来源 | 位置 | 动作 | 验证 | +| --- | --- | --- | --- | --- | +| **F-01** | P0-1 | `crates/desktop-protocol/src/astrbot.rs:453-455`;`src-tauri/src/networking/astrbot_client.rs:440` | **推荐方案 A**:`AstrBotStreamMapper::new(server_instance_id, stream_id)` 增加流级种子(调用方传 `Uuid::new_v4()`),`event_id` 改为 `astrbot-{sid}-{stream}-{seq}`。保留同流内去重语义,事件 ID 全局唯一。(方案 B:sequence 提到 client 级 `AtomicU64` —— 会让协议 crate 依赖 client 生命周期,不推荐;方案 C:astrbot 路径取消去重 —— 最省事但丢掉同流重复防护) | 新增单测:同一 `AstrBotClient` 连续两次 `send_chat_stream`,第二条流的 delta 与 completed 全部到达 sender。真机:同一连接连发 3 条,每条回复完整显示 | +| **F-02** | P1-12 | `src/features/pet/types.ts:47` | 正则 `\\.` → `\.` | `expect(petPackManifestSchema.parse(内置 manifest.json))` 通过 | +| **F-03** | P1-13 | `src-tauri/capabilities/default.json:5` | `windows` 数组加 `"desktop-pet"` | 桌宠窗口能收到 `connection-runtime-event`;拖动与右键菜单生效 | +| **F-04** | P1-14 | `src-tauri/tauri.conf.json` → `app.security.csp` | `img-src` 追加 `blob:` | **release 构建**下发送带图消息,图片正常渲染(dev 不注入 CSP,必须用 release 验) | +| **F-05** | P1-15 | `src/features/chat/MessageContent.tsx:66-72` | `new URL(href, base)` 解析后仅放行 `http/https`(可选 `mailto`),非法协议降级为纯文本;`rel` 补 `noopener` | 单测:`[x](javascript:alert(1))` 渲染为文本而非 `` | +| **F-06** | P1-7a | `src/features/chat/types.ts:35,36,63,64,156` | 五处 `.optional()` → `.nullish()`(`sessionId`/`messageId`/`displayName`/`updatedAt`/`name`) | 契约测试:用 Rust `serde_json` 真实输出(含 `null`)回放,`boundRuntimeEventSchema` / `remoteChatSessionSchema` / `astrbotModelOptionSchema` 全部通过 | +| **F-07** | P1-7b | `crates/desktop-protocol/src/astrbot.rs:84-91` | `AstrBotModelOption` 补 `#[serde(rename_all = "camelCase")]`(该类型不入库,无迁移风险) | 前端 `isDefault` 不再恒 undefined;模型下拉默认项正确 | +| **F-08** | P1-16 | 新建 `src/lib/errorMessage.ts`;接入 `ChatPanel.tsx:423` 等 6 处、`SettingsPages.tsx:119` | 抽出共享 `errorMessage()`,识别 `{code,message}` 形状(复用 `ProfileManager.tsx:689-702` 的既有实现) | 断开连接后发送,错误条显示 Rust 的 `message` 而非 `[object Object]` | +| **F-09** | P1-17 | `DesktopPetView.tsx:92,173,191,198`;`App.tsx:451,554` | 恢复中文原文("精灵图加载失败"/"无法获取 Canvas 上下文"/"桌宠"/"加载中…");`&#x...;` 实体改明文 | CI 加 `grep -nP '\?{3,}'` 与非 ASCII 实体扫描 | + +**批次验收**:`cargo test`(+3 条新测试)、Vitest、typecheck、lint、release 构建、真机连发 3 条消息 + 桌宠事件联动 + 附件图渲染。 + +**建议提交**:`fix(astrbot): scope stream event ids per request` / `fix(pet): correct manifest image pattern` / `fix(tauri): grant desktop-pet capability` / `fix(tauri): allow blob images in production csp` / `fix(chat): restrict markdown link protocols` / `fix(chat): accept null in runtime event contracts` / `fix(protocol): serialize model options in camelCase` / `refactor(ui): share ipc error formatting` / `fix(ui): restore corrupted localized strings` + +* * * + +## R2 · 传输层批(串行,同一分支) + +**目标**:让长连接与长回复真正可用。四项都在 `astrbot_client.rs` / `gateway_client.rs` 的流循环,必须串行。 + +| ID | 来源 | 位置 | 动作 | 验证 | +| --- | --- | --- | --- | --- | +| **F-10** | P1-1 | `gateway_client.rs:100-101`;`astrbot_client.rs:147-148` | 拆分两个 reqwest Client:REST 保留总时限,流式端点**不设** `.timeout()`,改用 `connect_timeout` + 心跳看门狗 / `read_timeout` 做空闲检测 | desktop SSE 连续保持 \>5 分钟不断;AstrBot 生成 \>120s 的长回复完整到达 | +| **F-11** | P1-3 | `astrbot_client.rs:462-463` | `buffer` 改 `Vec`,按 `\n` 在**字节层**分行,逐行 `String::from_utf8`(保留不完整尾字节到下一 chunk) | 单测:把一条中文 SSE 帧在 UTF-8 字符中间切成两个 chunk 喂入,输出无 `U+FFFD` | +| **F-12** | P1-2 | `runtime.rs:647-653`、`:723-731` | `should_retry_astrbot` 收窄:仅"连接建立失败"可重试;一旦收到响应头/首字节即不再自动重发,改返回可手动重试的错误码 | 单测:mock 在响应体中途断流 → 不产生第二次 POST | +| **F-13** | P2-2 | `astrbot_client.rs:456-459` 及 `next?` 错误路径 | 取消与错误两条 return 路径统一调 `mapper.finish_stream()`(`FinishReason::Cancelled` / `Error`)并 dispatch | 停止生成后重启应用,该消息不再显示为"生成中";DB 无 `streaming=1` 残留 | + +**批次验收**:新增 3 条单测;真机断网/恢复、长回复、中途停止三场景。 + +**建议提交**:`fix(net): stop total timeouts from killing streams` / `fix(astrbot): decode sse bytes on line boundaries` / `fix(astrbot): do not resend messages after response start` / `fix(astrbot): finalize streams on cancel and error` + +* * * + +## R3 · 隔离与状态正确性批 + +| ID | 来源 | 位置 | 动作 | 验证 | +| --- | --- | --- | --- | --- | +| **F-14** | P1-4 | `runtime.rs:197-325` | 探测移出锁:先置 `Connecting` 快照并 `drop(guard)`,`health()`/`probe()` 在锁外执行,按 generation 回写;激活伊始即安装 `connection_cancellation` 并在 probe 内 `select` | 一个槽连接不可达地址期间,另一槽的 `status()`/发送/断开全部正常;激活中可被 disconnect 打断 | +| **F-15** | P1-10 | `ChatPanel.tsx:144-155`;`App.tsx:391-399`;`DesktopPetView.tsx:46-82`;`src/test/setup.ts` | 三处改 `let active=true; listen().then(fn => active ? unlisten=fn : fn()); return () => {active=false; unlisten?.()}`;测试 mock 改为延迟 resolve 并断言注销次数 | StrictMode 下 delta 不再翻倍;新测试断言 unmount 后注销被调用 | +| **F-16** | P1-11 | `ChatPanel.tsx:80-82,384-412` | `pendingAttachments`、`draft`、`error` 改 `Record` | 陪伴槽上传附件 → 切运维 → 发送,附件不跟随;运维错误横幅不出现在陪伴槽 | +| **F-17** | P2-1 | `runtime.rs:453-477` | `switch_slot_session` 首锁捕获 `generation`,二次锁写入前比较,不一致返回 cancelled | 单测:切换会话期间 deactivate,旧 session 不写入新代快照 | +| **F-18** | P2-3 | `commands.rs:632-656` | 校验通过且确认 client 存在后再 `upsert_chat_message`;失败路径按 message_id 回删或标记 error | 未连接状态下发送,历史里不留 user 行 | +| **F-19** | P2-4 | `commands.rs:412-461` | `probe_connection_slot` 激活前校验 `connection_slots` 分配,拒绝同一 profile 占用两个运行时槽;operations 切换守卫覆盖 probe/disconnect | 同一 profile 依次 probe 双槽 → 第二次被 `profileAlreadyAssigned` 拒绝 | + +* * * + +## R4 · 数据与凭据安全批 + +| ID | 来源 | 位置 | 动作 | 验证 | +| --- | --- | --- | --- | --- | +| **F-20** | P1-6 | `database/mod.rs:319-320` | 改 `SELECT * FROM (… ORDER BY updated_at DESC LIMIT ?) ORDER BY updated_at ASC`;补 `before`/`after` 游标参数 | 单测:插入 250 条,加载返回最新 100 条 | +| **F-21** | P1-18 | `diagnostics/redaction.rs:91` | `key_value_regex` 候选加入裸 `token`、`auth[_-]?token`、`id[_-]?token`、`session[_-]?token`;新增 JWT 形态正则 `eyJ[\w-]+\.[\w-]+\.[\w-]+` | 新测试**不使用 known_secrets**:`token=eyJ…`、`?token=…`、YAML `token: eyJ…` 均须被脱敏(现有测试用 canary 掩盖了缺口,需一并重写) | +| **F-22** | P2-11 | `diagnostics/config.rs:213,232,259` | YAML/INI/.env 增加按 key 的行级结构化脱敏(对齐 JSON/TOML 的 `is_sensitive_key` 路径) | `.env` 内 `AUTH_TOKEN=…` 经诊断返回时为 `[REDACTED]` | +| **F-23** | P2-9 | `profiles.rs:213-218` | 删除 profile 前读取 `credential_reference` 并 `store.delete`;可选:启动时孤儿凭据对账 | 删除 profile 后 Credential Manager 中对应条目消失 | +| **F-24** | P2-10 | `auth.rs:13-20`;`credentials/mod.rs:11-20` | 两个请求结构体手写 `Debug`(敏感字段输出 `[REDACTED]`)或改 `secrecy::SecretString` | 单测断言 `format!("{:?}", req)` 不含明文(对齐 `SecretCredential` 既有测试) | +| **F-25** | P2-12 | `database/mod.rs:524,556` 及相关读写 | 统一 `account_id` 键模型:两表都含并全部读写带上,或彻底移除该列 —— 二选一,写进 ADR | 迁移测试 + 隔离测试 | + +* * * + +## R5 · 协议健壮与契约治理批 + +| ID | 来源 | 位置 | 动作 | 验证 | +| --- | --- | --- | --- | --- | +| **F-26** | P1-5 | `gateway_client.rs:179-184,282-284` | `UnsupportedEventType` / `InvalidPayload` 降级为事件级跳过(记日志、推进 `last_event_id`),仅版本/身份不匹配保持终态 | 单测:mock 推未知事件类型 → 槽位保持 Connected,后续事件正常 | +| **F-27** | P2-15 | `envelope.rs:171` 及各 payload | 信封与只读 payload 移除 `deny_unknown_fields`(`ToolProposal`/`ToolResult` **保留**);或解析失败跳过并推进游标 | 单测:信封带附加字段仍能解析;不再出现重放死循环 | +| **F-28** | P1-8 | `docs/protocol/v1/schemas/`;`tests/protocol_contract.rs` | 重跑 `export_schemas --write`;新增测试比对 `generated_schemas()` 与磁盘文件 | `cargo test` 即可发现漂移;`connection-profile.schema.json` 含 `remoteDisplayName` | +| **F-29** | P2-16 | `astrbot.rs:17-43`;`src/features/chat/types.ts:13`;`ChatPanel.tsx:240`;README | `TransportKind` 加 `#[serde(rename = "astrbot-openapi")]` 统一两套拼写,前端 enum 与文档同步(**跨端原子改动,一次落地**;DB 值不变,无迁移) | 全库 grep 无 `astr-bot-open-api` 残留 | +| **F-30** | P2-5 | `astrbot_client.rs:128-133,431-438` | 删除恒 false 的身份自比较,或改为探测可观测特征后再比对;文档明示 AstrBot 身份为 URL 派生 | 代码无死分支;`docs/decisions/` 记录该限制 | +| **F-31** | P2-19 | `mock-gateway/src/routes.rs:196-206`、`state.rs:161-173`、`config.rs:29-31` | `Lagged` 改 `break`(迫使走重连重放);cursor 未命中先发 gap 事件;`server_instance_id` 掺端口 | soak 增加 sequence 单调无缺口断言 | +| **F-32** | P2-17 | `astrbot.rs:381-444` | complete 后记录 per-message 完成标记,同 id 的后续 plain/complete 需显式重新开窗或忽略 | 单测覆盖"重复 complete"与"complete 后迟到 plain" | +| **F-33** | P2-18 | `astrbot.rs:336-353` | 非图片媒体输出通用占位标记;`pending_media` 改 FIFO 队列 | 单测:`record` + `attachment_saved` 产出可见标记;双图交错不丢 | +| **F-34** | P2-13 | `commands.rs:341`;`ChatPanel.tsx:916-917` | mapper 为无 `message_id` 的流合成稳定流内 id(如 `synthetic-{stream}`),前后端同步取消 event_id 回退 | 单测:省略 message_id 的多帧流合并为一条消息 | + +* * * + +## R6 · 体验、无障碍与产品红线批 + +| ID | 来源 | 位置 | 动作 | +| --- | --- | --- | --- | +| **F-35** | P2-30 | `DesktopPetView.tsx:139-148`;`tauri.conf.json` | **产品红线**:`alwaysOnTop` 默认改 `false`(隔离基线要求气泡/桌宠不默认置顶);embedded 模式跳过偏好写入;非 embedded 先读既有偏好再增量提交 | +| **F-36** | P2-20 | `ChatPanel.tsx:73-74,181-187,264-293` | mark-read 完成后再重取会话列表;仅存在真实 `activeSessionId` 时标已读;非选中槽位监听事件递增未读 | +| **F-37** | P2-21 | `ChatPanel.tsx:468-475` | `retryMessage` 增加 `sessionId === activeSessionId` 过滤;`messageOverride` 与 draft 回退解耦 | +| **F-38** | P2-22 | `ChatPanel.tsx:435-457` | 按 `code === "cancelled"` 区分取消与真错误;停止时保留已收内容为正常消息,不标 error、不弹横幅 | +| **F-39** | P2-23 | `ChatPanel.tsx:920-925`;`chat/types.ts` | `ChatMessage` 补 `profileId`/`serverInstanceId` 并纳入所有 find/filter/去重键(对齐四元组规范) | +| **F-40** | P2-24 | `styles.css:3116-3139` | 去掉 `visibility:hidden`,仅用 opacity + pointer-events,解开键盘 focus-within 死锁 | +| **F-41** | P2-25 | `ChatPanel.tsx:607-620,711-717` | 箭头切换时 `focus()` 目标 tab;两个 panel id 常驻或动态 `aria-controls`;`aria-busy` 与 `aria-live` 分离 | +| **F-42** | P2-26 | `CredentialEnrollmentCard.tsx:34-80` | `finally` 中清空 secret/password/totp;两处 `invoke` 返回值补 zod schema | +| **F-43** | P2-27 | `ChatPanel.tsx:343-354` | 首次 refresh 失败也建立退避轮询;snapshot schema strict 失败给可见告警而非静默离线 | +| **F-44** | P2-28 | `ChatPanel.tsx` | 消息列表底部锚点 +"接近底部才跟随";unmount 调 `recognition.stop()` / `speechSynthesis.cancel()`;朗读前 Markdown 转纯文本 | + +* * * + +## R7 · 性能与工程化批 + +| ID | 来源 | 动作 | 预期收益 | +| --- | --- | --- | --- | +| **F-45** | 优化 §2 | `DesktopPetView.tsx:10` 去掉 `?inline` 改普通资源引用,manifest 与 import 同时切到已有的 WebP | lazy chunk 从 \~5.2MB 降到 \~0.6MB | +| **F-46** | 优化 §1 | `activeMessages` memo 依赖改标量 `activeSessionId`;`MessageContent` 套 `React.memo`;`applyRuntimeEvents` 只克隆命中项;`messages` 按会话修剪 | 消除 500ms 全表重渲染与重复 Markdown 解析 | +| **F-47** | 优化 §3 | 附件上传/下载改 Tauri 2 raw body / `tauri::ipc::Response` 二进制通道;Rust 侧去掉 `bytes.clone()` | 16MiB 附件不再膨胀成 1670 万元素数组 | +| **F-48** | P2-14 | 事件通道改"每槽独立 mpsc + 唯一持久化点 + 广播 emit",移除 `drain_connection_runtime_events` | 消除双消费者抢事件与跨槽背压 | +| **F-49** | 优化 §2 | `send_slot_message` 的 `client.take()` 改 `clone()`,以 `message_cancellation` 存在性串行化发送 | 长流期间 sessions/capabilities/upload 不再误报"未连接" | +| **F-50** | 优化 §5 | `styles.css` 以 `--ui-*` 为唯一 token 源合并,删除 OS 亮色媒体查询块与幽灵 token,引入 stylelint | 减约 40% 死样式;修复暗色下链接对比度 | +| **F-51** | P2-31 | `tauri.conf.json` 的 `beforeDevCommand`/`beforeBuildCommand` 改 `pnpm run`;engines 与 `@types/node` 对齐;文档 React 版本更正为 19 | 消除双包管理器混跑 | +| **F-52** | P3-17 | tsconfig 补 `noUnusedLocals`/`noUncheckedIndexedAccess`;eslint 接 jsx-a11y、重开 `set-state-in-effect`;vitest 加 coverage;关掉无谓的 `usePolling` | 编译期即可暴露索引假设类缺陷 | + +* * * + +## R8 · 剩余 P3 与外部依赖 + +**可随手带入相邻批次的 P3**:`F-53` 事件 timestamp 注入真实时钟(P3-1)· `F-54` `server_instance_id` 改 sha2 派生 + 兼容映射(P3-2)· `F-55` username 逐字节百分号编码(P3-3,**放宽用户名规则前必须先修**)· `F-56` 取消消息不再置 Disconnected(P3-4)· `F-57` 生产 CSP 移除 `127.0.0.1:*`(P3-5)· `F-58` 凭据轮换改「写新→落库→删旧」(P3-6)· `F-59` 退出前 deactivate 双槽并 flush 日志(P3-8)· `F-60` session_id 对象分支取键(P3-9)· `F-61` 桌宠窗口补 Suspense 边界(P3-10)· `F-62` 导航图标 `aria-hidden` + 测试选择器改语义文本(P3-11)· `F-63` reduced-motion 停帧 + onerror 清理 + DPR(P3-12)· `F-64` 文案统一中文(P3-13)· `F-65` 死控件与标签错误四处(P3-14)· `F-66` 测试 SSE 助手容错(P3-15)· `F-67` App.test mock 补 `close_pet_window`(P3-16)· `F-68` mock 订阅重放竞态(P3-18) + +**需要真机/外部条件,不进本轮编码**: + +- **P1-9 附件契约验证**(置信度中):用真实容器发一条带图消息,确认模型是否真的看到附件。若确认被忽略,改为 `message` 段数组承载 `attachment_id`(snake_case),这会是一个 P1 级改动。 +- **证书指纹绑定**:在实现 TLS 校验前,建议在录入层标注"暂不生效",避免虚假安全感。 +- **工具提案六道闸门**:未开始实现属阶段合理;**在闸门落地前不得放开任何工具执行入口**,`connection_policy_status` 应如实上报 guard 未激活。 +- **签名更新、双服务器 soak**:维持现状,不在本地伪造。 + +* * * + +## 附录 · 批次依赖图与建议分支 + +| 批次 | 依赖 | 建议分支 | 可并行 | +| --- | --- | --- | --- | +| R1 | 无 | `fix/p02-release-blockers` | 内部 9 项可并行(除 F-06→F-08) | +| R2 | R1 的 F-01 | `fix/astrbot-stream-transport` | 内部串行 | +| R3 | R1 的 F-06 | `fix/slot-isolation-and-state` | Rust 项与前端项可分两人 | +| R4 | 无 | `fix/data-and-secret-boundaries` | 与 R2/R3 并行 | +| R5 | 无 | `fix/protocol-contract-hardening` | 与 R2/R3/R4 并行 | +| R6 | R3 | `fix/chat-ux-and-a11y` | — | +| R7 | R6 | `perf/frontend-and-ipc` | — | +| R8 | — | 随批携带 | — | + +按 `AGENTS.md` §11,每批合并前须走完:fmt → lint → typecheck → clippy(-D warnings) → 单元测试 → 适用集成测试 → 生产构建 → 更新 `docs/progress.md` 与 `CHANGELOG.md`。R1 与 R2 合并后建议同时刷新 `docs/q9-local-acceptance.md` 的验证记录。 diff --git a/docs/reports/full-source-audit-2026-07-26.md b/docs/reports/full-source-audit-2026-07-26.md new file mode 100644 index 0000000..e265255 --- /dev/null +++ b/docs/reports/full-source-audit-2026-07-26.md @@ -0,0 +1,289 @@ +# AstrBot Desktop 全源码审查档案 + +全源码审计 · 2026-07-26 + +> 配套修复队列:[fix-queue-2026-07-26.md](./fix-queue-2026-07-26.md)(68 项,8 个批次,含排期依赖与验证方式)。 + +| 项目 | 值 | +| --- | --- | +| 代码基线 | 分支 `feat/p02-dual-connections` · v0.1.0-alpha.2 · 本地快照 2026-07-21/22 | +| 所处阶段 | 本地 Q9 门槛已过;Q10–Q15 聊天体验增量与 AstrBot OpenAPI 适配器刚完成 | +| 审计范围 | `src/`、`src-tauri/`、`crates/`、`tests/`、根配置、`docs/`(契约与阶段文档)共 146 个文件、约 2.4 万行 | +| 审计方法 | 4 路并行深度静审(Rust 网络运行时 / Rust 数据安全 / 协议与网关 / 前端与工程)+ 逐条人工复核高危发现(关键结论均回读源码验证,宠物 manifest 正则经 node 实测) | +| 发现统计 | **P0 × 1 · P1 × 18 · P2 × 31 · P3 × 18**;另剔除误报 2 项、降级 2 项(见附录 A) | + +严重度定义:P0 = 核心功能不可用 / 数据丢失 / 安全越界;P1 = 明确 BUG 或隔离违规,特定场景必现;P2 = 边界缺陷 / 健壮性 / 一致性;P3 = 小优化。 + +* * * + +## 一、总体评估 + +架构骨架是健康的:双槽位隔离在**数据层**做得扎实(`chat_messages` 主键含 `profile_id + slot + server_instance_id + session_id + message_id`,超出规范要求);凭据边界(Windows Credential Manager + Zeroizing + 引用入库)、文件事务(plan→dry-run→复制→哈希→原子提交、保源不覆盖)、路径策略(双层防御,覆盖 UNC / `..` / 保留名 / 尾随点空格)、全库无任何 shell 执行入口——这些安全铁律主线成立,质量高于同阶段项目平均水平。 + +但**最近两周的高速增量(AstrBot 适配器 + Q10–Q15 前端)留下了一条贯穿性的裂缝:契约失配**。三类契约各自漂移——Rust 序列化 ↔ 前端 zod(`null` vs `optional` 三连)、Rust 类型 ↔ JSON Schema 文档(`remoteDisplayName` 漂移且无 CI 拦截)、客户端实现 ↔ 真实 AstrBot 线上行为(附件字段、事件 ID 语义)。叠加一个 P0(去重器吞掉第二条消息的流式回复)和两个传输层缺陷(30s/120s 全局超时杀长连接、UTF-8 跨 chunk 乱码),**当前基线对真实 AstrBot 的核心聊天闭环与对 Mock 网关的事件链路都处于"带病运行"状态**——本地门槛全绿是因为测试恰好全部避开了这些路径(单流单发、恒带 message_id、mock 不过前端)。 + +结论:不建议在修复第一批(见第六节路线图)之前打 `v0.1.0-alpha.3`(文字聊天完成)标签。 + +* * * + +## 二、BUG 档案 + +### P0:致命 + +**P0-1[后端·协议]同一连接第二条消息起,流式回复被去重器整体吞掉** + +- 位置:`crates/desktop-protocol/src/astrbot.rs:454-455` + `src-tauri/src/networking/astrbot_client.rs:440, 505-508`(两路审计独立发现,已人工复核确认) +- 证据: + +```rust +// astrbot.rs — 每次流从 1 重新计数 +self.sequence = self.sequence.saturating_add(1); +let event_id = format!("astrbot-{}-{}", self.server_instance_id, self.sequence); +// astrbot_client.rs — 去重器却挂在 client 上跨请求存活 +let mut mapper = AstrBotStreamMapper::new(server_instance_id.clone()); // 每次 send 新建 +if !seen.insert(event_id.clone()) { continue; } // seen 构造于 client 创建时 +``` + +- 问题:`AstrBotStreamMapper` 每次 `send_chat_stream` 新建、`sequence` 归零,事件 ID 仅由 `server_instance_id + 序号` 构成;而 `seen_event_ids`(容量 4096)随 `AstrBotClient` 存活,`runtime` 发送后把同一 client 放回复用。第 1 条消息占用 `astrbot-X-1..N`;第 2 条消息的事件重新从 `astrbot-X-1` 开始 → 全部命中去重 → `continue` 静默丢弃,不进前端、不进数据库。**同一连接从第二条消息起,助手回复整体丢失**(除非新流事件数超过历史最大值,只透出错位尾部)。发送失败重试(`attempts < 2`)同样重建 mapper,连第一条消息的重试流也会被部分吞掉。所有现有测试均为"单 mapper 单流",故 Q9 门槛未拦截。 +- 修复:事件 ID 掺入每次请求的唯一盐(UUID / message_id),或把 sequence 提升为 client 级 `AtomicU64`;更干净的做法是对 astrbot 传输**取消 event_id 去重**(请求级 SSE 不存在重放,去重语义只对 desktop-v1 的 Last-Event-ID 成立)。必须补"同一 client 连发两条"回归测试。 + +### P1:高危 + +#### A 组 · Rust 网络与运行时 + +**P1-1 reqwest 全局 `timeout` 作用于流式响应:Desktop SSE 每 30 秒必断,AstrBot 长回复 120 秒被截** +`gateway_client.rs:100-101`(`.timeout(30s)`)、`astrbot_client.rs:147-148`(`.timeout(120s)`)。`Client::timeout` 是"请求开始到响应体读完"的总时限,对 `bytes_stream()` 持续生效:desktop-v1 长连接永远处于 30 秒一断的重连循环(心跳无法续命);AstrBot 超过 120 秒的生成在中途被杀,并触发 P1-2 的整条重发。修复:流式端点使用不设总时限的专用 Client(空闲检测用 read_timeout / 心跳看门狗),仅普通 REST 保留总时限。 + +**P1-2 流中途断开被当作"未送达"整条重发:服务端出现重复用户消息,前端流内容错乱** +`runtime.rs:647-653` + `runtime.rs:724-725`。`should_retry_astrbot` 把 `Request(_)` 一律判可重试,但该类错误既含"POST 未发出"也含"响应流读取中断"(网络抖动、P1-1 的 120s 超时)。后者重试= 同一条消息再次 POST `/api/v1/chat`(无幂等键),会话里出现重复提问与重复回答;两次尝试的 delta 交错,再叠加 P0-1 被部分吞掉。且首次尝试失败不调 `finish_stream`,前端残留半截流式气泡。修复:收到响应头/首字节后不再自动重发,改报可手动重试错误。 + +**P1-3 SSE 字节流按网络 chunk 调 `String::from_utf8_lossy`:中文跨 chunk 必成 U+FFFD 乱码** +`astrbot_client.rs:462-463`(`buffer.push_str(&String::from_utf8_lossy(&chunk))`)。TCP chunk 边界可落在任意字节,中文(3 字节/字)被切在字符中间即产生 `�` 且随 delta 入库;断流/取消场景永久保留。这是面向中文用户客户端的高频显性缺陷。修复:以 `Vec` 缓冲,按 `\n` 字节分行后再做 UTF-8 解码(保留不完整尾字节)。 + +**P1-4 `activate_slot` 持全局锁跨网络探测:一个槽激活会冻结两个槽的全部运行时命令,且激活不可取消** +`runtime.rs:197`(加锁)→ `:243 health().await` / `:298 probe().await`(持锁 await)→ `:325 drop(guard)`。`inner` 是覆盖双槽的单一 `tokio::Mutex`,探测最坏耗时 = 120 秒;期间 `status()`(托盘 1s 轮询)、发送、断开、取消对**两个槽**全部阻塞——与"槽位隔离"目标直接冲突。`connection_cancellation` 在探测成功后才安装,激活过程无法被打断;启动自动连接串行走同一路径,一个坏 Profile 拖住整个 UI。修复:先置 Connecting 快照并释放锁,探测完按 generation 回写;激活伊始即安装取消令牌。 + +**P1-5 未知事件类型被判终态 `Incompatible`,与协议文档"安全跳过"承诺相反** +`envelope.rs:227`(`UnsupportedEventType` 报错)+ `gateway_client.rs:282-284`(`Protocol(_) → Incompatible`,停止重连)。`docs/protocol/v1/README.md:28` 承诺 "Unknown event types are … safely skipped"。网关新增任意事件类型(正常向后兼容演进)→ 槽位永久离线。同族问题见 P2-15(信封 `deny_unknown_fields` + Last-Event-ID 重放同一坏事件 → 重连永久卡死)。修复:对 `UnsupportedEventType`/`InvalidPayload` 做事件级跳过并推进 `last_event_id`,仅版本/身份不匹配保持终态。 + +**P1-6 长会话历史加载取"最旧 N 条":超过 200 条后最新消息永远不可见** +`database/mod.rs:320`:`ORDER BY updated_at ASC LIMIT ?5`(命令层默认 100、上限 200,无游标)。升序 + LIMIT 取的是最早的 N 条,长会话重启后只显示开头。修复:子查询取最新 N 条再正序返回,并补 before/after 游标分页。 + +#### B 组 · 契约失配(本次审计最大缺陷簇) + +**P1-7 zod `.optional()` ≠ Rust `null` 三连:事件、远端会话、能力三条链路静默失效** +Rust 侧 `Option` 无 `skip_serializing_if` → 序列化为 `null`;zod `.optional()` 只接受 `undefined`。三处失配(同文件上方 `slotRuntimeSnapshotSchema` 已全用 `.nullish()`,说明是"去信封化"后漏改): + +| 失配点 | 位置 | 后果 | +| --- | --- | --- | +| `boundRuntimeEventSchema.sessionId/messageId` | `types.ts:35-36` vs `gateway_client.rs:37-38` | `safeParse` 失败 → 事件整条丢弃:**desktop-v1/mock 事件(不带 session_id)100% 全丢**;AstrBot 的 error/heartbeat/无 message_id 帧被丢 → 聊天错误不显示 | +| `remoteChatSessionSchema.displayName/updatedAt` | `types.ts:62-65` vs `commands.rs:542-548` | 任一会话字段为 None → 整个数组解析抛错被 `.catch` 吞掉 → **远端会话列表恒空**(Q3.2 断裂) | +| `astrbotModelOptionSchema` | `types.ts:154-158` vs `astrbot.rs:84-91` | `name:null` → capabilities 解析失败 → **文件上传按钮永久禁用**;且 Rust 无 `rename_all`,输出 `is_default`,前端期望 `isDefault` 恒丢 | + +修复:前端三处改 `.nullish()` + Rust `AstrBotModelOption` 补 `rename_all="camelCase"`(或统一加 `skip_serializing_if`);`safeParse` 失败至少在 DEV 打 `console.warn`;用 Rust 真实序列化样本(含 null)做双端契约测试。 + +**P1-8 `connection-profile.schema.json` 已漂移(缺 `remoteDisplayName`),且 schema 漂移检查未接入任何自动化** +`connection.rs:85` 有 `remote_display_name`;schema 文件 0 处 `remoteDisplayName` 且顶层 `additionalProperties:false` ——按文档校验合法 profile 必失败。`export_schemas` 示例存在但无 CI/测试调用(全仓无 workflow 引用)。修复:重新 `--write` 导出;在 `protocol_contract.rs` 加"生成 schema ↔ 磁盘文件"比对断言,使 `cargo test` 即可拦截。 + +**P1-9 附件字段不在已探明的真实 OpenApiChatRequest 契约内,可能被服务端静默忽略**(置信度:中,需真机验证) +`astrbot.rs:75-76`:顶层 `attachments`(元素还是 camelCase);而 `docs/reports/astrbot-real-protocol-review.md:76-88` 探明的请求模型无此字段,附件正道是 `message` 段数组内的 `attachment_id`(snake_case)段。FastAPI 默认忽略未知字段 → 上传成功但模型看不到文件,Q3.1 多模态闭环虚假成立(探针报告自己也注明"end-to-end image rendering… still require a real chat send")。修复:含附件时把 `message` 构造成段数组,用真实容器验证一次模型可见性。 + +#### C 组 · 前端 + +**P1-10 `listen()` 注销竞态:StrictMode 下必现双监听 → 每个 delta 被应用两次** +`ChatPanel.tsx:144-155`(同模式 `App.tsx:391-399`、`DesktopPetView.tsx:46-82`):cleanup 执行时 `unlisten` 仍是 `undefined`,promise 解析出的注销函数无人调用 → 首个监听器永久泄漏。`main.tsx` 确认启用 `StrictMode`(挂载即 mount→cleanup→mount):delta 逐字翻倍、消息重复;生产环境快速切页同样触发。修复:`let active=true; listen().then(fn => active ? (unlisten=fn) : fn()); return () => { active=false; unlisten?.(); }`。测试 setup 把 `listen` mock 成同步返回,恰好掩盖此竞态,需一并改为延迟 resolve。 + +**P1-11 附件/草稿/错误状态不随槽位切换隔离:陪伴槽上传的附件会被发进运维槽** +`ChatPanel.tsx:80-82, 384-412`:`pendingAttachments` 单一 state、切槽不清空,发送时按当前 `selectedSlot` 提交——附件却是按上传时槽位落到对端实例的。操作序列:陪伴上传 → 切运维 → 发送 → 串槽。`draft`、`error` 同样全局单串(运维报错横幅在陪伴槽仍显示)。与"双槽 UI 层隔离"边界直接冲突。修复:三者改 `Record` 或切槽清空。 + +**P1-12 宠物素材包 manifest 校验正则写错:一切合法素材包被拒(含仓库自带示例)** +`src/features/pet/types.ts:47`:`/^[^\\/:*?"<>|]+\\.(png|webp)$/i` —— `\\.` 在正则字面量中= 「字面反斜杠+任意字符」,而字符类又排除反斜杠。**node 实测**:`"aemeath-spritesheet.png"` → `false`。`PetPackImporter` 功能整体不可用。修复:`\\.` 改 `\.`,并补一条 `parse(内置 manifest.json)` 单测。 + +**P1-13 `desktop-pet` 窗口不在 capability 清单:桌宠全部 IPC 与事件监听被 Tauri ACL 拒绝** +`capabilities/default.json:5`(`windows: ["main","quick-chat","status-bubble"]`)vs `tauri.conf.json`(`desktop-pet` 随启动 `create:true`)+ `lib.rs:35`。桌宠的运行状态联动(文档声称已接入双槽状态)、拖动、右键菜单、偏好设置全部静默失败(`void listen/invoke` 吞掉 rejection)。修复:windows 数组加入 `"desktop-pet"`。 + +**P1-14 生产 CSP `img-src` 缺 `blob:`:发行版聊天附件图片全部被拦** +`tauri.conf.json` CSP:`img-src 'self' asset: http://asset.localhost data:`;而 `MessageContent.tsx:117` 用 `URL.createObjectURL` 生成 `blob:` URL。dev 不注入 CSP,故本地开发发现不了。修复:`img-src` 补 `blob:`。 + +**P1-15[安全]Markdown 链接 href 未做协议白名单:`javascript:`/`data:` 可直达 ``** +`MessageContent.tsx:66-72`:`href={link[2]}` 原样透传,助手消息属不可信远端输入,本 webview 内 JS 可直达全部 Tauri IPC。渲染器其余部分全走 React 文本节点(无 `dangerouslySetInnerHTML`、正则无灾难回溯),唯一缺口是 href。实际可利用性取决于 WebView2 对 `_blank`+`javascript:` 的处理(纵深防御必修)。修复:`new URL()` 解析后仅放行 http/https,非法协议渲染为纯文本;`rel` 补 `noopener`。 + +**P1-16 Tauri 结构化错误全部显示为 `[object Object]`** +`ChatPanel.tsx:423-424` 等 6 处 + `SettingsPages.tsx:119-120`:`reason instanceof Error ? reason.message : String(reason)`,而 Rust `RuntimeCommandError {code,message}` 以普通对象 reject。任何发送/重连/停止失败,用户看到的都是 `[object Object]`。`ProfileManager.tsx:689-702` 已有正确的 `errorMessage()` 兜底——抽出共享即可。 + +**P1-17 用户可见乱码文案与乱码无障碍名(历史 UTF-8 损坏残留)** +`DesktopPetView.tsx:92/173/191`(`setSpriteError("????????")` 等)、`:198`(`aria-label="AstrBot ??"`)、`App.tsx:451`(`Loading?`)、`:554`(用 HTML 实体硬编码"桌面浮动")。与 `docs/implementation-queue.md:104/171-182` 的既有乱码同源。修复:恢复中文原文;CI 加 `\?{2,}` 扫描防回归。 + +#### D 组 · 安全 + +**P1-18 脱敏正则漏"裸 `token`/JWT":诊断功能可把 JWT 原文回传 UI** +`redaction.rs:91`:自由文本正则候选只有 `access_token/refresh_token/api_key/...`,**没有裸 `token`**(结构化 `is_sensitive_key` 反而认 `token`,`redaction.rs:68-85`);`bearer_regex` 需 `Bearer ` 前缀,无 JWT 形态兜底。生产日志 sink(`logging.rs:18`,`known_secrets` 为空)与 `log_tail`/`config` 诊断全靠此正则。实测路径:log-tail 一行 `token=eyJ...`、config 解析 `.env/.yaml` 里的 `token:` → JWT 原样回传前端,违反脱敏铁律。而 `auth.rs` 恰从响应 `data.token` 取 JWT,此 key 名正是高频形态。现有脱敏测试用 known-secret 做 canary,恰好掩盖了正则缺口。修复:候选加入裸 `token`(及 `auth/id/session[_-]?token`)+ JWT 形态正则 `eyJ[\w-]+\.[\w-]+\.[\w-]+`;YAML/INI/.env 增加结构化 key 脱敏(见 P2-11)。 + +### P2:中危(31 项) + +| \# | 位置 | 问题(触发 → 后果) | 修复方向 | +| --- | --- | --- | --- | +| 1 | `runtime.rs:469-477` | `switch_slot_session` 二次加锁不校验 generation:期间槽被重置/重激活,旧 session 写入新代快照并回写 sticky_session_id(generation guard 声明的漏网点,`send` 路径有检查此处没有) | 首锁捕获 generation,写前比较 | +| 2 | `astrbot_client.rs:456-459` | 取消/断流路径不调 `finish_stream()`:DB 残留 `streaming=1` 半截消息,重启后重新显示"生成中",未读逻辑误判新未读 | 取消/错误路径统一 finish(Cancelled/Error) | +| 3 | `commands.rs:643-647` + `runtime.rs:568-588` | 发送先入库 user 行再校验/取 client:槽位忙、未连接等失败后消息仍留历史且无失败标记,重试成功再插新行成重复 | 校验通过、确认 client 后再持久化;失败回删或标记 error | +| 4 | `commands.rs:459-461` vs `slots.rs:44-47` | `probe_connection_slot` 不查槽位分配表:同一 Profile 可同时激活双槽,`ProfileAlreadyAssigned` 策略被绕过,双向覆写同一 sticky_session_id;operations 切换守卫也管不到 probe | 激活前校验槽表分配 | +| 5 | `astrbot_client.rs:128-133, 431-438` | `expected_server_instance_id` 校验是死代码:Mutex 初始化为期望值后无任何写入点,比较恒 false —— 服务器身份校验呈"有校验"假象(AstrBot 无身份端点是客观限制) | 删除死校验或接入可观测特征;文档明示身份为 URL 派生 | +| 6 | `astrbot_client.rs:383-388` | `download_attachment` 先整体读入内存再查 16MiB 上限:异常/恶意服务端(尤其 `allow_insecure_http` 链路)可内存放大到 GB 级 | 先查 Content-Length,流式累读超限即断 | +| 7 | `gateway_client.rs:121-126` | `health()` 不带 bearer(SSE 带):health 需鉴权则合法 token 恒 401;health 免鉴权则坏 token 激活照样成功,激活期 AuthExpired 分支形同虚设 | health 与 SSE 一致附带 token | +| 8 | `gateway_client.rs:237-238` | `run_reconnecting` Ok 分支把退避重置回 100ms:服务端"接受即优雅关流"(LB 摘除/维护)时进入 \~10 次/秒热重连;与 P1-1 的 30s 超时叠加成周期性风暴 | 仅在"连接存活超阈值且收到过事件"时重置退避 | +| 9 | `profiles.rs:213-218` | 删除 Profile 不清理 Credential Manager:凭据引用(随机 UUID target)永久孤儿,应用内再无途径删除 | 删除前读取引用并 `store.delete`;启动时孤儿对账 | +| 10 | `auth.rs:13-20`、`credentials/mod.rs:11-20` | 承载明文 `password/secret/totp` 的 IPC 结构体裸 `derive(Debug)`,与注释"never logged"矛盾;当前无 `{:?}` 调用点,属一步之遥的泄露隐患(`SecretCredential` 有手写红act Debug,标准不一致) | 手写 Debug 或改 `secrecy::SecretString` | +| 11 | `diagnostics/config.rs:213/232/259` | YAML/INI/.env 只做正则脱敏(无结构化 key 脱敏,JSON/TOML 有):叠加 P1-18 正则缺口,`token:` 值可泄露 | 三格式补按 key 的行级结构化脱敏 | +| 12 | `database/mod.rs:524 vs 556` | 键模型不一致:`chat_sessions` 主键含 `account_id`(查询却不带),`chat_messages` 主键不含——`account_id` 处处硬编码 `local-default`,未来引入多账号即破隔离 | 统一键模型(都含或都删) | +| 13 | `commands.rs:341` | 服务端省略 `message_id` 时 delta 落库以逐事件唯一的 `event_id` 兜底:一条回复被拆成 N 行消息(测试恒带 message_id 掩盖此路径;前端同款回退 `ChatPanel.tsx:916-917`) | mapper 为无 id 流合成稳定流内 id | +| 14 | `lib.rs:544-556` + `commands.rs:267-278` | 事件通道双合法消费者(转发循环 vs `drain` 命令)互相抢事件,且 drain 路径不落库;双槽共享一条 256 深度队列,一槽洪峰背压另一槽(前端当前未调 drain,属暴露的 footgun) | 移除 drain 或改广播;每槽独立通道 | +| 15 | `envelope.rs:171` + `gateway_client.rs:177` | 信封及全部只读 payload `deny_unknown_fields` + Json 错误非终态:网关加一个附加字段 → 解析失败 → 以旧 Last-Event-ID 重连 → 服务端重放同一坏事件 → 永久卡死循环 | 非安全 payload 移除 deny(ToolProposal/Result 保留)或解析失败跳过并推进游标 | +| 16 | `astrbot.rs:17-43` vs DB/文档 | `TransportKind` 两套线上拼写:serde/前端/schema 用 `astr-bot-open-api`,`as_str()/parse()`/SQLite/README 用 `astrbot-openapi`——两条通道暂各自闭环,任何交叉即断 | 统一 `#[serde(rename)]` 为 `astrbot-openapi`,同步前端 enum 与 schema | +| 17 | `astrbot.rs:381-410, 429-444` | mapper 边界:重复 complete 帧产生第二条 completed 事件;complete 后迟到 plain 会以尾块覆盖全文(丢字)——需服务端乱序才触发 | complete 后记录 per-message 完成标记 | +| 18 | `astrbot.rs:336-353` | 非图片媒体(record/file/video)的 `attachment_saved` 被静默丢弃,机器人发的语音/文件用户完全不可见;`pending_media` 仅存一个,双图交错丢第一张 | 非图片输出通用占位标记;pending 改 FIFO | +| 19 | `mock-gateway routes.rs:196-206`、`state.rs:161-173`、`config.rs:29-31` | mock 三缺陷:broadcast `Lagged` 直接 continue(静默丢事件不断流,soak"无丢失"结论不可信);Last-Event-ID 未命中静默零重放(无 gap 信号);同类双实例 `server_instance_id` 恒等(身份校验失去分辨力) | Lagged 改断流;未命中发 gap 事件;instance_id 掺端口 | +| 20 | `ChatPanel.tsx:73-74, 181-187, 264-293` | 未读三连:list 与 mark-read 竞态使徽标回弹不清;无活动会话时回退 `storedSessions[0]` 把从未打开的会话误标已读;他槽未读不随事件实时更新 | mark-read 后再取列表;仅真实 activeSessionId 才标读;事件驱动他槽未读 | +| 21 | `ChatPanel.tsx:468-475` | `retryMessage` 只滤 slot 不滤 session:切换会话后重试可把 A 会话的内容重发进 B 会话 | 加 `sessionId === activeSessionId` 过滤 | +| 22 | `ChatPanel.tsx:435-457` + `runtime.rs:626-633` | 停止生成:已收半截内容被标 `error:true` 按失败样式渲染;Rust 取消返回 `Err{code:"cancelled"}` → 乐观用户消息也被标失败并弹横幅(叠加 P1-16 显示 `[object Object]`) | 按 code 区分 cancelled;保留已收内容为正常消息 | +| 23 | `ChatPanel.tsx:920-925, 77` | 事件→消息归并键只用 `slot+sessionId+id`,丢弃事件自带的 `profileId/serverInstanceId`,与"四元组本地键"规范不符;同槽换绑 Profile 后迟到事件可并入新 Profile 消息流 | 归并键与 `ChatMessage` 补全二元组 | +| 24 | `styles.css:3116-3139` | 消息操作按钮 `visibility:hidden` + 依赖 `:focus-within` 显示 = 键盘死锁(不可聚焦 → 永不显示);触屏有兜底,桌面键盘没有 | 去掉 visibility,仅用 opacity/pointer-events | +| 25 | `ChatPanel.tsx:607-620, 711-717` | tablist:箭头切换不移动焦点(roving tabindex 失效);未选中 tab 的 `aria-controls` 指向不存在的 panel;`aria-busy` 挂在 `aria-live` 容器上,发送期间压制读屏播报 | 切换即 focus 目标 tab;panel 常驻;busy/live 分离 | +| 26 | `CredentialEnrollmentCard.tsx:34-80` | 登记/登录失败路径不清空 `secret/password`(明文留在 state 与受控 input DOM);`invoke` 返回值为全库唯二未过 zod 的裸类型断言 | `finally` 清空;返回值补 schema | +| 27 | `ChatPanel.tsx:343-354` | 首次 `refresh()` 失败即永不建立轮询("状态不可用"直到重挂载);且 snapshot schema `.strict()`——Rust 加任一字段即触发此永久离线路径 | 失败也建(退避)轮询;strict 失败要有兜底与告警 | +| 28 | `ChatPanel.tsx`(全文件无 scroll 代码)、`540-585` | 无自动滚动:流式生成发生在视口外;语音识别/朗读无卸载清理:切页后麦克风继续、`onresult` 向已卸载组件 setState、朗读不 cancel | 底部锚点+接近底部才跟随;unmount 停止 recognition/synthesis | +| 29 | `astrbot_client.rs:554-565` | JWT `exp` 无时钟裕度(临期 token 过检后立即 401);缺 exp/解析失败一律 fail-open(有 401 兜底,可用性取向合理但窗口偏乐观) | `exp <= now+30s`;不可解析打 debug 日志 | +| 30 | `DesktopPetView.tsx:139-148` + `tauri.conf.json` | 桌宠挂载即以硬编码覆写窗口偏好(`positionMode:"edge", monitorIndex:0, alwaysOnTop:true`),应用内叠层模式也触发——用户设置被持续踩掉;且 `alwaysOnTop:true`(含 tauri.conf 默认)**违反"气泡/桌宠不默认置顶"的产品红线**(implementation-queue 隔离基线) | embedded 跳过;读取既有偏好增量提交;默认置顶改 false | +| 31 | `tauri.conf.json` build 段 vs `package.json` | 工程口径漂移:Tauri CLI 回调 `npm run dev/build` 而工程锁 `pnpm@11.9.0`(双包管理器混跑);engines 钉死 node `>=24.17 <25` 但 `@types/node` 是 24.13;文档口径 React 18 而实际 React 19.2.7 | tauri.conf 改 pnpm;engines 对齐;文档更新 | + +### P3:低危与小缺陷(18 项) + +| \# | 位置 | 问题 | 建议 | +| --- | --- | --- | --- | +| 1 | `astrbot.rs:495-499, 449` | 所有 astrbot 事件 `timestamp` 恒为 `1970-01-01T00:00:00Z`,心跳 interval 硬编码 1000 | 调用方注入时钟 | +| 2 | `astrbot.rs:502-508` | `server_instance_id` 用 `DefaultHasher` 派生并持久化,std 明示跨版本无稳定承诺——换工具链后同 URL 新旧键空间分裂(仓库已依赖 sha2) | 改 sha2 截断 + 一次性兼容映射 | +| 3 | `astrbot_client.rs:544-552` | `urlencoding_username` 对非 ASCII `ch as u8` 截断编码(潜在缺陷:当前被 `profiles.rs:250-256` 的 ASCII 校验挡住;一旦放宽用户名规则即升 P1,文档恰有"最终确定命名规则"待办) | 改逐字节百分号编码 | +| 4 | `astrbot_client.rs:456-458` | 取消消息把连接状态置 Disconnected 再改回 Connected,托盘/前端可见闪烁 | 取消不动连接状态 | +| 5 | `tauri.conf.json` + `lib.rs:378-389` | CSP `connect-src` 放行 `http://127.0.0.1:*`(渲染层可直连本地端口);`check_network_target` 向所有窗口暴露限速 TCP 探测——能力面收敛问题 | 生产移除 127.0.0.1:\*;诊断目标限已存 profile host | +| 6 | `auth.rs:179-198` | 凭据轮换顺序:先删旧、后写 DB——DB 更新失败时引用悬空需重新登录 | 写新→落库→删旧,失败回滚 | +| 7 | `runtime_guards.rs:28-51` | operations 切换守卫无生产调用方(仅测试引用),`connection_policy_status` 上报一个永远解锁的守卫 | 工具管线落地时接线;先在状态中标注未激活 | +| 8 | `lib.rs:270-276` | 退出走 `std::process::exit(0)`:跳过 Drop,遗留 -wal/-shm、可能丢最后一段日志 | 退出前 deactivate 双槽并 flush | +| 9 | `astrbot.rs:267-269, 469-477` | `session_id` 帧 data 为对象时会把整个 JSON 转储当会话 ID 持久化(现网帧形态未触发) | Object 分支提取 `session_id/id` 键 | +| 10 | `App.tsx:129` | 独立桌宠窗口渲染 lazy 组件无 Suspense 边界(React 18+ 根级挂起容错=首帧空白而非白屏,但违反 React 文档要求且整根阻塞) | 补 `` | +| 11 | `App.tsx:171` + 两套测试 | 导航图标未 `aria-hidden`,读屏播报"◎ 连接";e2e/单测硬编码含图标的可及名,换图标即双杀 | 图标 aria-hidden;选择器用语义文本 | +| 12 | `DesktopPetView.tsx:150-160` + `styles.css:3086-3090` | reduced-motion 未约束 JS 帧循环(`setInterval` 驱动,CSS `animation:none` 是死规则);`image.onerror` 未清理;canvas 未按 DPR 放大 | matchMedia 停帧;补清理 | +| 13 | `ChatPanel.tsx:447/482/513` 等 | 用户可见文案中英文混杂("Generation stopped." / "image loading" / 英文 aria-label 混在中文 UI 中) | 统一文案表 | +| 14 | `App.tsx:562-567`、`SettingsPages.tsx:165-192`、`ProfileManager.tsx:570-575` | 死控件与标签错误:活动策略下拉无 onChange;jwt 认证显示为"设备 Token 引用";槽位状态裸英文枚举(ChatPanel 有中文映射未复用);诊断输入 `Number()` 产 NaN 直发后端 | 逐项补齐 | +| 15 | `soak.rs:101-103`、`dual_instance.rs:264` | 测试 SSE 助手只认 `"data: "`(带空格)且 `.unwrap()`:axum 换排版即全挂成超时;`acknowledged_event_ids` 无界增长 | strip_prefix("data:")+trim;ack 加上限 | +| 16 | `App.test.tsx:148-172` | 所有用例的 mock 缺 `close_pet_window` → 全局错误横幅由旁路触发,"IPC 不可用"断言存在假阳性通道 | mock 补齐;断言具体文案 | +| 17 | `tsconfig.app.json`、`eslint.config.js`、`vite.config.ts` | 缺 `noUnusedLocals/noUncheckedIndexedAccess`;关闭 `react-hooks/set-state-in-effect` 且无 jsx-a11y;`usePolling:true` 白耗 CPU;vitest 无 coverage 配置 | 逐项收紧 | +| 18 | `mock routes.rs:178-188` | 订阅与重放快照的间隙内事件双下发(at-least-once);并发 publish 广播顺序可与 sequence 倒置——mock 内部竞态,单线程测试不触发 | push+send 同临界区或文档注明 | + +* * * + +## 三、代码优化建议 + +### 性能热点(按收益排序) + +1. **前端渲染管线**:`ChatPanel` 每 500ms 全量轮询 `connection_runtime_status` 且 `setStatus` 恒新引用 → 整面板重渲染;`activeMessages` 的 `useMemo` 依赖整只 `status` 对象每轮失效;`MessageContent` 无 `React.memo`,每轮全量重新解析 Markdown;`applyRuntimeEvents` 对每个 delta 全量浅克隆消息数组;`messages` 跨会话驻留从不修剪。修法集中且低风险:依赖改标量(`activeSessionId`)、`React.memo`、命中才克隆、轮询改事件驱动或放宽。 +2. **spritesheet 内联**:`DesktopPetView.tsx:10` 以 `?inline` 把 1536×3120 PNG(磁盘 3.9MB,base64 后 \~5.2MB)内联进 lazy chunk;同目录已有 573KB 的 WebP 却未使用(manifest 与 import 都指 PNG)。改普通资源引用 + WebP,chunk 直降 \~90%,"代码分割"收益才真正成立(app-ui 模式主窗口默认也会加载该 chunk)。 +3. **附件二进制走 JSON IPC**:前端 `Array.from(new Uint8Array(...))` + Rust `Vec`——16MiB 文件变 \~1670 万元素数字数组(膨胀 3–4 倍、主线程长任务、Rust 侧再 `bytes.clone()` 一份)。Tauri 2 原生支持 raw body / `tauri::ipc::Response` 二进制通道,上传下载双向改造。 +4. **轮询叠加**:StatusBubble 每 1s 发 3 个 invoke、托盘 1s 轮询、ProfileManager 2s 轮询——统一改为订阅 `connection-runtime-event` + 低频兜底。 +5. **styles.css 分层腐化**:3388 行按五代叠写(基础层→OS 亮色媒体查询→data-theme 手工枚举→`--ui-*` token→触控层),约 40% 是被覆盖的死层;`.chat-error` 定义 5 次;`--muted-text/--ink/--accent` 等幽灵 token 全库无定义永走 fallback(暗色气泡里链接恒亮色)。建议以 `--ui-*` 为唯一 token 源做一次合并,删除 OS 亮色块,引入 stylelint 防回归。 + +### 结构与架构 + +- **事件出口**:单条 256 深度 mpsc + 双消费者设计(见 P2-14)改为"每槽独立通道 + 唯一持久化点 + 广播 emit",同时消除背压串扰与丢事件 footgun。 +- **发送期客户端独占**:`send` 用 `client.take()` 令并发的 sessions/capabilities/upload/download 在长流期间全部误报"未连接"(`AstrBotClient` 本身可 Clone)。改 clone + 以 `message_cancellation` 存在性串行化发送。 +- **错误展示层**:抽出共享 `errorMessage()`(识别 `{code,message}`),ChatPanel/SettingsPages/CredentialEnrollmentCard 统一接入(P1-16 的治本)。 +- **契约治理**(本次教训的制度化):Rust 序列化输出 → JSON 样本夹具 → 前端 zod 契约测试三点一线;`export_schemas` 比对进 `cargo test`;`TransportKind` 拼写统一后在 CI 加 grep 断言。 + +* * * + +## 四、功能实现完整度 + +### 4\.1 对照 13 项 roadmap 声明(implementation-queue.md 2026-07-21) + +| \# | 声明 | 代码现状 | 判定 | +| --- | --- | --- | --- | +| 1 | 启动自动连接 | 已实现(逐 profile 独立 try、日志只记类别);但串行 + 全局锁使"逐槽独立"在时间上不成立(P1-4),无前端提示(文档已自认) | ⚠️ 基本成立 | +| 2 | 凭据轮换 + JWT | 主线成立(Credential Manager、一次性 secret、JWT 登录/过期识别/重登录提示);隐患:Debug 派生(P2-10)、孤儿凭据(P2-9)、轮换顺序(P3-6) | ⚠️ 基本成立 | +| 3 | 服务器身份保护 | desktop-v1 侧成立(bind 强校验);**AstrBot 侧是死代码**(P2-5),身份仅 URL 哈希派生 | ❌ 部分虚假 | +| 4 | 快速聊天窗口 | 单实例、几何持久化、夹取、共享 runtime 均在,质量好 | ✅ | +| 5 | 托盘与状态气泡 | 成立;气泡走 1s 轮询(优化项) | ✅ | +| 6 | 桌宠状态与素材 | **三处断裂**:capability 缺失致事件联动全哑(P1-13)、素材导入正则全拒(P1-12)、偏好被硬编码覆写且默认置顶违反产品红线(P2-30) | ❌ 名存实亡 | +| 7 | 多显示器/游戏策略 | 几何、安全边、受限前台/进程检测在;游戏模式切换依赖的 pet 窗口 IPC 因 P1-13 失效 | ⚠️ | +| 8 | 语音交互(Web Speech MVP) | 可用;无卸载清理(P2-28)、朗读读原始 Markdown | ⚠️ | +| 9 | 主动消息 | 事件类型与未读持久化在;**AstrBot 传输无后台事件流,proactive 实际仅 mock 可达**——对真实服务器该功能不可用 | ❌ 仅 mock 成立 | +| 10 | 聊天可靠性 | 会话隔离持久化与切换去重在;但 P0-1、P1-2/3/6、P2-2/3/13 直接命中此项 | ❌ 与声明差距最大 | +| 11 | 日志/诊断脱敏 | 机制健全;裸 token/JWT 缺口(P1-18)、YAML/env 弱脱敏(P2-11) | ⚠️ | +| 12 | Release 构建 | 成立(unsigned NSIS) | ✅ | +| 13 | 验收覆盖 | 门槛存在但关键路径全在盲区(见第五节) | ⚠️ | + +### 4\.2 安全铁律符合性 + +| 铁律 | 判定 | 备注 | +| --- | --- | --- | +| 凭据只进 Credential Manager,不入 DB/日志/前端 | ⚠️ 主线成立 | 缺口:P1-18、P2-10、P2-9 | +| 日志必须脱敏 | ❌ 有实洞 | 裸 `token=`/JWT 可原文透出(P1-18) | +| 不暴露任意 Shell | ✅ | 全仓 0 处 Command/ShellExecute | +| 文件事务 plan→dry-run→确认→复制→校验→原子提交、保源不覆盖 | ✅ | 名副其实;暂停残留 `.part` 为小疵 | +| 本地键 ≥ profile_id+server_instance_id+conversation_id | ✅ 数据层 / ⚠️ UI 层 | DB 主键超额达标;前端归并键丢二元组(P2-23) | +| companion 默认无本机工具权限;operations 六道闸门 | ➖ | 工具执行管线未开始(与"暂不进入实现"一致);闸门零代码,实现前不得放开能力面;guard 空转(P3-7) | +| 气泡/桌宠不默认置顶 | ❌ | `desktop-pet` 窗口与偏好硬编码 `alwaysOnTop:true`(P2-30) | + +### 4\.3 "名存实亡"清单(有 UI/字段/命令,无实际效果) + +证书指纹绑定(录入校验齐全、TLS 验证零接入,用户获得虚假安全感——文档列为外部前置,但录入通道已开放,建议标注"暂不生效");AstrBot 服务器身份校验(P2-5);operations 切换守卫(P3-7);`drain_connection_runtime_events` 命令(前端不用,用则丢事件+丢持久化);远端会话列表与模型能力(被 P1-7 契约失配掐断);桌宠事件联动与素材导入(P1-12/13);"活动策略"下拉(P3-14)。 + +* * * + +## 五、测试覆盖缺口 + +现状:Rust 工作区 67 测试(DB 迁移/未读/delta 合并/槽隔离、profile/slot/credential IPC、redaction、mapper 单流 8 例、mock 双实例集成)+ Vitest 9 + Playwright 5,全绿。**全绿与带病并存的原因是关键路径系统性缺位**: + +1. **astrbot 传输零集成测试**——没有任何测试起假 `/api/v1/chat` SSE 服务端跑 `AstrBotClient`。P0-1、P1-2/3、P2-2 全在盲区。最小补法:同一 client 连续两次 `send_chat_stream` 的单测即可暴露 P0-1。 +2. **契约测试缺 null 样本**——`types.test.ts` 恰好没测 `sessionId:null/displayName:null/name:null`;一条"用 Rust 真实序列化输出回放"的测试可拦下全部 P1-7。建议以 serde_json 快照做双端共享夹具。 +3. **ChatPanel 零测试**(最重组件):delta 归并、切槽隔离、未读清零、重试/停止边界、附件上限。 +4. **脱敏测试用 known-secret 做 canary**,掩盖了正则不认裸 token 的事实(P1-18);需要"无 known_secrets 下 `token=` 必须被脱敏"的断言。 +5. `DualSlotRuntime` 仅 2 个参数校验测试:无 activate/send/cancel/switch 竞态、无"激活期间另一槽命令阻塞"回归(P1-4、P2-1)。 +6. 未知事件类型/附加字段的客户端行为无测试(P1-5、P2-15);Last-Event-ID 断点续传虽有 mock 支持但客户端请求头未被断言;重连退避行为(P2-8)无测试。 +7. `listen` 的 mock 同步返回 cleanup,掩盖注销竞态(P1-10)——改为延迟 resolve 并断言注销次数。 +8. `petPackManifestSchema.parse(内置 manifest.json)` 一条测试即可抓住 P1-12;MessageContent 的 `javascript:` 链接、未闭合代码块也应有用例。 +9. 长会话(\>200 条)分页顺序无测试(P1-6);缺 message_id 的流式帧无测试(P2-13)。 +10. soak 断言只有计数+身份,不校验 sequence 单调无缺口——mock 的 Lagged 静默丢失(P2-19)不会使其失败,"30 分钟无丢失"结论目前不可信。 + +* * * + +## 六、修复路线图 + +**第一批 · 发布阻断(建议本周内,全部为小改动)** +P0-1(事件 ID 加盐/去重下沉)→ P1-7 三连 `.nullish()` + `rename_all` → P1-1 流式专用 Client → P1-12 正则一字符 → P1-13 capability 加一行 → P1-14 CSP 加 `blob:` → P1-15 href 白名单 → P1-16 errorMessage 共享 → P1-17 乱码文案。同批补三条回归测试:同 client 连发两条、null 契约回放、manifest 自解析。 + +**第二批 · 正确性与安全(进入 alpha.3 前)** +P1-2 重试语义收窄、P1-3 UTF-8 字节缓冲、P1-4 探测出锁+可取消、P1-5/P2-15 未知事件跳过、P1-6 历史取最新 N、P1-10 listen 竞态、P1-11 附件/错误按槽隔离、P1-18+P2-11 脱敏补洞、P2-2 finish_stream、P2-3 先校验后入库、P2-20/21/22 未读与重试/停止链路、P2-30 置顶红线。 + +**第三批 · 健壮性与工程化** +其余 P2/P3、性能五热点、契约治理制度化(schema 比对进 cargo test、TransportKind 统一、双端夹具)、mock 网关三缺陷、测试缺口按第五节补齐。 + +* * * + +## 附录 A · 已剔除的误报与降级说明 + +| 原始发现 | 处理 | 理由 | +| --- | --- | --- | +| "aemeath-spritesheet.png / src-tauri/icons 缺失,构建必败" | **剔除** | 审计快照未包含二进制资源;设备上文件实际存在(PNG 3.9MB、WebP 573KB、icons 全套)。保留的是 `?inline` 体积问题(优化 §2) | +| "桌宠窗口无 Suspense → 白屏"(P0) | **降级为 P3-10** | React 18+/createRoot 对初次挂载的根级挂起会延迟提交(短暂空白后正常渲染),非崩溃;仍建议按 React 文档补边界 | +| "username 百分号编码截断 → 会话串线"(P1) | **降级为 P3-3** | `profiles.rs:250-256` 强制 remote_username 为 ASCII 字母数字 3–32 位,非 ASCII 分支当前不可达;属纵深缺陷,放宽命名规则前必须先修 | +| "AstrBot 附件字段被服务端忽略" | **保留为 P1-9,置信度中** | 依据为仓库内真实协议探针文档的字段清单,静态审计无法接触真实服务器终证;已注明需真机验证 | + +## 附录 B · astrbot SSE 映射器边界推演摘要 + +对 `astrbot.rs` 状态机手工推演 14 组输入序列的结论:纯 complete、纯 delta+finish、delta+complete reconcile、空 complete、跨消息切换、error 携带部分文本——**均正确**;重复 complete(事件层重复)、complete 后迟到 plain(尾块覆盖全文)、缺 message_id(每 delta 一气泡)、多行 data / 坏 JSON 行(整流中止且无 completed)、同 client 二次发送(P0-1)——**均有缺陷**,已分列 P0-1、P2-13/17、P1 组。取消与解析错误两条路径不调 `finish_stream` 是悬挂 streaming 状态的共同根因。 + +## 附录 C · Mock 网关与真实 AstrBot 的关键差异(影响测试可信度) + +流模型(长连+重放+ack vs 请求级 SSE 无重放——基于 mock 验证的重连/续传/去重对 astrbot 传输完全不适用,P0-1 因此漏网);事件 ID(服务端单调分配 vs 客户端合成每请求复位);消息形态(mock 永不出现纯 complete/无终止帧/error/attachment_saved);认证(双 token+refresh vs 静态 Key/7 天 JWT,refresh 代码对真实后端是死路径);身份(/server-info 权威 vs URL 哈希自证);会话(无列表 vs username+session 双键有列表);工具流(mock 周期推 tool.proposal,现网不存在)。**结论:凡只被 mock 集成测试覆盖的行为,对真实 AstrBot 都应视为未验证。** + +## 附录 D · 审计方法与覆盖率 + +设备快照(2026-07-26 拉取)→ 云端工作区重建目录树 → 4 路并行深度静审(每路独立通读职责文件全文并给出逐字证据)→ 主审对全部 P0/P1 与关键 P2 回读源码逐条复核(含 1 项 node 运行时实测、2 项跨路交叉印证)→ 按"宁缺毋滥"原则合并去重。因目标平台为 Windows,本环境未执行编译与测试套件;windows-rs unsafe 调用(credential_manager/capture/uia/event_log)为人工推演,结论为"未见泄漏/越权,质量高",建议在 Windows CI 补运行时验证。行号基于 2026-07-21/22 版本文件,后续提交可能偏移。