比较提交

..

没有共同的提交。573f9f793be60a8e2c6da5d2682f2b1d6ba32623 和 785f125efc1fbad378133451fd54a561963a8b84 的历史完全不同。

共有 24 个文件被更改,包括 122 次插入 和 1941 次删除

查看文件

@ -28,24 +28,6 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
## [Unreleased] ## [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 ### Changed
- Synchronized the 13-item roadmap status with the actual P02 implementation state. - Synchronized the 13-item roadmap status with the actual P02 implementation state.
@ -78,21 +60,6 @@ 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. - Runtime operations switch guard that blocks operations slot changes while an operations task is active.
- Duplicate `server_instance_id` warnings without silently merging Profiles. - 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 ### Security
- Kept credentials and native capabilities in Rust; the React capability set remains `core:default` only. - Kept credentials and native capabilities in Rust; the React capability set remains `core:default` only.

查看文件

@ -81,11 +81,7 @@ pub struct AstrBotChatRequest {
} }
/// A model/provider configuration exposed by AstrBot. /// A model/provider configuration exposed by AstrBot.
///
/// Serialized towards React, so the field names must match the frontend
/// contract in `src/features/chat/types.ts`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AstrBotModelOption { pub struct AstrBotModelOption {
pub id: String, pub id: String,
#[serde(default)] #[serde(default)]
@ -225,7 +221,6 @@ struct PendingMedia {
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct AstrBotStreamMapper { pub struct AstrBotStreamMapper {
server_instance_id: String, server_instance_id: String,
stream_id: String,
session_id: Option<String>, session_id: Option<String>,
active_message_id: Option<String>, active_message_id: Option<String>,
accumulated: String, accumulated: String,
@ -236,17 +231,9 @@ pub struct AstrBotStreamMapper {
} }
impl AstrBotStreamMapper { impl AstrBotStreamMapper {
/// Creates a mapper for a single AstrBot chat request stream. pub fn new(server_instance_id: impl Into<String>) -> Self {
///
/// `stream_id` must be unique per request for the lifetime of the client
/// that consumes the mapped events. The mapper restarts its sequence
/// counter at zero for every stream, so without a per-stream component the
/// generated event ids of a second request would collide with the first
/// request's ids and be discarded by the client-side deduplicator.
pub fn new(server_instance_id: impl Into<String>, stream_id: impl Into<String>) -> Self {
Self { Self {
server_instance_id: server_instance_id.into(), server_instance_id: server_instance_id.into(),
stream_id: stream_id.into(),
..Self::default() ..Self::default()
} }
} }
@ -265,18 +252,7 @@ impl AstrBotStreamMapper {
/// Call when the HTTP stream ends without a terminal server frame. /// Call when the HTTP stream ends without a terminal server frame.
pub fn finish_stream(&mut self) -> Vec<GatewayEvent> { pub fn finish_stream(&mut self) -> Vec<GatewayEvent> {
self.finish_stream_with(FinishReason::Stop) self.complete_if_needed(FinishReason::Stop)
}
/// Terminates the in-flight message with an explicit reason.
///
/// Cancellation and transport errors must go through this instead of
/// returning early: without a `MessageCompleted` event the message stays
/// `streaming = 1` in the database and reappears as "generating" after a
/// restart. Returns an empty vector when no assistant text is pending, so
/// it is safe to call unconditionally on every exit path.
pub fn finish_stream_with(&mut self, reason: FinishReason) -> Vec<GatewayEvent> {
self.complete_if_needed(reason)
} }
fn map_frame(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> { fn map_frame(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
@ -476,10 +452,7 @@ impl AstrBotStreamMapper {
fn event(&mut self, message_id: Option<String>, body: GatewayEventBody) -> GatewayEvent { fn event(&mut self, message_id: Option<String>, body: GatewayEventBody) -> GatewayEvent {
self.sequence = self.sequence.saturating_add(1); self.sequence = self.sequence.saturating_add(1);
let event_id = format!( let event_id = format!("astrbot-{}-{}", self.server_instance_id, self.sequence);
"astrbot-{}-{}-{}",
self.server_instance_id, self.stream_id, self.sequence
);
let mut metadata = EventMetadata::new( let mut metadata = EventMetadata::new(
event_id, event_id,
self.server_instance_id.clone(), self.server_instance_id.clone(),
@ -540,7 +513,7 @@ mod tests {
#[test] #[test]
fn maps_live_probe_style_plain_stream() { fn maps_live_probe_style_plain_stream() {
let mut mapper = AstrBotStreamMapper::new("astrbot-test", "stream-a"); let mut mapper = AstrBotStreamMapper::new("astrbot-test");
let lines = [ let lines = [
r#"data: {"type": "session_id", "data": null, "session_id": "desktop-companion-s1"}"#, r#"data: {"type": "session_id", "data": null, "session_id": "desktop-companion-s1"}"#,
r#"data: {"type": "user_message_saved", "data": {"id": 1}}"#, r#"data: {"type": "user_message_saved", "data": {"id": 1}}"#,
@ -585,7 +558,7 @@ mod tests {
#[test] #[test]
fn maps_complete_frame_when_no_plain_chunks_are_emitted() { fn maps_complete_frame_when_no_plain_chunks_are_emitted() {
let mut mapper = AstrBotStreamMapper::new("astrbot-test", "stream-a"); let mut mapper = AstrBotStreamMapper::new("astrbot-test");
let events = mapper let events = mapper
.push_line(r#"data: {"type":"complete","data":"A complete reply","streaming":true,"message_id":"m1"}"#) .push_line(r#"data: {"type":"complete","data":"A complete reply","streaming":true,"message_id":"m1"}"#)
.expect("parse"); .expect("parse");
@ -602,7 +575,7 @@ mod tests {
#[test] #[test]
fn complete_frame_reconciles_partial_plain_chunks_without_duplication() { fn complete_frame_reconciles_partial_plain_chunks_without_duplication() {
let mut mapper = AstrBotStreamMapper::new("astrbot-test", "stream-a"); let mut mapper = AstrBotStreamMapper::new("astrbot-test");
mapper mapper
.push_line( .push_line(
r#"data: {"type":"plain","data":"Hello","streaming":true,"message_id":"m1"}"#, r#"data: {"type":"plain","data":"Hello","streaming":true,"message_id":"m1"}"#,
@ -624,7 +597,7 @@ mod tests {
#[test] #[test]
fn maps_error_frames() { fn maps_error_frames() {
let mut mapper = AstrBotStreamMapper::new("astrbot-test", "stream-a"); let mut mapper = AstrBotStreamMapper::new("astrbot-test");
let events = mapper let events = mapper
.push_line(r#"data: {"type":"error","data":"provider missing"}"#) .push_line(r#"data: {"type":"error","data":"provider missing"}"#)
.expect("parse"); .expect("parse");
@ -640,7 +613,7 @@ mod tests {
#[test] #[test]
fn maps_image_frames_to_persistable_attachment_markers() { fn maps_image_frames_to_persistable_attachment_markers() {
let mut mapper = AstrBotStreamMapper::new("astrbot-test", "stream-a"); let mut mapper = AstrBotStreamMapper::new("astrbot-test");
assert!( assert!(
mapper mapper
.push_line(r#"data: {"type":"image","data":"[IMAGE]happy.png","message_id":"m1"}"#) .push_line(r#"data: {"type":"image","data":"[IMAGE]happy.png","message_id":"m1"}"#)
@ -660,37 +633,6 @@ mod tests {
assert_eq!(delta, "![image](astrbot-attachment://att-1)"); assert_eq!(delta, "![image](astrbot-attachment://att-1)");
} }
#[test]
fn consecutive_streams_do_not_reuse_event_ids() {
// Regression: a client keeps one deduplicator for its whole lifetime,
// while a mapper is rebuilt per request and restarts its sequence at
// zero. Without a per-stream id the second message's events collided
// with the first message's ids and were dropped as duplicates.
let frame = r#"data: {"type":"plain","data":"Hi","streaming":true,"message_id":"m1"}"#;
let collect = |stream_id: &str| {
let mut mapper = AstrBotStreamMapper::new("astrbot-test", stream_id);
let mut events = mapper.push_line(frame).expect("parse");
events.extend(mapper.finish_stream());
events
.into_iter()
.map(|event| event.metadata.event_id)
.collect::<Vec<_>>()
};
let first = collect("stream-a");
let second = collect("stream-b");
assert!(!first.is_empty());
assert_eq!(first.len(), second.len());
for event_id in &second {
assert!(
!first.contains(event_id),
"event id {event_id} was reused across streams"
);
}
}
#[test] #[test]
fn derives_stable_instance_ids() { fn derives_stable_instance_ids() {
let a = derive_astrbot_server_instance_id("http://192.168.31.210:26285/"); let a = derive_astrbot_server_instance_id("http://192.168.31.210:26285/");

查看文件

@ -386,118 +386,3 @@ 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. - Rust fmt, Clippy with warnings denied, workspace tests (67), and workspace check: passed.
- Tauri release build and unsigned NSIS bundle: 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. - 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).

查看文件

@ -1,253 +0,0 @@
# 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<u8>` 缓冲、按 `\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))` 渲染为文本而非 `<a>` |
| **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<u8>`,按 `\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<ChatSlot, …>` | 陪伴槽上传附件 → 切运维 → 发送,附件不跟随;运维错误横幅不出现在陪伴槽 |
| **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` 的验证记录。

查看文件

@ -1,289 +0,0 @@
# 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 字节/字)被切在字符中间即产生 `<60>` 且随 delta 入库;断流/取消场景永久保留。这是面向中文用户客户端的高频显性缺陷。修复:以 `Vec<u8>` 缓冲,按 `\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<String>` 无 `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<ChatSlot, …>` 或切槽清空。
**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:` 可直达 `<a>`**
`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 文档要求且整根阻塞) | 补 `<Suspense fallback>` |
| 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<u8>`——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=<jwt>` 必须被脱敏"的断言。
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 版本文件,后续提交可能偏移。

查看文件

@ -1,222 +0,0 @@
# R1 / R2 执行状态
2026-07-26 · 分支 `feat/p02-dual-connections` · 基线 v0.1.0-alpha.2
> 配套文档:[full-source-audit-2026-07-26.md](./full-source-audit-2026-07-26.md)(68 项发现)、
> [fix-queue-2026-07-26.md](./fix-queue-2026-07-26.md)(8 个批次的执行队列)。
> 本文只记录**做了什么、没做什么、验证到什么程度**,不重复队列正文。
---
## 一、总览
| 批次 | 项数 | 状态 | 门槛验证 | 真机验证 |
| --- | --- | --- | --- | --- |
| R1 发布阻断批 | 9 | 已完成 | 已通过 | **未做** |
| R2 传输层批 | 4 | 已完成 | 已通过 | **未做** |
| R3 隔离与状态正确性 | 6 | 未开始 | — | — |
| R4 数据与凭据安全 | 6 | 未开始 | — | — |
| R5 协议健壮与契约治理 | 9 | 未开始 | — | — |
| R6 体验、无障碍与产品红线 | 10 | 未开始 | — | — |
| R7 性能与工程化 | 8(1 项已提前完成) | 未开始 | — | — |
| R8 剩余 P3 | 16(1 项已提前完成) | 未开始 | — | — |
**已完成 15 项,剩余 53 项。** 共 10 个提交,工作区干净。
---
## 二、已完成
### R1 · 发布阻断批(9 项)
这批改动由上一个会话写入仓库但**从未编译过**。本次首次跑完整门槛,暴露并修复了 2 处真实失败。
| ID | 来源 | 内容 |
| --- | --- | --- |
| F-01 | P0-1 | `AstrBotStreamMapper` 每流重置 sequence,而 `seen_event_ids` 挂在 client 上跨请求存活,导致同一连接第二条消息起助手回复被去重器整体吞掉。事件 ID 加入每请求唯一的 `stream_id`。 |
| F-02 | P1-12 | 宠物素材包 manifest 正则 `\\.` → `\.`,此前拒绝一切合法素材包(含仓库自带示例)。 |
| F-03 | P1-13 | `desktop-pet` 加入 capability 窗口清单,此前该窗口全部 IPC 与事件监听被 ACL 静默拒绝。 |
| F-04 | P1-14 | 生产 CSP `img-src` 追加 `blob:`,此前发行版聊天附件图全部被拦。 |
| F-05 | P1-15 | Markdown 链接协议白名单(http/https/mailto),非法协议降级为纯文本,`rel` 补 `noopener`。 |
| F-06 | P1-7a | 五处 `.optional()` → `.nullish()`,修复事件、远端会话、模型能力三条链路因 Rust `null` 而静默失效。 |
| F-07 | P1-7b | `AstrBotModelOption` 补 `rename_all = "camelCase"`,此前前端 `isDefault` 恒 undefined。 |
| F-08 | P1-16 | 抽出共享 `errorMessage()`,此前 9 处 IPC 失败一律显示 `[object Object]`。 |
| F-09 | P1-17 | 恢复 6 处乱码文案与 1 处乱码 `aria-label`。 |
**门槛暴露的 2 处失败(本次修复)**
1. `npm run typecheck` —— `ChatPanel.tsx` `TS2345`。F-06 把 `updatedAt` 放宽为 `.nullish()` 后,
`string | null` 流进了 `formatSessionTime(value?: string)`。形参放宽为 `string | null`
(函数原有的 falsy 判断已覆盖 `null`)。**这正是队列文档「接手 R2 前必须先做的事」第 4 条预警的
`.nullish()` 向下游传播。**
2. `npm run lint` —— `react-refresh/only-export-components`。F-05 把 `safeLinkHref` 作为非组件导出
放进了 `MessageContent.tsx`;仓库用 `--max-warnings 0`,warning 即失败。已移到
`src/lib/safeLinkHref.ts`。
预警清单中的另两项(`astrbot.rs` 新测试闭包借用、`errorMessage()` 接入点类型)实测无问题。
**补齐的缺失测试**:F-05 的验收条件写明需要 `[x](javascript:alert(1))` 单测,但该测试从未写过。
已新增 `src/features/chat/MessageContent.test.tsx`(4 例:`javascript:`、`data:`、正常 https 链接
带 `noopener`、相对路径不被伪装成绝对链接)。
### R2 · 传输层批(4 项)
四项都在同一个流循环里,按队列要求串行落地。
| ID | 来源 | 内容 |
| --- | --- | --- |
| F-10 | P1-1 | 每个 client 拆成 REST(保留总时限 120s / 30s)与流式(**不设** `.timeout()`,改 `read_timeout` 120s / 90s + `tcp_keepalive` 60s)。`Client::timeout` 是「请求开始到响应体读完」的总时限且在消费 `bytes_stream()` 期间持续生效,此前 desktop-v1 长连接每 30 秒必断(心跳无法续命),AstrBot 超过 120s 的生成被中途截断。已从 vendored reqwest 0.13.4 源码确认 `read_timeout` 语义为「每次读成功后重置」。 |
| F-11 | P1-3 | 新增 `SseLineBuffer`:`Vec<u8>` 缓冲、按 `\n` **字节**分行、逐行解码。此前逐 chunk `from_utf8_lossy` 会把跨 chunk 的多字节字符打成 `U+FFFD` 并随 delta 入库。 |
| F-12 | P1-2 | `should_retry_astrbot` 收窄为 `reqwest::Error::is_connect()` 唯一可重试;新增 `AstrBotClientError::StreamInterrupted` 标记「响应已开始后断流」,经 `astrbot_send_error()` 映射为前端可见的 `streamInterrupted` 码供手动重试。此前响应流中断被当作未送达整条重发,`/api/v1/chat` 无幂等键,会在会话里产生重复提问与重复回答。 |
| F-13 | P2-2 | 取消 / chunk 错误 / mapper 错误 / 行溢出四条路径统一走新的 `finish_and_fail()` → `finish_stream_with(Cancelled \| Error)` 并 dispatch。此前这些路径不发 `MessageCompleted`,DB 残留 `streaming = 1`,重启后重新显示为「生成中」。 |
**顺带并入的两项**
- **F-56**(R8 · P3-4):取消不再把连接置 `Disconnected` 再置回。它就在为 F-13 重写的那一行上,
队列本身标注该项「可随手带入相邻批次」。
- **F-49**(R7 · 优化 §2):`send_slot_message` 由 `client.take()` 改 `clone()`,并以
`message_cancellation` 存在性串行化发送(并发发送返回 `slotBusy`)。提前的理由:另外五个槽位命令
在 client 缺席时一律报「未连接」,这个独占窗口**原本被 120s 总超时封顶,F-10 移除后变成与回复等长**
—— 一次正常的长回复就会让该槽的 sessions / capabilities / upload / download / switch 全部瘫痪。
是 R2 让它显性化的,因此在 R2 内修掉。
**审查发现的两处加固**(均为 R2 自身改动造成)
- 移除流式总超时后,单条响应失去唯一边界(`read_timeout` 只测两次读之间的间隔,替代不了),
`SseLineBuffer` 与 `mapper.accumulated` 都可无限增长。已加 64 MiB 单响应上限。
- `SseLineBuffer` 逐行从头 `drain` 会把剩余缓冲整体搬移一次,对 hyper 单个可达数百 KiB 的 item
是平方复杂度。已改为游标,每 chunk 只压缩一次。
---
## 三、测试与验证
### 新增测试
**Rust:67 → 76(+9)**
| 测试 | 覆盖 |
| --- | --- |
| `line_buffer_keeps_multibyte_characters_split_across_chunks_intact` | F-11 单元层 |
| `line_buffer_strips_crlf_and_returns_the_trailing_line` | F-11 边界 |
| `line_buffer_cursor_survives_interleaved_reads_and_writes` | 游标改造 |
| `line_buffer_bounds_a_single_line_and_the_whole_response` | 单行上限 + 64 MiB 总量上限 |
| `decodes_multibyte_text_split_across_tcp_chunks` | F-11 端到端 |
| `truncated_body_reports_stream_interrupted_and_finalizes_the_message` | F-12 分类 + F-13 错误路径 |
| `a_broken_response_body_does_not_resend_the_chat_post` | F-12 不重发 |
| `cancellation_finalizes_the_message_as_cancelled` | F-13 取消路径 |
| `only_connect_failures_are_resent_automatically` | F-12 重试收窄 + 错误码 |
**前端:19 项 / 4 文件**(新增 `MessageContent.test.tsx` 4 例)
### 测试基建
三条传输测试用**裸 `TcpListener` 手写的 HTTP/1.1 chunked SSE 假服务端**驱动真实 `AstrBotClient`,
**未引入任何新依赖**。选它而非 axum 的理由:需要按字节精确控制 chunk 切分点,以及在不发终止块的
情况下中途断连——这两点用 HTTP 框架无法表达。
**护栏有效性已验证**:把 `push_chunk` 临时退回旧的逐 chunk lossy 解码后,端到端测试真实复现了
乱码才失败,证明 hyper 确实把两帧当作独立 stream item 投递,测试不是同义反复。
### 门槛结果
| 命令 | 结果 |
| --- | --- |
| `cargo fmt --all -- --check` | 通过 |
| `cargo clippy --workspace --all-targets -- -D warnings` | 通过 |
| `cargo test --workspace` | 76 通过 / 0 失败 / 0 ignored |
| `npm run typecheck` | 通过 |
| `npm run lint` | 通过 |
| `npm run test -- --run` | 19 通过 / 4 文件 |
| `npm run build` | 通过 |
### 提交
```
58a98d3 docs(reports): record the source audit, fix queue, and R1/R2 results
c4c40bd fix(astrbot): do not resend messages after the response starts
6e81a3a fix(astrbot): scope stream event ids and fix the transport layer
41592e2 fix(ui): restore corrupted localized strings
828f7c5 fix(chat): accept null in runtime event contracts
e8d9dbc refactor(ui): share ipc error formatting
051b9ce fix(chat): restrict markdown link protocols
78f03e3 fix(tauri): allow blob images in production csp
def5e92 fix(tauri): grant desktop-pet capability
28ec300 fix(pet): correct manifest image pattern
```
R1 的前端 7 项按 F-02…F-09 逐项拆分提交。`astrbot.rs` 与 `astrbot_client.rs` 中,R1 的 F-01/F-07
与 R2 的 F-10/F-11/F-13 物理交织在同一函数内,无法在不伪造未经测试的中间状态的前提下拆开,
因此合为一个提交,并在提交正文中逐项说明。
---
## 四、未完成
### 4.1 未开始的批次(53 项)
| 批次 | 剩余项 | 依赖 | 内容摘要 |
| --- | --- | --- | --- |
| **R3** | F-14 … F-19(6) | R1 的 F-06(已完成,**可立即开始**) | 探测移出全局锁且可取消;`listen()` 注销竞态(StrictMode 下 delta 翻倍);附件/草稿/错误按槽隔离;`switch_slot_session` 的 generation 校验;发送先校验后入库;`probe_connection_slot` 校验槽位分配 |
| **R4** | F-20 … F-25(6) | 无,可与 R3 并行 | 长会话取最新 N 条 + 游标分页;脱敏正则补裸 `token`/JWT;YAML/INI/.env 结构化脱敏;删除 profile 时清理凭据;敏感请求结构体手写 `Debug`;`account_id` 键模型统一 |
| **R5** | F-26 … F-34(9) | 无,可与 R3/R4 并行 | 未知事件类型降级为跳过;移除只读 payload 的 `deny_unknown_fields`;schema 漂移比对进 `cargo test`;`TransportKind` 拼写统一;删除恒 false 的身份自比较;mock 网关三缺陷;mapper 重复 complete / 迟到 plain;非图片媒体占位与 FIFO;无 `message_id` 流的稳定合成 id |
| **R6** | F-35 … F-44(10) | R3 | **产品红线**:`alwaysOnTop` 默认改 `false`;未读三连;重试按会话过滤;取消与真错误区分;`ChatMessage` 补四元组;键盘 focus 死锁;tablist 无障碍;凭据卡明文清空;轮询退避与告警;自动滚动与语音卸载清理 |
| **R7** | F-45 … F-52 中的 7 项(F-49 已完成) | R6 | spritesheet 去 `?inline` 改 WebP(lazy chunk ~5.2 MB → ~0.6 MB);前端渲染管线 memo 化;附件走二进制 IPC 通道;事件通道改每槽独立 mpsc;`styles.css` token 合并;`tauri.conf` 改 pnpm;tsconfig/eslint/vitest 收紧 |
| **R8** | F-53 … F-68 中的 15 项(F-56 已完成) | 随批携带 | 时钟注入、`server_instance_id` 改 sha2、username 逐字节编码、生产 CSP 移除 `127.0.0.1:*`、凭据轮换顺序、退出前 flush、Suspense 边界、`aria-hidden`、reduced-motion、文案统一等 |
**当前构建仍可观测到的 R7 症状**:`npm run build` 产出的 `DesktopPetView` chunk 为 5,230.85 kB
(gzip 3,921.56 kB),即 F-45 描述的 `?inline` 内联问题,本轮未处理。
### 4.2 未做的验证
以下属于 R1/R2 的**批次验收条件**,本轮只跑了本地门槛,尚未执行:
- **Tauri release 构建(NSIS)** —— 只跑了 Vite 生产构建(`npm run build`),未跑
`npm run tauri:build`。**F-04 必须用 release 验证**,因为 dev 不注入 CSP。
- **Playwright e2e**(`npm run test:e2e`)—— 未运行。
- **R1 真机验收**:同一连接连发 3 条消息每条完整显示;桌宠事件联动、拖动、右键菜单;
release 构建下附件图渲染。
- **R2 真机验收**:断网/恢复、超过 120s 的长回复完整到达、中途停止后重启应用不残留「生成中」。
- **`docs/q9-local-acceptance.md`** 未刷新(队列建议 R1 与 R2 合并后同时刷新)。
### 4.3 需要外部条件、不进本轮编码
- **P1-9 附件契约验证**(置信度中):需用真实容器发一条带图消息,确认模型是否真的看到附件。
若确认被忽略,改为 `message` 段数组承载 `attachment_id`(snake_case),属 P1 级改动。
- **证书指纹绑定**:TLS 校验零接入,录入通道已开放。建议在实现前于录入层标注「暂不生效」。
- **工具提案六道闸门**:未开始实现属阶段合理;闸门落地前不得放开任何工具执行入口。
- **签名更新、双服务器 soak**:维持现状,不在本地伪造。
---
## 五、过程记录:审查工具链事故
本批的对抗式审查让 subagent 直接运行在**工作区**上。其中两个 agent 在做「临时改动以验证测试是否
真的会失败」之后**没有还原**,留下了:
- `send_chat_stream` 错误分支内一段显式的第二次 `POST /api/v1/chat`(注释标着
`MUTATION (temporary)`);
- `astrbot_client.rs` 的 `zz_repro`、`runtime.rs` 的 `throwaway_slot_lockout_repro` 两个测试模块;
- `src-tauri/tests/zz_repro_sse_quadratic.rs`;
- 把 F-10 的流式 client 改回 `.timeout()` 并留下 `let _ = STREAM_IDLE_TIMEOUT;`。
那段注入的 POST 一度被误判为「HTTP 栈自行重发」的真实缺陷并记为 F-69,且**被提交进了仓库**。
从复现侧逐级二分(用 client 自己的 `stream_http` 手动驱动 → 换真实 body → 换 `select!` 驱动 →
加锁与 mpsc → 近乎逐字复制整个函数体,全部只发 1 次请求,唯独真函数发 2 次)把差异压缩到函数体
内部之后,注入的那 7 行才暴露出来。
**处置**:全部注入物已清除;F-69 记录已从 CHANGELOG、`docs/progress.md`、修复队列中撤销;
三个含污染代码的本地提交已用 `git reset --soft` 重写(未推送),并逐提交扫描确认无残留;
`#[ignore]` 的占位测试改回正常断言 `a_broken_response_body_does_not_resend_the_chat_post`,
现已通过。
**结论:F-69 不存在,P1-2 已闭环。**
**规程**:后续审查必须只读运行,或用独立 worktree 隔离;不得让审查 agent 写主工作区。
---
## 六、下一步
按队列顺序进入 **R3 · 隔离与状态正确性批**(F-14 … F-19)。R3 依赖的 R1 · F-06 已完成,
无阻塞。R4 与 R5 与 R3 无依赖关系,可并行分派到不同分支。

查看文件

@ -2,6 +2,6 @@
"$schema": "../gen/schemas/desktop-schema.json", "$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default", "identifier": "default",
"description": "Minimal capability set for the main AstrBot Desktop window.", "description": "Minimal capability set for the main AstrBot Desktop window.",
"windows": ["main", "quick-chat", "status-bubble", "desktop-pet"], "windows": ["main", "quick-chat", "status-bubble"],
"permissions": ["core:default"] "permissions": ["core:default"]
} }

查看文件

@ -3,8 +3,8 @@ use std::{collections::VecDeque, sync::Arc, time::Duration};
use desktop_protocol::{ use desktop_protocol::{
AstrBotApiEnvelope, AstrBotAttachment, AstrBotCapabilitySnapshot, AstrBotChatRequest, AstrBotApiEnvelope, AstrBotAttachment, AstrBotCapabilitySnapshot, AstrBotChatRequest,
AstrBotConfigListData, AstrBotModelOption, AstrBotSessionListData, AstrBotStreamMapper, AstrBotConfigListData, AstrBotModelOption, AstrBotSessionListData, AstrBotStreamMapper,
AuthenticationType, BoundGatewayEvent, ConnectionState, FinishReason, GatewayEvent, AuthenticationType, BoundGatewayEvent, ConnectionState, GatewayEvent, PROTOCOL_VERSION,
PROTOCOL_VERSION, derive_astrbot_server_instance_id, derive_astrbot_server_instance_id,
}; };
use futures_util::StreamExt; use futures_util::StreamExt;
use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderValue}; use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderValue};
@ -44,14 +44,6 @@ pub enum AstrBotClientError {
Json(#[from] serde_json::Error), Json(#[from] serde_json::Error),
#[error("astrbot stream mapping failed: {0}")] #[error("astrbot stream mapping failed: {0}")]
Map(String), Map(String),
/// The response body broke after the server had already started answering.
///
/// Distinct from [`AstrBotClientError::Request`] on purpose: `/api/v1/chat`
/// has no idempotency key, so re-POSTing a message whose response had
/// already begun duplicates it in the remote conversation. Only the caller
/// (i.e. the user) may retry this.
#[error("astrbot stream interrupted after the response started")]
StreamInterrupted,
#[error("server identity changed")] #[error("server identity changed")]
ServerIdentityChanged, ServerIdentityChanged,
#[error("astrbot event channel closed")] #[error("astrbot event channel closed")]
@ -72,9 +64,6 @@ impl From<AstrBotClientError> for GatewayError {
AstrBotClientError::ChannelClosed => GatewayError::ChannelClosed, AstrBotClientError::ChannelClosed => GatewayError::ChannelClosed,
AstrBotClientError::ApiStatus(message) => GatewayError::Adapter(message), AstrBotClientError::ApiStatus(message) => GatewayError::Adapter(message),
AstrBotClientError::Map(message) => GatewayError::Adapter(message), AstrBotClientError::Map(message) => GatewayError::Adapter(message),
AstrBotClientError::StreamInterrupted => GatewayError::Adapter(
"AstrBot stream interrupted after the response started".into(),
),
AstrBotClientError::InvalidConfig(message) => GatewayError::Adapter(message.to_owned()), AstrBotClientError::InvalidConfig(message) => GatewayError::Adapter(message.to_owned()),
AstrBotClientError::CredentialExpired => { AstrBotClientError::CredentialExpired => {
GatewayError::Adapter("AstrBot authentication has expired".into()) GatewayError::Adapter("AstrBot authentication has expired".into())
@ -85,88 +74,6 @@ impl From<AstrBotClientError> for GatewayError {
const MAX_DEDUPLICATED_EVENTS: usize = 4_096; const MAX_DEDUPLICATED_EVENTS: usize = 4_096;
/// Guards against a hostile or broken server streaming an unbounded single line.
const MAX_SSE_LINE_BYTES: usize = 1024 * 1024;
/// Ceiling on the total size of one chat response.
///
/// Removing `Client::timeout` from the streaming client (so a slow reply is no
/// longer cut off) also removed the only bound on how much a server could send
/// in one response. `read_timeout` cannot replace it: it measures the gap
/// between successful reads, so a server that keeps trickling bytes keeps the
/// stream alive forever, and both this buffer and the mapper's accumulated
/// message text would grow without limit. A real reply is far below this.
const MAX_STREAM_BYTES: u64 = 64 * 1024 * 1024;
/// Splits an SSE byte stream into lines at the byte level.
///
/// TCP chunk boundaries fall on arbitrary byte offsets, so decoding each chunk
/// with `String::from_utf8_lossy` corrupts any multi-byte character that
/// straddles two chunks — for CJK text (3 bytes per character) that is a
/// frequent, user-visible `U+FFFD`. Buffering raw bytes and only decoding
/// complete `\n`-delimited lines keeps every character intact, because SSE
/// guarantees `\n` (0x0A) never appears inside a UTF-8 multi-byte sequence.
#[derive(Debug, Default)]
struct SseLineBuffer {
bytes: Vec<u8>,
/// Offset of the first unconsumed byte.
///
/// Consuming a line by draining from the front would memmove the entire
/// remainder once per line, which is quadratic in the chunk size — and a
/// single `bytes_stream()` item from hyper can be several hundred KiB of
/// short delta frames. Advancing a cursor instead makes reading a line O(1)
/// and leaves one memmove per chunk, in `push_chunk`.
cursor: usize,
total: u64,
}
impl SseLineBuffer {
fn push_chunk(&mut self, chunk: &[u8]) {
if self.cursor > 0 {
self.bytes.drain(..self.cursor);
self.cursor = 0;
}
self.total = self.total.saturating_add(chunk.len() as u64);
self.bytes.extend_from_slice(chunk);
}
/// Pops the next complete line, or `None` when the buffer holds no `\n` yet.
///
/// Invalid UTF-8 within a single complete line is replaced rather than
/// rejected: a lossy line is still parseable SSE, and dropping the whole
/// stream over one bad byte would lose the surrounding reply.
fn next_line(&mut self) -> Option<String> {
let pending = &self.bytes[self.cursor..];
let index = pending.iter().position(|byte| *byte == b'\n')?;
let mut line = &pending[..index];
if line.last() == Some(&b'\r') {
line = &line[..line.len() - 1];
}
let text = String::from_utf8_lossy(line).into_owned();
self.cursor += index + 1;
Some(text)
}
/// Consumes whatever is left once the stream ends without a trailing `\n`.
fn take_remainder(&mut self) -> Option<String> {
let mut line = &self.bytes[self.cursor..];
if line.is_empty() {
return None;
}
if line.last() == Some(&b'\r') {
line = &line[..line.len() - 1];
}
let text = String::from_utf8_lossy(line).into_owned();
self.cursor = self.bytes.len();
(!text.trim().is_empty()).then_some(text)
}
/// True when one line, or the whole response, has outgrown its limit.
fn is_overflowing(&self) -> bool {
self.bytes.len() - self.cursor > MAX_SSE_LINE_BYTES || self.total > MAX_STREAM_BYTES
}
}
#[derive(Default)] #[derive(Default)]
struct EventDeduplicator { struct EventDeduplicator {
ids: std::collections::HashSet<String>, ids: std::collections::HashSet<String>,
@ -188,27 +95,10 @@ impl EventDeduplicator {
} }
} }
/// Total budget for a short request/response exchange (probe, sessions, upload).
const REST_TOTAL_TIMEOUT: Duration = Duration::from_secs(120);
/// How long the chat stream may stay completely silent before it is abandoned.
///
/// This is deliberately *not* a total timeout. `Client::timeout` counts from the
/// start of the request until the body has finished, and it keeps running while
/// `bytes_stream()` is being consumed, so any generation longer than the budget
/// was cut off mid-reply. `read_timeout` resets after every successful read, so
/// a reply may take arbitrarily long as long as it keeps producing bytes.
const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(120);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Clone)] #[derive(Clone)]
pub struct AstrBotClient { pub struct AstrBotClient {
config: AstrBotClientConfig, config: AstrBotClientConfig,
/// Short request/response endpoints; keeps a total deadline.
http: reqwest::Client, http: reqwest::Client,
/// `/api/v1/chat` only; no total deadline, idle detection via `read_timeout`.
stream_http: reqwest::Client,
seen_event_ids: Arc<Mutex<EventDeduplicator>>, seen_event_ids: Arc<Mutex<EventDeduplicator>>,
session_id: Arc<Mutex<Option<String>>>, session_id: Arc<Mutex<Option<String>>>,
server_instance_id: Arc<Mutex<String>>, server_instance_id: Arc<Mutex<String>>,
@ -252,18 +142,10 @@ impl AstrBotClient {
); );
let http = reqwest::Client::builder() let http = reqwest::Client::builder()
.default_headers(headers.clone())
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(CONNECT_TIMEOUT)
.timeout(REST_TOTAL_TIMEOUT)
.build()?;
let stream_http = reqwest::Client::builder()
.default_headers(headers) .default_headers(headers)
.redirect(reqwest::redirect::Policy::none()) .redirect(reqwest::redirect::Policy::none())
.connect_timeout(CONNECT_TIMEOUT) .connect_timeout(Duration::from_secs(5))
.read_timeout(STREAM_IDLE_TIMEOUT) .timeout(Duration::from_secs(120))
.tcp_keepalive(Duration::from_secs(60))
.build()?; .build()?;
let (state_tx, _) = watch::channel(ConnectionState::Disconnected); let (state_tx, _) = watch::channel(ConnectionState::Disconnected);
@ -274,7 +156,6 @@ impl AstrBotClient {
..config ..config
}, },
http, http,
stream_http,
seen_event_ids: Arc::new(Mutex::new(EventDeduplicator::default())), seen_event_ids: Arc::new(Mutex::new(EventDeduplicator::default())),
session_id: Arc::new(Mutex::new(initial_session)), session_id: Arc::new(Mutex::new(initial_session)),
server_instance_id: Arc::new(Mutex::new(initial_identity)), server_instance_id: Arc::new(Mutex::new(initial_identity)),
@ -531,7 +412,7 @@ impl AstrBotClient {
}; };
let response = self let response = self
.stream_http .http
.post(self.url("/api/v1/chat")) .post(self.url("/api/v1/chat"))
.header(ACCEPT, HeaderValue::from_static("text/event-stream")) .header(ACCEPT, HeaderValue::from_static("text/event-stream"))
.json(&request) .json(&request)
@ -556,12 +437,7 @@ impl AstrBotClient {
return Err(AstrBotClientError::ServerIdentityChanged); return Err(AstrBotClientError::ServerIdentityChanged);
} }
// Every request gets its own stream id: the mapper restarts its let mut mapper = AstrBotStreamMapper::new(server_instance_id.clone());
// sequence counter per stream, and `seen_event_ids` outlives a single
// request, so reusing ids would make the deduplicator discard every
// event of the second and later messages on this connection.
let stream_id = uuid::Uuid::new_v4().to_string();
let mut mapper = AstrBotStreamMapper::new(server_instance_id.clone(), stream_id);
if let Some(existing) = session_id { if let Some(existing) = session_id {
let seed = serde_json::json!({ let seed = serde_json::json!({
"type": "session_id", "type": "session_id",
@ -572,78 +448,39 @@ impl AstrBotClient {
} }
let mut stream = response.bytes_stream(); let mut stream = response.bytes_stream();
let mut buffer = SseLineBuffer::default(); let mut buffer = String::new();
self.set_state(ConnectionState::Connected); self.set_state(ConnectionState::Connected);
// From here on the server has accepted and is answering this POST, so a
// failure must never be retried automatically — see `finish_and_fail`.
loop { loop {
tokio::select! { tokio::select! {
_ = cancellation.cancelled() => { _ = cancellation.cancelled() => {
// Leave the connection state alone: the socket is still self.set_state(ConnectionState::Disconnected);
// healthy and flipping to Disconnected only makes the tray
// and the slot badge flicker.
let events = mapper.finish_stream_with(FinishReason::Cancelled);
self.dispatch_events(events, sender).await?;
if let Some(session) = mapper.session_id() {
*self.session_id.lock().await = Some(session.to_owned());
}
self.set_state(ConnectionState::Connected);
return Ok(mapper.session_id().map(str::to_owned)); return Ok(mapper.session_id().map(str::to_owned));
} }
next = stream.next() => { next = stream.next() => {
let Some(next) = next else { break; }; let Some(next) = next else { break; };
let chunk = match next { let chunk = next?;
Ok(chunk) => chunk, buffer.push_str(&String::from_utf8_lossy(&chunk));
Err(_) => { while let Some(index) = buffer.find('\n') {
return self let mut line = buffer[..index].to_owned();
.finish_and_fail(&mut mapper, sender, AstrBotClientError::StreamInterrupted) buffer.drain(..=index);
.await; if line.ends_with('\r') {
} line.pop();
};
buffer.push_chunk(&chunk);
if buffer.is_overflowing() {
return self
.finish_and_fail(
&mut mapper,
sender,
AstrBotClientError::Map(
"astrbot response exceeded the supported size".into(),
),
)
.await;
}
while let Some(line) = buffer.next_line() {
match mapper.push_line(&line) {
Ok(events) => self.dispatch_events(events, sender).await?,
Err(error) => {
return self
.finish_and_fail(
&mut mapper,
sender,
AstrBotClientError::Map(error.to_string()),
)
.await;
}
} }
let events = mapper
.push_line(&line)
.map_err(|error| AstrBotClientError::Map(error.to_string()))?;
self.dispatch_events(events, sender).await?;
} }
} }
} }
} }
if let Some(remainder) = buffer.take_remainder() { if !buffer.trim().is_empty() {
match mapper.push_line(&remainder) { let events = mapper
Ok(events) => self.dispatch_events(events, sender).await?, .push_line(buffer.trim_end_matches('\r'))
Err(error) => { .map_err(|error| AstrBotClientError::Map(error.to_string()))?;
return self self.dispatch_events(events, sender).await?;
.finish_and_fail(
&mut mapper,
sender,
AstrBotClientError::Map(error.to_string()),
)
.await;
}
}
} }
let events = mapper.finish_stream(); let events = mapper.finish_stream();
self.dispatch_events(events, sender).await?; self.dispatch_events(events, sender).await?;
@ -655,29 +492,6 @@ impl AstrBotClient {
Ok(self.session_id.lock().await.clone()) Ok(self.session_id.lock().await.clone())
} }
/// Closes out a half-streamed message before surfacing a transport failure.
///
/// Every error path after the response headers arrive has to emit a
/// `MessageCompleted { finishReason: error }`; otherwise the partial reply
/// stays `streaming = 1` in the database and renders as "generating"
/// forever, including after a restart.
async fn finish_and_fail(
&self,
mapper: &mut AstrBotStreamMapper,
sender: &mpsc::Sender<super::gateway_client::BoundGatewayEvent>,
error: AstrBotClientError,
) -> Result<Option<String>, AstrBotClientError> {
let events = mapper.finish_stream_with(FinishReason::Error);
// Best effort: if the channel is already gone there is nothing left to
// finalize, and the original transport error is the more useful one.
let _ = self.dispatch_events(events, sender).await;
if let Some(session) = mapper.session_id() {
*self.session_id.lock().await = Some(session.to_owned());
}
self.set_state(ConnectionState::ServerUnavailable);
Err(error)
}
async fn dispatch_events( async fn dispatch_events(
&self, &self,
events: Vec<GatewayEvent>, events: Vec<GatewayEvent>,
@ -817,386 +631,4 @@ mod tests {
assert!(jwt_is_expired("e30.eyJleHAiOjF9.signature")); assert!(jwt_is_expired("e30.eyJleHAiOjF9.signature"));
assert!(!jwt_is_expired("not-a-jwt")); assert!(!jwt_is_expired("not-a-jwt"));
} }
#[test]
fn line_buffer_keeps_multibyte_characters_split_across_chunks_intact() {
// "你好世界" is 12 UTF-8 bytes; cut in the middle of the second char.
let payload = "data: {\"type\":\"plain\",\"data\":\"你好世界\"}\n";
let bytes = payload.as_bytes();
let split = bytes
.iter()
.position(|byte| *byte == 0xE4)
.expect("payload contains a CJK lead byte")
+ 4;
assert!(
!payload.is_char_boundary(split),
"split must cut a character"
);
let mut buffer = SseLineBuffer::default();
buffer.push_chunk(&bytes[..split]);
assert!(
buffer.next_line().is_none(),
"an incomplete line must not be emitted"
);
buffer.push_chunk(&bytes[split..]);
let line = buffer
.next_line()
.expect("line completes on the second chunk");
assert!(!line.contains('\u{FFFD}'), "decoded line: {line}");
assert!(line.contains("你好世界"));
}
#[test]
fn line_buffer_strips_crlf_and_returns_the_trailing_line() {
let mut buffer = SseLineBuffer::default();
buffer.push_chunk(b"data: one\r\ndata: two\r\n");
assert_eq!(buffer.next_line().as_deref(), Some("data: one"));
assert_eq!(buffer.next_line().as_deref(), Some("data: two"));
assert_eq!(buffer.next_line(), None);
buffer.push_chunk(b"data: tail");
assert_eq!(buffer.next_line(), None);
assert_eq!(buffer.take_remainder().as_deref(), Some("data: tail"));
assert_eq!(buffer.take_remainder(), None);
}
#[test]
fn line_buffer_cursor_survives_interleaved_reads_and_writes() {
// The cursor is only compacted on push_chunk, so a partially drained
// buffer must still read correctly across the next chunk.
let mut buffer = SseLineBuffer::default();
buffer.push_chunk(b"a\nb\nc");
assert_eq!(buffer.next_line().as_deref(), Some("a"));
buffer.push_chunk(b"d\ne\n");
assert_eq!(buffer.next_line().as_deref(), Some("b"));
assert_eq!(buffer.next_line().as_deref(), Some("cd"));
assert_eq!(buffer.next_line().as_deref(), Some("e"));
assert_eq!(buffer.next_line(), None);
assert_eq!(buffer.take_remainder(), None);
}
#[test]
fn line_buffer_bounds_a_single_line_and_the_whole_response() {
let mut oversized_line = SseLineBuffer::default();
oversized_line.push_chunk(&vec![b'x'; MAX_SSE_LINE_BYTES + 1]);
assert!(oversized_line.is_overflowing());
// Consumed bytes still count towards the response ceiling, otherwise a
// server could stream forever in small well-formed lines: read_timeout
// never fires while bytes keep arriving, and there is no total timeout.
let mut long_response = SseLineBuffer::default();
let line = b"data: {}\n";
let repeats = (MAX_STREAM_BYTES as usize / line.len()) + 1;
for _ in 0..repeats {
long_response.push_chunk(line);
while long_response.next_line().is_some() {}
}
assert!(long_response.is_overflowing());
assert!(
long_response.bytes.len() < 1024,
"the buffer itself must stay small; only the counter grows"
);
}
}
/// End-to-end transport tests against a hand-rolled HTTP/1.1 SSE server.
///
/// A raw `TcpListener` is used instead of an HTTP framework on purpose: these
/// tests need byte-exact control over where the response body is split across
/// TCP writes, and the ability to drop the socket mid-body without sending the
/// terminal chunk. Neither is expressible through a normal server API.
#[cfg(test)]
mod stream_transport_tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
/// What the fake server does after it has written the scripted frames.
#[derive(Clone, Copy, PartialEq)]
enum Ending {
/// Send the terminal `0\r\n\r\n` chunk: a well-formed, complete body.
Complete,
/// Drop the socket without the terminal chunk, so the client sees a
/// truncated body rather than a clean end of stream.
Truncate,
/// Keep the connection open and silent, so only cancellation ends it.
HoldOpen,
}
struct FakeAstrBot {
base_url: String,
requests: Arc<AtomicUsize>,
}
/// Serves `chunks` as separate chunked-encoding frames with a pause between
/// them, which forces hyper to surface them as distinct stream items.
async fn spawn_fake(chunks: Vec<Vec<u8>>, ending: Ending) -> FakeAstrBot {
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
let port = listener.local_addr().expect("addr").port();
let requests = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&requests);
tokio::spawn(async move {
loop {
let Ok((mut socket, _)) = listener.accept().await else {
return;
};
let chunks = chunks.clone();
let counter = Arc::clone(&counter);
tokio::spawn(async move {
if read_request(&mut socket).await.is_none() {
return;
}
counter.fetch_add(1, Ordering::SeqCst);
let header = b"HTTP/1.1 200 OK\r\n\
Content-Type: text/event-stream\r\n\
Transfer-Encoding: chunked\r\n\r\n";
if socket.write_all(header).await.is_err() {
return;
}
for chunk in chunks {
let framed = format!("{:X}\r\n", chunk.len());
if socket.write_all(framed.as_bytes()).await.is_err()
|| socket.write_all(&chunk).await.is_err()
|| socket.write_all(b"\r\n").await.is_err()
|| socket.flush().await.is_err()
{
return;
}
// Guarantees the next frame lands in its own TCP read.
tokio::time::sleep(Duration::from_millis(60)).await;
}
match ending {
Ending::Complete => {
let _ = socket.write_all(b"0\r\n\r\n").await;
let _ = socket.flush().await;
}
Ending::Truncate => {
// Dropping without the terminal chunk makes hyper
// report an incomplete message.
let _ = socket.shutdown().await;
}
Ending::HoldOpen => {
tokio::time::sleep(Duration::from_secs(30)).await;
}
}
});
}
});
FakeAstrBot {
base_url: format!("http://127.0.0.1:{port}"),
requests,
}
}
/// Reads request headers plus any declared body so the client's write side
/// completes before the response is produced.
async fn read_request(socket: &mut tokio::net::TcpStream) -> Option<()> {
let mut raw = Vec::new();
let mut scratch = [0u8; 1024];
loop {
let read = socket.read(&mut scratch).await.ok()?;
if read == 0 {
return None;
}
raw.extend_from_slice(&scratch[..read]);
if let Some(index) = raw
.windows(4)
.position(|window| window == b"\r\n\r\n")
.map(|index| index + 4)
{
let headers = String::from_utf8_lossy(&raw[..index]).to_ascii_lowercase();
let length = headers
.lines()
.find_map(|line| line.strip_prefix("content-length:"))
.and_then(|value| value.trim().parse::<usize>().ok())
.unwrap_or(0);
let mut body = raw.len() - index;
while body < length {
let read = socket.read(&mut scratch).await.ok()?;
if read == 0 {
return None;
}
body += read;
}
return Some(());
}
}
}
fn client_for(base_url: &str) -> AstrBotClient {
AstrBotClient::new(AstrBotClientConfig {
profile_id: "profile-a".into(),
slot: SlotKind::Companion,
base_url: base_url.to_owned(),
api_key: SecretString::from("abk_test".to_owned()),
remote_username: "desktop-companion".into(),
remote_display_name: None,
authentication_type: AuthenticationType::ApiKey,
session_id: None,
expected_server_instance_id: None,
})
.expect("client")
}
fn drain(
receiver: &mut mpsc::Receiver<super::super::gateway_client::BoundGatewayEvent>,
) -> Vec<super::super::gateway_client::BoundGatewayEvent> {
let mut events = Vec::new();
while let Ok(event) = receiver.try_recv() {
events.push(event);
}
events
}
#[tokio::test]
async fn decodes_multibyte_text_split_across_tcp_chunks() {
// One SSE frame carrying CJK text, cut in the middle of a character.
let frame = "data: {\"type\":\"plain\",\"data\":\"你好,世界\"}\n\n";
let bytes = frame.as_bytes().to_vec();
let split = bytes
.iter()
.position(|byte| *byte == 0xE4)
.expect("CJK lead byte")
+ 1;
assert!(!frame.is_char_boundary(split), "split must cut a character");
let server = spawn_fake(
vec![bytes[..split].to_vec(), bytes[split..].to_vec()],
Ending::Complete,
)
.await;
let client = client_for(&server.base_url);
let (tx, mut rx) = mpsc::channel(64);
let cancellation = CancellationToken::new();
client
.send_chat_stream("hi", None, Vec::new(), &tx, &cancellation)
.await
.expect("stream completes");
let text = drain(&mut rx)
.iter()
.filter(|event| event.event_type == "message.completed")
.filter_map(|event| {
event
.payload
.get("content")
.and_then(Value::as_str)
.map(ToOwned::to_owned)
})
.collect::<String>();
assert!(!text.contains('\u{FFFD}'), "decoded content: {text}");
assert!(text.contains("你好,世界"), "decoded content: {text}");
}
#[tokio::test]
async fn truncated_body_reports_stream_interrupted_and_finalizes_the_message() {
let server = spawn_fake(
vec![b"data: {\"type\":\"plain\",\"data\":\"partial\"}\n\n".to_vec()],
Ending::Truncate,
)
.await;
let client = client_for(&server.base_url);
let (tx, mut rx) = mpsc::channel(64);
let cancellation = CancellationToken::new();
let error = client
.send_chat_stream("hi", None, Vec::new(), &tx, &cancellation)
.await
.expect_err("a truncated body must not look like success");
assert!(
matches!(error, AstrBotClientError::StreamInterrupted),
"the response had already started, so this must not be auto-retried: {error:?}"
);
let completed = drain(&mut rx)
.into_iter()
.find(|event| event.event_type == "message.completed")
.expect("the half-streamed message must be finalized, not left streaming");
assert_eq!(
completed
.payload
.get("finishReason")
.and_then(Value::as_str),
Some("error")
);
assert_eq!(
completed.payload.get("content").and_then(Value::as_str),
Some("partial"),
"text received before the break must be preserved"
);
}
/// A message whose reply had already started must never be re-sent:
/// `POST /api/v1/chat` carries no idempotency key, so a second attempt
/// appends the user's message to the remote conversation again.
#[tokio::test]
async fn a_broken_response_body_does_not_resend_the_chat_post() {
let server = spawn_fake(
vec![
b"data: {\"type\":\"plain\",\"data\":\"partial\"}
"
.to_vec(),
],
Ending::Truncate,
)
.await;
let client = client_for(&server.base_url);
let (tx, _rx) = mpsc::channel(64);
let cancellation = CancellationToken::new();
let _ = client
.send_chat_stream("hi", None, Vec::new(), &tx, &cancellation)
.await;
// Give any resend time to land before sampling.
tokio::time::sleep(Duration::from_millis(500)).await;
assert_eq!(server.requests.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn cancellation_finalizes_the_message_as_cancelled() {
let server = spawn_fake(
vec![b"data: {\"type\":\"plain\",\"data\":\"half a rep\"}\n\n".to_vec()],
Ending::HoldOpen,
)
.await;
let client = client_for(&server.base_url);
let (tx, mut rx) = mpsc::channel(64);
let cancellation = CancellationToken::new();
let trigger = cancellation.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(400)).await;
trigger.cancel();
});
client
.send_chat_stream("hi", None, Vec::new(), &tx, &cancellation)
.await
.expect("cancellation is not a failure");
let completed = drain(&mut rx)
.into_iter()
.find(|event| event.event_type == "message.completed")
.expect("stopping generation must still finalize the message");
assert_eq!(
completed
.payload
.get("finishReason")
.and_then(Value::as_str),
Some("cancelled")
);
assert_eq!(
completed.payload.get("content").and_then(Value::as_str),
Some("half a rep"),
"content received before the stop must be kept"
);
}
} }

查看文件

@ -83,28 +83,10 @@ impl EventDeduplicator {
} }
} }
/// Total budget for `/desktop/v1/health` and any other short exchange.
const REST_TOTAL_TIMEOUT: Duration = Duration::from_secs(30);
/// How long the event stream may stay silent before it is torn down and resumed.
///
/// A total `Client::timeout` keeps counting while `bytes_stream()` is consumed,
/// so a 30s total deadline meant the long-lived desktop-v1 connection was
/// killed and reconnected every 30 seconds no matter how healthy it was, and
/// heartbeats could not keep it alive. `read_timeout` resets on every received
/// byte, so heartbeats now do exactly that. Reconnects still resume from
/// `Last-Event-ID`, so an idle teardown is lossless.
const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(90);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Clone)] #[derive(Clone)]
pub struct GatewayClient { pub struct GatewayClient {
config: GatewayClientConfig, config: GatewayClientConfig,
/// Short request/response endpoints; keeps a total deadline.
http: reqwest::Client, http: reqwest::Client,
/// `/desktop/v1/events/stream` only; no total deadline.
stream_http: reqwest::Client,
seen_event_ids: Arc<Mutex<EventDeduplicator>>, seen_event_ids: Arc<Mutex<EventDeduplicator>>,
last_event_id: Arc<Mutex<Option<String>>>, last_event_id: Arc<Mutex<Option<String>>>,
state_tx: watch::Sender<ConnectionState>, state_tx: watch::Sender<ConnectionState>,
@ -115,21 +97,13 @@ impl GatewayClient {
let (state_tx, _) = watch::channel(ConnectionState::Disconnected); let (state_tx, _) = watch::channel(ConnectionState::Disconnected);
let http = reqwest::Client::builder() let http = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none()) .redirect(reqwest::redirect::Policy::none())
.connect_timeout(CONNECT_TIMEOUT) .connect_timeout(Duration::from_secs(5))
.timeout(REST_TOTAL_TIMEOUT) .timeout(Duration::from_secs(30))
.build()?;
let stream_http = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(CONNECT_TIMEOUT)
.read_timeout(STREAM_IDLE_TIMEOUT)
.tcp_keepalive(Duration::from_secs(60))
.build()?; .build()?;
Ok(Self { Ok(Self {
config, config,
http, http,
stream_http,
seen_event_ids: Arc::new(Mutex::new(EventDeduplicator::default())), seen_event_ids: Arc::new(Mutex::new(EventDeduplicator::default())),
last_event_id: Arc::new(Mutex::new(None)), last_event_id: Arc::new(Mutex::new(None)),
state_tx, state_tx,
@ -166,7 +140,7 @@ impl GatewayClient {
) -> Result<(), GatewayError> { ) -> Result<(), GatewayError> {
self.set_state(ConnectionState::Connecting); self.set_state(ConnectionState::Connecting);
let mut request = self let mut request = self
.stream_http .http
.get(format!("{}/desktop/v1/events/stream", self.config.base_url)) .get(format!("{}/desktop/v1/events/stream", self.config.base_url))
.header(ACCEPT, HeaderValue::from_static("text/event-stream")); .header(ACCEPT, HeaderValue::from_static("text/event-stream"));
if let Some(token) = &self.config.bearer_token { if let Some(token) = &self.config.bearer_token {

查看文件

@ -571,15 +571,7 @@ impl DualSlotRuntime {
)); ));
} }
// Clone the client rather than checking it out of the slot. // Take the client out so we can await without holding the mutex across network IO.
//
// `AstrBotClient` is a handle over shared state, and taking it made
// every other slot command — sessions, capabilities, upload, download,
// session switch — report "not connected" for the whole send. That
// window used to be capped by the client's 120s total timeout; now that
// streaming has no total deadline it would last as long as the reply,
// so an ordinary long answer would disable the rest of the slot.
// Concurrency is instead serialized on `message_cancellation`.
let ( let (
client, client,
profile_id, profile_id,
@ -591,13 +583,7 @@ impl DualSlotRuntime {
) = { ) = {
let mut guard = self.inner.lock().await; let mut guard = self.inner.lock().await;
let runtime = slot_mut(&mut guard, slot); let runtime = slot_mut(&mut guard, slot);
if runtime.message_cancellation.is_some() { let client = runtime.client.take().ok_or_else(|| {
return Err(RuntimeCommandError {
code: "slotBusy",
message: "This slot is already sending a message.",
});
}
let client = runtime.client.clone().ok_or_else(|| {
RuntimeCommandError::unavailable("The selected slot is not connected.") RuntimeCommandError::unavailable("The selected slot is not connected.")
})?; })?;
let cancellation = Arc::new(tokio_util::sync::CancellationToken::new()); let cancellation = Arc::new(tokio_util::sync::CancellationToken::new());
@ -615,9 +601,15 @@ impl DualSlotRuntime {
}; };
let send_result = match client { let send_result = match client {
ActiveClient::Desktop(_) => Err(RuntimeCommandError::unavailable( ActiveClient::Desktop(client) => {
"Desktop mock chat send is not activated in this runtime path yet.", let restored = ActiveClient::Desktop(client);
)), Err((
restored,
RuntimeCommandError::unavailable(
"Desktop mock chat send is not activated in this runtime path yet.",
),
))
}
ActiveClient::AstrBot(client) => { ActiveClient::AstrBot(client) => {
let mut attempts = 0; let mut attempts = 0;
loop { loop {
@ -632,19 +624,25 @@ impl DualSlotRuntime {
.await .await
{ {
Ok(_session) if cancellation.is_cancelled() => { Ok(_session) if cancellation.is_cancelled() => {
break Err(RuntimeCommandError { break Err((
code: "cancelled", ActiveClient::AstrBot(client),
message: "The chat request was cancelled.", RuntimeCommandError {
}); code: "cancelled",
message: "The chat request was cancelled.",
},
));
} }
Ok(session) => break Ok(session), Ok(session) => break Ok((ActiveClient::AstrBot(client), session)),
Err(AstrBotClientError::HttpStatus(status)) Err(AstrBotClientError::HttpStatus(status))
if status.as_u16() == 401 || status.as_u16() == 403 => if status.as_u16() == 401 || status.as_u16() == 403 =>
{ {
break Err(RuntimeCommandError { break Err((
code: "authExpired", ActiveClient::AstrBot(client),
message: "AstrBot authentication has expired. Re-login is required.", RuntimeCommandError {
}); code: "authExpired",
message: "AstrBot authentication has expired. Re-login is required.",
},
));
} }
Err(error) if should_retry_astrbot(&error) && attempts < 2 => { Err(error) if should_retry_astrbot(&error) && attempts < 2 => {
attempts += 1; attempts += 1;
@ -654,7 +652,12 @@ impl DualSlotRuntime {
drop(guard); drop(guard);
tokio::time::sleep(Duration::from_millis(250 * attempts)).await; tokio::time::sleep(Duration::from_millis(250 * attempts)).await;
} }
Err(error) => break Err(astrbot_send_error(&error)), Err(_) => {
break Err((
ActiveClient::AstrBot(client),
RuntimeCommandError::unavailable("AstrBot chat send failed."),
));
}
} }
} }
} }
@ -670,7 +673,8 @@ impl DualSlotRuntime {
} }
runtime.message_cancellation = None; runtime.message_cancellation = None;
match send_result { match send_result {
Ok(session) => { Ok((client, session)) => {
runtime.client = Some(client);
runtime.snapshot.profile_id = profile_id; runtime.snapshot.profile_id = profile_id;
runtime.snapshot.transport = transport; runtime.snapshot.transport = transport;
runtime.snapshot.server_instance_id = server_instance_id; runtime.snapshot.server_instance_id = server_instance_id;
@ -679,7 +683,8 @@ impl DualSlotRuntime {
runtime.snapshot.last_error = None; runtime.snapshot.last_error = None;
Ok(runtime.snapshot.clone()) Ok(runtime.snapshot.clone())
} }
Err(error) => { Err((client, error)) => {
runtime.client = Some(client);
runtime.snapshot.profile_id = profile_id; runtime.snapshot.profile_id = profile_id;
runtime.snapshot.transport = transport; runtime.snapshot.transport = transport;
runtime.snapshot.server_instance_id = server_instance_id; runtime.snapshot.server_instance_id = server_instance_id;
@ -715,40 +720,13 @@ fn slot_ref(inner: &DualSlotRuntimeInner, slot: SlotKind) -> &SlotRuntime {
} }
} }
/// Only a failure to *establish* the connection may be retried automatically.
///
/// `POST /api/v1/chat` carries no idempotency key. Once the server has accepted
/// the request it has already appended the user's message to the conversation,
/// so a second attempt duplicates both the question and the answer, and the two
/// attempts' deltas interleave into one garbled bubble. A connect error is the
/// only case where the request provably never reached the server; everything
/// else — a mid-body disconnect, an idle timeout, an HTTP error status — means
/// the server responded, and the user decides whether to resend.
fn should_retry_astrbot(error: &AstrBotClientError) -> bool { fn should_retry_astrbot(error: &AstrBotClientError) -> bool {
match error { match error {
AstrBotClientError::Request(error) => error.is_connect(), AstrBotClientError::Request(_) | AstrBotClientError::ChannelClosed => true,
_ => false, AstrBotClientError::HttpStatus(status) => {
} status.is_server_error() || status.as_u16() == 408 || status.as_u16() == 429
}
/// Maps a transport failure onto the code the UI uses to offer a manual retry.
fn astrbot_send_error(error: &AstrBotClientError) -> RuntimeCommandError {
match error {
AstrBotClientError::StreamInterrupted => RuntimeCommandError {
code: "streamInterrupted",
message: "The reply was cut off. AstrBot already received this message, so it was not resent automatically.",
},
AstrBotClientError::CredentialExpired => RuntimeCommandError {
code: "authExpired",
message: "AstrBot authentication has expired. Re-login is required.",
},
AstrBotClientError::HttpStatus(_) | AstrBotClientError::ApiStatus(_) => {
RuntimeCommandError {
code: "serverUnavailable",
message: "AstrBot rejected the chat request.",
}
} }
_ => RuntimeCommandError::unavailable("AstrBot chat send failed."), _ => false,
} }
} }
@ -785,43 +763,6 @@ mod tests {
assert_eq!(error.code, "validationFailed"); assert_eq!(error.code, "validationFailed");
} }
#[tokio::test]
async fn only_connect_failures_are_resent_automatically() {
// A refused connection proves the POST never reached AstrBot.
let connect_error = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(2))
.build()
.expect("client")
.get("http://127.0.0.1:1/api/v1/chat")
.send()
.await
.expect_err("port 1 refuses connections");
assert!(connect_error.is_connect(), "expected a connect-phase error");
assert!(should_retry_astrbot(&AstrBotClientError::Request(
connect_error
)));
// Everything below means the server already received the message, so
// resending would duplicate it in the remote conversation.
assert!(!should_retry_astrbot(
&AstrBotClientError::StreamInterrupted
));
assert!(!should_retry_astrbot(&AstrBotClientError::HttpStatus(
reqwest::StatusCode::INTERNAL_SERVER_ERROR
)));
assert!(!should_retry_astrbot(&AstrBotClientError::HttpStatus(
reqwest::StatusCode::TOO_MANY_REQUESTS
)));
assert!(!should_retry_astrbot(&AstrBotClientError::ChannelClosed));
// A break after the response started must surface its own code so the
// UI can offer a manual retry instead of silently swallowing it.
assert_eq!(
astrbot_send_error(&AstrBotClientError::StreamInterrupted).code,
"streamInterrupted"
);
}
#[tokio::test] #[tokio::test]
async fn status_starts_disconnected() { async fn status_starts_disconnected() {
let runtime = DualSlotRuntime::new(); let runtime = DualSlotRuntime::new();

查看文件

@ -42,7 +42,7 @@
} }
], ],
"security": { "security": {
"csp": "default-src \u0027self\u0027; connect-src ipc: http://ipc.localhost http://127.0.0.1:*; img-src \u0027self\u0027 asset: http://asset.localhost data: blob:; style-src \u0027self\u0027 \u0027unsafe-inline\u0027; script-src \u0027self\u0027" "csp": "default-src \u0027self\u0027; connect-src ipc: http://ipc.localhost http://127.0.0.1:*; img-src \u0027self\u0027 asset: http://asset.localhost data:; style-src \u0027self\u0027 \u0027unsafe-inline\u0027; script-src \u0027self\u0027"
} }
}, },
"bundle": { "bundle": {

查看文件

@ -10,7 +10,6 @@ import {
useState, useState,
} from "react"; } from "react";
import { errorMessage } from "./lib/errorMessage";
import { ChatPanel } from "./features/chat/ChatPanel"; import { ChatPanel } from "./features/chat/ChatPanel";
import { StatusBubble } from "./features/chat/StatusBubble"; import { StatusBubble } from "./features/chat/StatusBubble";
const ProfileManager = lazy(() => const ProfileManager = lazy(() =>
@ -102,7 +101,7 @@ export function App() {
setStatus(bootstrapStatusSchema.parse(result)); setStatus(bootstrapStatusSchema.parse(result));
setError(null); setError(null);
} catch (reason) { } catch (reason) {
setError(errorMessage(reason)); setError(reason instanceof Error ? reason.message : String(reason));
} }
}, []); }, []);
@ -122,7 +121,7 @@ export function App() {
? "open_pet_window" ? "open_pet_window"
: "close_pet_window"; : "close_pet_window";
void invoke(command).catch((reason) => { void invoke(command).catch((reason) => {
setError(errorMessage(reason)); setError(reason instanceof Error ? reason.message : String(reason));
}); });
}, [isBubbleView, isPetView, isQuickView, petDisplayMode]); }, [isBubbleView, isPetView, isQuickView, petDisplayMode]);
@ -449,7 +448,7 @@ function navIcon(page: PageKey) {
function PageLoading() { function PageLoading() {
return ( return (
<p className="loading-state" role="status" aria-live="polite"> <p className="loading-state" role="status" aria-live="polite">
加载中… Loading?
</p> </p>
); );
} }
@ -551,7 +550,9 @@ function PetPage({
} }
> >
<option value="app-ui">仅应用 UI 内</option> <option value="app-ui">仅应用 UI 内</option>
<option value="desktop-floating">桌面浮动</option> <option value="desktop-floating">
&#x684c;&#x9762;&#x6d6e;&#x52a8;
</option>
</select> </select>
</SettingCard> </SettingCard>
<SettingCard <SettingCard

查看文件

@ -2,7 +2,6 @@ import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { errorMessage } from "../../lib/errorMessage";
import { MessageContent } from "./MessageContent"; import { MessageContent } from "./MessageContent";
import { import {
@ -376,7 +375,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
} }
setPendingAttachments((current) => current.concat(uploaded)); setPendingAttachments((current) => current.concat(uploaded));
} catch (reason) { } catch (reason) {
setError(errorMessage(reason)); setError(reason instanceof Error ? reason.message : String(reason));
} finally { } finally {
setUploading(false); setUploading(false);
} }
@ -422,7 +421,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
); );
setError(null); setError(null);
} catch (reason) { } catch (reason) {
setError(errorMessage(reason)); setError(reason instanceof Error ? reason.message : String(reason));
setMessages((current) => setMessages((current) =>
current.map((item) => current.map((item) =>
item.id === id ? { ...item, error: true } : item, item.id === id ? { ...item, error: true } : item,
@ -453,7 +452,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
); );
setError(null); setError(null);
} catch (reason) { } catch (reason) {
setError(errorMessage(reason)); setError(reason instanceof Error ? reason.message : String(reason));
} }
}; };
@ -500,7 +499,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
setStatus((current) => ({ ...current, [selectedSlot]: result })); setStatus((current) => ({ ...current, [selectedSlot]: result }));
setError(null); setError(null);
} catch (reason) { } catch (reason) {
setError(errorMessage(reason)); setError(reason instanceof Error ? reason.message : String(reason));
} }
}; };
@ -523,7 +522,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
setStatus((current) => ({ ...current, [selectedSlot]: result })); setStatus((current) => ({ ...current, [selectedSlot]: result }));
setError(null); setError(null);
} catch (reason) { } catch (reason) {
setError(errorMessage(reason)); setError(reason instanceof Error ? reason.message : String(reason));
} }
}; };
@ -534,7 +533,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
}); });
await refresh(); await refresh();
} catch (reason) { } catch (reason) {
setError(errorMessage(reason)); setError(reason instanceof Error ? reason.message : String(reason));
} }
}; };
@ -698,7 +697,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
.then(() => void refresh()) .then(() => void refresh())
.catch((reason) => .catch((reason) =>
setError( setError(
errorMessage(reason), reason instanceof Error ? reason.message : String(reason),
), ),
); );
}} }}
@ -985,7 +984,7 @@ function applyRuntimeEvents(
return next; return next;
} }
function formatSessionTime(value?: string | null): string { function formatSessionTime(value?: string): string {
if (!value) return "本地历史"; if (!value) return "本地历史";
const date = new Date(value); const date = new Date(value);
if (Number.isNaN(date.getTime())) return "本地历史"; if (Number.isNaN(date.getTime())) return "本地历史";

查看文件

@ -1,54 +0,0 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { MessageContent } from "./MessageContent";
vi.mock("@tauri-apps/api/core", () => ({
invoke: vi.fn(async () => {
throw new Error("not available in tests");
}),
}));
describe("MessageContent link safety", () => {
it("renders javascript: links as plain text instead of anchors", () => {
const { container } = render(
<MessageContent content="[x](javascript:alert(1))" slot="companion" />,
);
expect(container.querySelector("a")).toBeNull();
expect(screen.getByText("[x](javascript:alert(1))")).toBeInTheDocument();
});
it("renders data: links as plain text instead of anchors", () => {
const { container } = render(
<MessageContent
content="[x](data:text/html,<script>alert(1)</script>)"
slot="companion"
/>,
);
expect(container.querySelector("a")).toBeNull();
});
it("keeps http and https links and marks them noopener", () => {
const { container } = render(
<MessageContent
content="[docs](https://example.com/guide)"
slot="companion"
/>,
);
const anchor = container.querySelector("a");
expect(anchor).not.toBeNull();
expect(anchor).toHaveAttribute("href", "https://example.com/guide");
expect(anchor?.getAttribute("rel")).toContain("noopener");
});
it("does not turn relative hrefs into absolute placeholder links", () => {
const { container } = render(
<MessageContent content="[x](/local/path)" slot="companion" />,
);
expect(container.querySelector("a")).toBeNull();
});
});

查看文件

@ -1,7 +1,6 @@
import { Fragment, useEffect, useState, type ReactNode } from "react"; import { Fragment, useEffect, useState, type ReactNode } from "react";
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { safeLinkHref } from "../../lib/safeLinkHref";
import type { ChatSlot } from "./types"; import type { ChatSlot } from "./types";
type MessageContentProps = { type MessageContentProps = {
@ -66,12 +65,8 @@ function renderInline(
} }
const link = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/); const link = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
if (link) { if (link) {
const href = safeLinkHref(link[2]);
if (!href) {
return <Fragment key={key}>{token}</Fragment>;
}
return ( return (
<a key={key} href={href} target="_blank" rel="noopener noreferrer"> <a key={key} href={link[2]} target="_blank" rel="noreferrer">
{link[1]} {link[1]}
</a> </a>
); );

查看文件

@ -1,11 +1,8 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { import {
astrbotCapabilitySnapshotSchema,
boundRuntimeEventSchema,
chatSessionSchema, chatSessionSchema,
mergeLoadedChatMessages, mergeLoadedChatMessages,
remoteChatSessionSchema,
storedChatMessageSchema, storedChatMessageSchema,
} from "./types"; } from "./types";
@ -45,47 +42,6 @@ describe("chat persistence IPC schemas", () => {
).toMatchObject({ content: "hello" }); ).toMatchObject({ content: "hello" });
}); });
// Regression guard for the Rust `Option::None` -> JSON `null` boundary.
// `.optional()` only accepts `undefined`, so these payloads used to fail
// validation and were dropped without any user-visible signal.
it("accepts null session and message ids on runtime events", () => {
expect(
boundRuntimeEventSchema.parse({
profileId: "profile-1",
slot: "companion",
eventId: "event-1",
eventType: "message.delta",
serverInstanceId: "server-1",
sessionId: null,
messageId: null,
payload: { delta: "hi", index: 0 },
}),
).toMatchObject({ eventId: "event-1" });
});
it("accepts null display names and timestamps on remote sessions", () => {
expect(
remoteChatSessionSchema.array().parse([
{ sessionId: "session-1", displayName: null, updatedAt: null },
{ sessionId: "session-2", displayName: "named", updatedAt: null },
]),
).toHaveLength(2);
});
it("accepts null model names in the capability snapshot", () => {
expect(
astrbotCapabilitySnapshotSchema.parse({
transport: "astrbot-openapi",
textChat: true,
streaming: true,
modelSelection: true,
fileUpload: true,
imageInput: true,
models: [{ id: "model-a", name: null, isDefault: null }],
}).models,
).toHaveLength(1);
});
it("replaces loaded session messages without duplicating optimistic users", () => { it("replaces loaded session messages without duplicating optimistic users", () => {
const record = { const record = {
accountId: "local-default", accountId: "local-default",

查看文件

@ -32,11 +32,8 @@ export const boundRuntimeEventSchema = z
eventId: z.string().min(1), eventId: z.string().min(1),
eventType: z.string().min(1), eventType: z.string().min(1),
serverInstanceId: z.string().min(1), serverInstanceId: z.string().min(1),
// Rust serializes `Option::None` as `null`, not as an absent key, so these sessionId: z.string().min(1).optional(),
// must accept null. `.optional()` here made every event without a session messageId: z.string().min(1).optional(),
// or message id fail validation and be dropped silently.
sessionId: z.string().min(1).nullish(),
messageId: z.string().min(1).nullish(),
payload: z.unknown(), payload: z.unknown(),
}) })
.strict(); .strict();
@ -64,8 +61,8 @@ export type ChatSession = z.infer<typeof chatSessionSchema>;
export const remoteChatSessionSchema = z.object({ export const remoteChatSessionSchema = z.object({
sessionId: z.string().min(1), sessionId: z.string().min(1),
displayName: z.string().min(1).nullish(), displayName: z.string().min(1).optional(),
updatedAt: z.string().min(1).nullish(), updatedAt: z.string().min(1).optional(),
}); });
export type RemoteChatSession = z.infer<typeof remoteChatSessionSchema>; export type RemoteChatSession = z.infer<typeof remoteChatSessionSchema>;
@ -156,8 +153,8 @@ export function mergeLoadedChatMessages(
export const astrbotModelOptionSchema = z.object({ export const astrbotModelOptionSchema = z.object({
id: z.string().min(1), id: z.string().min(1),
name: z.string().min(1).nullish(), name: z.string().min(1).optional(),
isDefault: z.boolean().nullish(), isDefault: z.boolean().optional(),
}); });
export const astrbotAttachmentSchema = z.object({ export const astrbotAttachmentSchema = z.object({

查看文件

@ -89,7 +89,7 @@ export function DesktopPetView({ embedded = false }: { embedded?: boolean }) {
setSpriteReady(true); setSpriteReady(true);
}; };
image.onerror = () => { image.onerror = () => {
setSpriteError("桌宠精灵图加载失败。"); setSpriteError("????????");
}; };
image.src = AEMEATH_SPRITESHEET; image.src = AEMEATH_SPRITESHEET;
return () => { return () => {
@ -170,7 +170,7 @@ export function DesktopPetView({ embedded = false }: { embedded?: boolean }) {
if (!canvas || !image || !spriteReady) return; if (!canvas || !image || !spriteReady) return;
const context = canvas.getContext("2d"); const context = canvas.getContext("2d");
if (!context) { if (!context) {
setSpriteError("无法获取 Canvas 绘图上下文。"); setSpriteError("???? Canvas ?????");
return; return;
} }
try { try {
@ -188,18 +188,14 @@ export function DesktopPetView({ embedded = false }: { embedded?: boolean }) {
208, 208,
); );
} catch (reason) { } catch (reason) {
setSpriteError( setSpriteError(reason instanceof Error ? reason.message : "??????");
reason instanceof Error
? reason.message
: "桌宠精灵图绘制失败。",
);
} }
}, [frameColumn, frameRow, spriteReady]); }, [frameColumn, frameRow, spriteReady]);
return ( return (
<main <main
className={`pet-window pet-window-${state}${gameMode ? " pet-window-game" : ""}${embedded ? " pet-window-embedded" : ""}`} className={`pet-window pet-window-${state}${gameMode ? " pet-window-game" : ""}${embedded ? " pet-window-embedded" : ""}`}
aria-label="AstrBot 桌宠" aria-label="AstrBot ??"
data-tauri-drag-region={!embedded ? "true" : undefined} data-tauri-drag-region={!embedded ? "true" : undefined}
onMouseDown={(event) => { onMouseDown={(event) => {
if (embedded || event.button !== 0) return; if (embedded || event.button !== 0) return;

查看文件

@ -1,37 +0,0 @@
import { describe, expect, it } from "vitest";
import aemeathManifest from "./assets/aemeath/manifest.json";
import { petPackManifestSchema } from "./types";
describe("pet pack manifest schema", () => {
// Regression: the image pattern used `\\.` instead of `\.`, which required a
// literal backslash in the file name and therefore rejected every valid pack,
// including the one shipped in this repository.
it("accepts the bundled aemeath manifest", () => {
expect(petPackManifestSchema.parse(aemeathManifest).image).toBe(
"aemeath-spritesheet.png",
);
});
it("accepts plain png and webp file names", () => {
for (const image of ["pet.png", "pet.webp", "my-pet_v2.PNG"]) {
expect(
petPackManifestSchema.parse({ ...aemeathManifest, image }).image,
).toBe(image);
}
});
it("rejects path traversal and unsupported extensions", () => {
for (const image of [
"../escape.png",
"nested/pet.png",
"C:\\pet.png",
"pet.gif",
"pet.png.exe",
]) {
expect(() =>
petPackManifestSchema.parse({ ...aemeathManifest, image }),
).toThrow();
}
});
});

查看文件

@ -44,7 +44,7 @@ export const petPackManifestSchema = z
format: z.literal("astrbot-pet-pack.v1"), format: z.literal("astrbot-pet-pack.v1"),
name: z.string().min(1).max(80), name: z.string().min(1).max(80),
version: z.string().min(1).max(32), version: z.string().min(1).max(32),
image: z.string().regex(/^[^\\/:*?"<>|]+\.(png|webp)$/i), image: z.string().regex(/^[^\\/:*?"<>|]+\\.(png|webp)$/i),
width: z.number().int().positive().max(4096), width: z.number().int().positive().max(4096),
height: z.number().int().positive().max(4096), height: z.number().int().positive().max(4096),
frameWidth: z.number().int().positive().max(1024), frameWidth: z.number().int().positive().max(1024),

查看文件

@ -21,7 +21,6 @@ import {
type UpdateConnectionProfileRequest, type UpdateConnectionProfileRequest,
} from "../../types/profile"; } from "../../types/profile";
import { connectionRuntimeStatusSchema } from "../chat/types"; import { connectionRuntimeStatusSchema } from "../chat/types";
import { errorMessage } from "../../lib/errorMessage";
import { CredentialEnrollmentCard } from "./CredentialEnrollmentCard"; import { CredentialEnrollmentCard } from "./CredentialEnrollmentCard";
interface ProfileFormState { interface ProfileFormState {
@ -686,3 +685,18 @@ function slotLabel(slot: ActiveSlotKind) {
function connectionStateLabel(state: ConnectionSlot["state"]) { function connectionStateLabel(state: ConnectionSlot["state"]) {
return state === "disconnected" ? "未连接" : state; return state === "disconnected" ? "未连接" : state;
} }
function errorMessage(reason: unknown) {
if (reason instanceof Error) {
return reason.message;
}
if (
typeof reason === "object" &&
reason !== null &&
"message" in reason &&
typeof reason.message === "string"
) {
return reason.message;
}
return String(reason);
}

查看文件

@ -1,38 +0,0 @@
/**
* Normalizes a rejection reason into a human-readable string.
*
* Tauri `invoke` rejects with the deserialized Rust error value, which is a
* plain object (for example `RuntimeCommandError { code, message }`) rather
* than an `Error` instance. Passing such a value to `String()` yields
* "[object Object]", so every IPC failure has to go through this helper.
*/
export function errorMessage(reason: unknown): string {
if (reason instanceof Error) {
return reason.message;
}
if (typeof reason === "string") {
return reason;
}
if (typeof reason === "object" && reason !== null) {
const candidate = reason as { message?: unknown; code?: unknown };
if (typeof candidate.message === "string" && candidate.message.length > 0) {
return candidate.message;
}
if (typeof candidate.code === "string" && candidate.code.length > 0) {
return candidate.code;
}
}
return String(reason);
}
/** Rust returns this code when a request was cancelled on purpose. */
export const CANCELLED_ERROR_CODE = "cancelled";
/** True when a rejection reason is a deliberate cancellation rather than a failure. */
export function isCancelledError(reason: unknown): boolean {
return (
typeof reason === "object" &&
reason !== null &&
(reason as { code?: unknown }).code === CANCELLED_ERROR_CODE
);
}

查看文件

@ -1,24 +0,0 @@
const SAFE_LINK_PROTOCOLS = new Set(["http:", "https:", "mailto:"]);
/** Placeholder base used to resolve relative hrefs without a real origin. */
const RESOLUTION_BASE = "https://astrbot.invalid/";
/**
* Assistant messages come from a remote AstrBot instance and are untrusted.
* Only well-known navigation protocols may reach an anchor href; anything else
* (`javascript:`, `data:`, `file:`, custom schemes) is rejected so the caller
* can render the original markdown as plain text.
*/
export function safeLinkHref(raw: string): string | null {
const candidate = raw.trim();
if (!candidate) return null;
try {
const parsed = new URL(candidate, RESOLUTION_BASE);
if (!SAFE_LINK_PROTOCOLS.has(parsed.protocol)) return null;
// Relative inputs resolve against the placeholder base and must not be
// presented as if they pointed at a real destination.
return parsed.href.startsWith(RESOLUTION_BASE) ? null : parsed.href;
} catch {
return null;
}
}

查看文件

@ -1,7 +1,6 @@
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { useState } from "react"; import { useState } from "react";
import { errorMessage } from "../lib/errorMessage";
import type { BootstrapStatus } from "../types/bootstrap"; import type { BootstrapStatus } from "../types/bootstrap";
export type SettingsChatSlot = "companion" | "operations"; export type SettingsChatSlot = "companion" | "operations";
@ -118,7 +117,7 @@ function DiagnosticsTools() {
); );
setResult(JSON.stringify(value, null, 2)); setResult(JSON.stringify(value, null, 2));
} catch (reason) { } catch (reason) {
setResult(errorMessage(reason)); setResult(reason instanceof Error ? reason.message : String(reason));
} finally { } finally {
setBusy(false); setBusy(false);
} }