@chen_hu_hu/pi-qq 1.3.5 → 1.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.3.6] - 2026-11-04
11
+
12
+ ### Added
13
+
14
+ - Debug timing logs for tool stream enqueue/append, stream buffer/flush timers, and event-loop delay. They are written only at `logLevel: "debug"` and do not change runtime behavior.
15
+
10
16
  ## [1.3.5] - 2026-11-04
11
17
 
12
18
  ### Added
@@ -79,7 +85,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
79
85
  - Added thinking labels, per-tool icons, model-error recovery, and idle-safe session handling.
80
86
  - Reorganized modules by bounded context and updated settings and delivery documentation.
81
87
 
82
- [Unreleased]: https://github.com/CQ-Developer/pi-qq/compare/v1.3.5...HEAD
88
+ [Unreleased]: https://github.com/CQ-Developer/pi-qq/compare/v1.3.6...HEAD
89
+ [1.3.6]: https://github.com/CQ-Developer/pi-qq/compare/v1.3.5...v1.3.6
83
90
  [1.3.5]: https://github.com/CQ-Developer/pi-qq/compare/v1.3.4...v1.3.5
84
91
  [1.3.4]: https://github.com/CQ-Developer/pi-qq/compare/v1.3.3...v1.3.4
85
92
  [1.3.3]: https://github.com/CQ-Developer/pi-qq/compare/v1.3.2...v1.3.3
package/doc/todo.md ADDED
@@ -0,0 +1,79 @@
1
+ # TODO
2
+
3
+ ## 1. 长运行 bash 工具的参数延迟显示
4
+
5
+ > 状态:TODO,等待长期使用日志
6
+ > 记录日期:2026-11-04
7
+ > 相关版本:pi-qq 1.3.6(仅增加 debug 日志)
8
+
9
+ ### 现象
10
+
11
+ 正常使用中,bash 执行 e2e 测试通常需要数分钟。此时 QQ 上只能看到 `bash` 和一个点,看不到命令参数;理论上工具名称和参数应该在 `tool_execution_start` 后立即出现,只有结果需要等待工具结束。
12
+
13
+ ### 已知事实
14
+
15
+ - `AppendStream` 默认有 500ms 节流;这是 pi-qq 自己设置的值,不是 QQ 限制。
16
+ - 500ms 定时器不依赖工具 Promise;长工具的启动帧曾在工具结束前通过 `stream_messages` 发出。
17
+ - pi 内置 bash 使用异步 `spawn`,正常情况下不会阻塞 Node 事件循环。
18
+ - 本地异步子进程可持续触发 500ms timer,说明“bash 子进程本身”不是必然的事件循环阻塞源。
19
+ - 当前还没有这次 e2e 的长期使用日志,无法判断:
20
+ - 启动帧是否真的发出;
21
+ - `content_raw` 是否包含命令;
22
+ - timer/队列/事件循环是否被延迟;
23
+ - QQ 是否把长行内代码折叠成了一个点。
24
+
25
+ ### 已经添加的诊断日志
26
+
27
+ 版本 1.3.6 只增加了 debug 日志,没有改变行为:
28
+
29
+ - `scope: "stream"`,`msgKey: "log.streamTiming"`:
30
+ - `phase: "tool queued"`:工具行进入队列;
31
+ - `phase: "append start"`:队列开始处理,包含 `waitedMs`;
32
+ - `phase: "append done"`:队列处理完成,包含 `totalMs`。
33
+ - `AppendStream.onDebug`(同 scope `"stream"`):
34
+ - `append: buffered/immediate/while flushing`;
35
+ - `timer: fired after ...`;
36
+ - `flush: start/done`。
37
+ - `scope: "event-loop"`,`msgKey: "log.eventLoopDelay"`:
38
+ - 每 5 秒记录一次 `meanMs`、`maxMs`、`p99Ms`。
39
+
40
+ 所有日志只在 `logLevel: "debug"` 时写入:
41
+
42
+ ```json
43
+ {
44
+ "logLevel": "debug"
45
+ }
46
+ ```
47
+
48
+ 日志路径:
49
+
50
+ ```text
51
+ <cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log
52
+ ```
53
+
54
+ ### 下次日志分析步骤
55
+
56
+ 1. 找到 e2e 的 `toolStart`:
57
+ - `scope: "tool"`
58
+ - `toolName: "bash"`
59
+ - `args` 是否包含完整 `command`。
60
+ 2. 找到随后 `scope: "stream"` 的时序日志:
61
+ - `tool queued` 时间;
62
+ - `append start` 的 `waitedMs`;
63
+ - `append done` 的 `totalMs`;
64
+ - `append: buffered` / `timer: fired` / `flush: start` 时间。
65
+ 3. 找到对应的 `POST .../stream_messages`:
66
+ - 请求时间;
67
+ - `content_raw` 是否包含命令参数。
68
+ 4. 对照 `scope: "event-loop"` 的 `maxMs` / `p99Ms`:
69
+ - 如果事件循环延迟达到数秒/数分钟,说明 Node 主线程被饿死;
70
+ - 如果 event-loop 正常,但 `append start` 的 `waitedMs` 很大,说明前面的流/队列阻塞;
71
+ - 如果 POST 很快且 `content_raw` 有命令,但 QQ 只显示一个点,说明是 QQ 渲染/截断。
72
+
73
+ ### 下一步
74
+
75
+ - 收集长期使用日志后,确定是事件循环、队列、网络还是 QQ 渲染问题。
76
+ - 如果是队列/缓冲问题,考虑给工具启动行增加 `flushAfter`。
77
+ - 如果是长命令渲染问题,考虑把参数从行内代码改成 fenced code block,或显示更短的命令摘要。
78
+ - 如果是 e2e CPU 导致的事件循环饥饿,需要评估 TUI/tool output 的同步开销,或把 relay 移出主进程。
79
+ - 修复后补测试、更新 `doc/tool-return.md`,再发布版本。
@@ -0,0 +1,378 @@
1
+ # 工具启动信息延迟回传调研
2
+
3
+ > 状态:调研/设计文档,尚未实现
4
+ > 日期:2026-11-04
5
+ > 涉及版本:pi-qq 1.3.5
6
+ > 现象:工具开始执行后,QQ 侧要等到工具结束才一起看到工具名称、参数和结果;希望工具名称和参数在 `tool_execution_start` 时立即回传。
7
+
8
+ ## 1. 问题
9
+
10
+ 当前 QQ 侧的工具气泡通常是“工具名称 + 参数 + 结果”一起出现,而不是:
11
+
12
+ 1. 工具一开始执行,就先显示名称和参数;
13
+ 2. 工具结束后,再补充结果。
14
+
15
+ 这会让用户误以为工具没有开始,尤其在工具执行时间短、但结果返回稍慢时。
16
+
17
+ ## 2. 现象与证据
18
+
19
+ ### 2.1 日志时间线
20
+
21
+ 测试日志:
22
+
23
+ ```text
24
+ /home/chen/project/pi-qq-test/.pi/pi-qq/logs/pi-qq-2026-11-04.log
25
+ ```
26
+
27
+ 其中一次 bash 工具的时间线:
28
+
29
+ ```text
30
+ 06:34:36.068 tool start bash which playwright-cli ...
31
+ 06:34:36.414 tool end bash (0.3s)
32
+ 06:34:36.827 stream bubble split
33
+ ```
34
+
35
+ 工具在 `36.068` 开始,`36.414` 结束,直到 `36.827` 才发生流式气泡切分/刷新。
36
+ 也就是说,工具启动信息没有在 `36.068` 立即形成可见的 QQ 流式帧,而是和后续结果一起进入了同一次发送窗口。
37
+
38
+ 另一个长工具:
39
+
40
+ ```text
41
+ 06:34:38.295 tool start bash playwright-cli open ...
42
+ 06:34:38.777 stream bubble split (约 482ms 后)
43
+ 06:34:42.014 tool end
44
+ ```
45
+
46
+ 这个工具的启动行在约 500ms 后才被刷新。
47
+
48
+ ### 2.2 当前代码路径
49
+
50
+ `index.ts` 收到 `tool_execution_start` 后调用:
51
+
52
+ ```ts
53
+ void runFeedback.onToolStart(event.toolName, event.args, event.toolCallId);
54
+ ```
55
+
56
+ `RunFeedback.onToolStart()` 把工具加入队列并调用 `startNextTool()`:
57
+
58
+ ```ts
59
+ run.tools.push({ id, name, toolName, args, started: false, finished: false });
60
+ this.startNextTool(run);
61
+ ```
62
+
63
+ `startNextTool()` 调用:
64
+
65
+ ```ts
66
+ run.writer.pushTool(tool.name, tool.args);
67
+ ```
68
+
69
+ `BubbleWriter.pushTool()` 把工具行包装成一次普通的 `push()`:
70
+
71
+ ```ts
72
+ this.push(`${prefix}${formatToolLine(name, args)}\n\n`, ...);
73
+ ```
74
+
75
+ `push()` 只是把 append 操作排入队列:
76
+
77
+ ```ts
78
+ await stream.append(outgoing);
79
+ ```
80
+
81
+ 这里没有调用 `stream.flush()`。
82
+
83
+ ### 2.3 关键原因:`AppendStream` 的节流缓冲
84
+
85
+ `src/relay/stream-session.ts` 的 `append()`:
86
+
87
+ ```ts
88
+ this.buffer += delta;
89
+ const elapsed = Date.now() - this.lastFlushAt;
90
+ if (this.flushing) return;
91
+ if (elapsed >= this.throttleMs()) {
92
+ await this.doFlush("generating");
93
+ return;
94
+ }
95
+ if (!this.flushTimer) {
96
+ this.flushTimer = setTimeout(() => {
97
+ this.flushTimer = null;
98
+ void this.doFlush("generating").catch(...);
99
+ }, this.throttleMs() - elapsed);
100
+ }
101
+ ```
102
+
103
+ 默认节流窗口是 500ms(最小 300ms)。因此:
104
+
105
+ - 如果上一次流式帧刚刚发送,工具启动行会先进入 buffer;
106
+ - 工具在 500ms 内结束,结果也进入同一个 buffer;
107
+ - 定时器到点后,工具行和结果被一起发送。
108
+
109
+ 这就是“工具名称和参数等结果一起出现”的直接原因。
110
+
111
+ ### 2.4 500ms 到点后,是否还要等工具结束?
112
+
113
+ 不需要。500ms 定时器是普通 Node 定时器,**不依赖工具 Promise 完成**;只要事件循环没有被工具阻塞,它会在 500ms 左右触发并把 buffer 发出。
114
+
115
+ 上面的长工具日志可以证明这一点:
116
+
117
+ ```text
118
+ 06:34:38.295 tool start bash
119
+ 06:34:38.777 POST stream_messages content_raw: "**💻 bash** ..."
120
+ 06:34:42.014 tool end
121
+ ```
122
+
123
+ 启动行在 `38.777` 已经通过 `stream_messages` 发出,此时工具还在执行,直到 `42.014` 才结束。因此:
124
+
125
+ - **长工具**:启动行会在约 500ms 后先发出,不会等结果;
126
+ - **短工具**:结果在 500ms 内进入同一 buffer,才会和启动行一起发出;
127
+ - **真正会等到工具结束的情况**:工具同步阻塞了 Node 事件循环,定时器无法触发;或使用并行工具时被 `activeTool` 串行策略挡住。
128
+
129
+ `bash`、`read` 等 pi 内置工具使用异步子进程/文件 IO,不会阻塞事件循环;CPU 密集的自定义工具、同步插件代码可能阻塞,需要单独排查。
130
+
131
+ ### 2.5 第二个原因:并行工具被串行排队
132
+
133
+ `RunFeedback.startNextTool()` 有一个 `activeTool` 保护:
134
+
135
+ ```ts
136
+ if (run.writer.dead || run.activeTool) return;
137
+ ```
138
+
139
+ 只有当前工具结束后,才会启动下一个工具的输出:
140
+
141
+ ```ts
142
+ run.activeTool = undefined;
143
+ this.startNextTool(run);
144
+ ```
145
+
146
+ 因此,当 pi 并行启动多个工具时:
147
+
148
+ - 第一个工具的启动行会先进入队列;
149
+ - 第二个工具的启动行要等第一个工具结束;
150
+ - 用户看到的工具启动信息仍然是串行的。
151
+
152
+ 对单个工具来说,主因是 `AppendStream` 节流;对并行工具来说,还有 `RunFeedback` 的串行输出策略。
153
+
154
+ ### 2.6 长 e2e 命令只显示 `bash` + 一个点
155
+
156
+ 用户反馈:bash 执行 e2e 测试数分钟时,QQ 上只看到 `bash` 和一个点,看不到命令参数。
157
+
158
+ 这不是“等待结果后一起推送”的典型表现;如果长时间工具已经超过 500ms,启动帧通常已经发出(前面的日志已验证)。需要区分:
159
+
160
+ 1. **启动帧确实包含命令,但 QQ 只渲染出一个点/省略号**
161
+ - `formatToolLine()` 把命令放在行内代码中,并对参数做 200 字符截断,末尾是 `…`;
162
+ - 超长命令、包含反引号或特殊 Markdown 字符时,QQ 可能折叠/截断行内代码,只留下一个小点或省略号;
163
+ - 此时日志中的 `POST stream_messages` 的 `content_raw` 仍然应该包含完整或截断后的命令。
164
+
165
+ 2. **启动帧没有命令参数**
166
+ - `tool_execution_start` 的 `args` 缺失/不是 `{command: string}`;
167
+ - `formatToolLine()` 的 `primaryArg()` 没有取到 `command`;
168
+ - 需要检查 `scope":"tool"` 的 `toolStart` 日志和同时间的 `stream_messages` 请求体。
169
+
170
+ 3. **启动帧没有在 500ms 后发出**
171
+ - 工具/主进程阻塞了 Node 事件循环;
172
+ - 并行工具被 `activeTool` 串行策略挡住;
173
+ - 需要看日志中 tool start 后是否有 `stream_messages` POST。
174
+
175
+ 当前工作区没有该次 e2e 的日志(`pi-qq-test` 只有 14:34 的一次运行),因此还无法确认是 1、2 还是 3。需要用户提供:
176
+
177
+ - e2e 的 bash 命令或 QQ 截图;
178
+ - 对应时间段的 `pi-qq-YYYY-MM-DD.log`;
179
+ - `scope":"tool"` 的 `toolStart` 行;
180
+ - 紧随其后的 `POST .../stream_messages` 的 `content_raw`。
181
+
182
+ 如果确认是长命令渲染问题,建议把工具参数从行内代码改为 fenced code block,或只显示命令摘要,避免 QQ 把长行内代码折叠成一个点。
183
+
184
+ ### 2.7 是否是 Node 事件循环阻塞导致的?
185
+
186
+ 目前不能直接归因于 `bash` 工具本身。pi 的内置 bash 工具使用 `node:child_process.spawn` 启动子进程,然后异步等待子进程结束;它不是 `spawnSync`,正常情况下不会阻塞 Node 事件循环。
187
+
188
+ 本地用同样的异步子进程做验证:
189
+
190
+ ```js
191
+ const child = spawn("bash", ["-lc", "sleep 3; echo done"]);
192
+ setInterval(() => console.log(Date.now() - start), 500);
193
+ ```
194
+
195
+ 结果:
196
+
197
+ ```text
198
+ tick 1 at 501ms
199
+ tick 2 at 1002ms
200
+ ...
201
+ child finished at 3018ms, ticks=6
202
+ ```
203
+
204
+ 即子进程运行 3 秒期间,定时器正常触发。pi 的 bash 路径也是同一个模型:`spawn` + stdout/stderr 异步事件 + `await` 子进程退出。
205
+
206
+ pi-qq 侧也没有在 `onToolStart()` 里等待工具结果:
207
+
208
+ ```ts
209
+ onToolStart(...) {
210
+ ...
211
+ this.startNextTool(run); // 同步返回
212
+ }
213
+ ```
214
+
215
+ `AppendStream` 的 500ms 定时器是独立的 Node timer,工具 Promise 尚未完成不会阻止它。
216
+
217
+ 因此,单次 bash 工具本身**不应该**让 QQ 参数等几分钟。还需要排查以下可能:
218
+
219
+ 1. **e2e 子进程把 CPU 吃满**:Node 父进程可能被严重饿死,timer 实际延迟;需要看系统 CPU/Nice 和 event-loop lag。
220
+ 2. **pi TUI 处理大量 tool update/输出**:大量同步渲染可能占用主线程,延迟 timer。
221
+ 3. **`BubbleWriter` 队列被之前的网络请求阻塞**:如果前一个 `stream.flush()`/HTTP 请求卡住,新的工具启动 append 会排在它后面;`ApiClient` 单个请求有 30s 超时,但多次重试/排队可能造成较长延迟。
222
+ 4. **并行工具被 `activeTool` 串行化**:后面工具的启动行要等前一个工具结束,这一条与事件循环无关。
223
+ 5. **启动帧已经发出,但 QQ 没有渲染出参数**:需要对照日志中的 `content_raw` 和截图,而不能只看聊天界面。
224
+
225
+ 区分方法:
226
+
227
+ - 如果日志中 `POST .../stream_messages` 的 `content_raw` 在 tool start 后约 500ms 就包含完整命令,但 QQ 只显示 bash + 点,则是 QQ 渲染/截断问题,不是事件循环。
228
+ - 如果 POST 直到 tool end 后才出现,则说明 timer 或前面的队列被阻塞,再结合 event-loop lag 定位。
229
+ - 如果 POST 在 500ms 出现但 `content_raw` 不含 command,则检查 `tool_execution_start` 的 `args` 和 `formatToolLine()`。
230
+
231
+ 建议在 `index.ts` 或 `file-logger` 增加临时诊断:
232
+
233
+ ```ts
234
+ import { monitorEventLoopDelay } from "node:perf_hooks";
235
+ const lag = monitorEventLoopDelay({ resolution: 100 });
236
+ lag.enable();
237
+ // 定期 log.debug("event-loop", "lag", { maxMs: lag.max / 1e6, meanMs: lag.mean / 1e6 });
238
+ ```
239
+
240
+ 并在 tool start、`BubbleWriter` enqueue、`stream.flush` 前后记录时间戳。这样可以直接判断是“事件循环被饿死”还是“队列/网络/渲染”导致。
241
+
242
+ ## 3. 影响
243
+
244
+ - 用户无法从 QQ 判断工具是否已经开始执行;
245
+ - 工具参数在结果出现前不可见,降低了可观测性;
246
+ - 长工具和短工具的体验不一致:
247
+ - 短工具:名称、参数、结果一起出现;
248
+ - 长工具:约 500ms 后才出现启动行;
249
+ - 与 pi TUI 的工具执行状态不一致。
250
+
251
+ ## 4. 解决方案
252
+
253
+ ### 4.1 工具启动后立即 flush
254
+
255
+ 在 `BubbleWriter.push()` 增加一个 `flushAfter` 参数:
256
+
257
+ ```ts
258
+ private push(
259
+ text: string,
260
+ blockBoundary = false,
261
+ endTool = false,
262
+ newBubble = false,
263
+ thinking = false,
264
+ flushAfter = false,
265
+ ): void
266
+ ```
267
+
268
+ 在 append 成功后,如果 `flushAfter` 为 true,调用:
269
+
270
+ ```ts
271
+ await stream.flush();
272
+ ```
273
+
274
+ `pushTool()` 传入 `flushAfter = true`:
275
+
276
+ ```ts
277
+ this.push(
278
+ `${prefix}${formatToolLine(name, args)}\n\n`,
279
+ ...,
280
+ true, // flushAfter
281
+ );
282
+ ```
283
+
284
+ 这样工具启动操作会在同一队列任务内完成 append + flush,结果操作排在它之后,不会被合并到同一个 buffer。
285
+
286
+ 需要注意:
287
+
288
+ - `flush()` 本身会立即发送当前 buffer,不受 500ms 节流限制;
289
+ - flush 失败要进入现有 `handleStreamError()` 流程;
290
+ - 不需要对每个文本 delta 都 flush,只对工具启动行做;
291
+ - 如果工具启动行和上一条文本在同一气泡,flush 也会把上一条文本一起发出,这是可接受的。
292
+
293
+ ### 4.2 处理并行工具启动
294
+
295
+ 如果希望并行工具也能立即显示启动行,需要把“启动行发送”和“结果发送”解耦:
296
+
297
+ - 在 `onToolStart()` 中立即发送启动行;
298
+ - 在 `onToolEnd()` 中发送结果;
299
+ - 用 `tool.startLineSent` 避免重复;
300
+ - 结果仍可按工具完成顺序或启动顺序输出。
301
+
302
+ 第一版可以只做 4.1,解决单工具的“启动行等结果”问题;并行工具的启动延迟作为后续优化。
303
+
304
+ ### 4.3 不建议的方案
305
+
306
+ - **降低 throttle 到 0**:会增加 QQ 流式 API 调用频率,且不能保证工具启动瞬间发送;
307
+ - **在 `pushToolResult()` 里 flush**:只能让结果更快,不能解决启动行延迟;
308
+ - **每个 delta 都 flush**:网络调用过多,容易触发限流;
309
+ - **把工具启动和结果拆成两个独立消息**:会破坏现有同泡工具时间线,且增加消息数量。
310
+
311
+ ## 5. 测试计划
312
+
313
+ ### 单元测试
314
+
315
+ 1. 在 `BubbleWriter` 测试中注入一个记录 `flush` 的 fake stream,验证:
316
+ - `pushTool()` 后立即调用 `flush()`;
317
+ - `pushText()` 不会额外 flush;
318
+ - `pushToolResult()` 不会把启动行和结果合并。
319
+ 2. 用 fake timers 模拟 500ms 节流窗口:
320
+ - 工具启动后立刻检查 flush 调用;
321
+ - 工具结束后结果仍然追加到同一气泡。
322
+ 3. 现有 relay 测试继续通过:
323
+ - 工具顺序;
324
+ - 并行工具结果归属;
325
+ - 流式熔断 fallback。
326
+
327
+ ### 集成验证
328
+
329
+ 在 `pi-qq-test` 中执行一个 300ms 左右的 bash 工具,记录:
330
+
331
+ - `tool start` 时间;
332
+ - QQ 上工具名称/参数出现时间;
333
+ - `tool end` 时间;
334
+ - 结果出现时间。
335
+
336
+ 目标是:
337
+
338
+ ```text
339
+ tool start -> QQ 立即显示工具名称和参数
340
+ tool end -> QQ 再显示结果
341
+ ```
342
+
343
+ ## 6. 执行计划
344
+
345
+ ### Phase 1:单工具立即 flush
346
+
347
+ - [ ] `BubbleWriter.push()` 增加 `flushAfter`;
348
+ - [ ] `pushTool()` 启用 `flushAfter`;
349
+ - [ ] flush 错误进入 `handleStreamError()`;
350
+ - [ ] 补测试。
351
+
352
+ ### Phase 2:并行工具(可选)
353
+
354
+ - [ ] `ToolCall` 增加 `startLineSent`;
355
+ - [ ] `onToolStart()` 立即发送启动行;
356
+ - [ ] 处理结果顺序和重复;
357
+ - [ ] 补并行测试。
358
+
359
+ ### Phase 3:验证
360
+
361
+ - [ ] lint / typecheck / test / format;
362
+ - [ ] 在 `pi-qq-test` 中复测短工具和长工具;
363
+ - [ ] 对比 QQ 时间线与日志时间戳。
364
+
365
+ ## 7. 变更文件
366
+
367
+ | 文件 | 变更 |
368
+ | ------------------------------------- | ---------------------------------------- |
369
+ | `src/relay/bubble-writer.ts` | `push()` 增加 `flushAfter`;工具启动刷新 |
370
+ | `src/relay/stream-session.ts` | 复用现有 `flush()`,不改节流算法 |
371
+ | `test/relay/run-stream-relay.test.ts` | 工具启动立即 flush 测试 |
372
+ | `doc/tool-return.md` | 本文档 |
373
+
374
+ ## 8. 待确认问题
375
+
376
+ 1. 并行工具是否要求每个工具启动行都立即显示,还是先只解决单工具。
377
+ 2. 工具启动行 flush 是否接受额外的 QQ 流式 API 调用;一般工具数量不多,建议接受。
378
+ 3. 工具启动行和结果是否继续在同一个气泡中;当前设计保持不变。
package/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { join } from "node:path";
3
+ import { monitorEventLoopDelay } from "node:perf_hooks";
3
4
  import { getSettings, readConfig, type Credentials, type ResolvedSettings } from "./src/infra/settings";
4
5
  import { startBot, type BotState, type RunningBot } from "./src/qq/qq-bot";
5
6
  import { runQrLogin, type QrLoginResult } from "./src/qq/qr-login";
@@ -45,6 +46,35 @@ const runFeedback = new RunFeedback({
45
46
  onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
46
47
  });
47
48
 
49
+ const eventLoopDelay = monitorEventLoopDelay({ resolution: 100 });
50
+ let eventLoopTimer: ReturnType<typeof setInterval> | undefined;
51
+
52
+ function roundMs(value: number): number {
53
+ return Math.round((value / 1e6) * 10) / 10;
54
+ }
55
+
56
+ function startEventLoopMonitor(): void {
57
+ if (!isLogEnabled("debug") || eventLoopTimer) return;
58
+ eventLoopDelay.disable();
59
+ eventLoopDelay.reset();
60
+ eventLoopDelay.enable();
61
+ eventLoopTimer = setInterval(() => {
62
+ log.debug("event-loop", "event loop delay", {
63
+ meanMs: roundMs(eventLoopDelay.mean),
64
+ maxMs: roundMs(eventLoopDelay.max),
65
+ p99Ms: roundMs(eventLoopDelay.percentile(99)),
66
+ });
67
+ eventLoopDelay.reset();
68
+ }, 5_000);
69
+ eventLoopTimer.unref?.();
70
+ }
71
+
72
+ function stopEventLoopMonitor(): void {
73
+ if (eventLoopTimer) clearInterval(eventLoopTimer);
74
+ eventLoopTimer = undefined;
75
+ eventLoopDelay.disable();
76
+ }
77
+
48
78
  export default function (pi: ExtensionAPI) {
49
79
  activeSettings = getSettings(readConfig().config);
50
80
  configureI18n(activeSettings.language);
@@ -91,12 +121,14 @@ export default function (pi: ExtensionAPI) {
91
121
  stateDetail = undefined;
92
122
  sessionCtx = undefined;
93
123
  runFeedback.dispose();
124
+ stopEventLoopMonitor();
94
125
  };
95
126
 
96
127
  const startWithCredentials = async (ctx: ExtensionContext, creds: Credentials, allowedOpenid: string) => {
97
128
  const settings = activeSettings;
98
129
  configureLogger(settings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
99
130
  stopIfRunning();
131
+ startEventLoopMonitor();
100
132
  stateDetail = undefined;
101
133
  sessionCtx = ctx;
102
134
  const uploadDir = sessionUploadDir(ctx.cwd, ctx.sessionManager.getSessionId());
@@ -141,6 +173,7 @@ export default function (pi: ExtensionAPI) {
141
173
  pi.on("session_start", async (_event, ctx) => {
142
174
  const { settings, error } = applyConfig(ctx);
143
175
  configureLogger(settings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
176
+ startEventLoopMonitor();
144
177
 
145
178
  const login = getLoginState();
146
179
  log.info("session", "started", {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chen_hu_hu/pi-qq",
3
- "version": "1.3.5",
3
+ "version": "1.3.6",
4
4
  "description": "Connect pi to QQ private chats.",
5
5
  "license": "MIT",
6
6
  "author": "CQ-Developer",
package/src/infra/i18n.ts CHANGED
@@ -214,6 +214,8 @@ const enUS = {
214
214
  "log.messageReceived": "message received",
215
215
  "log.ended": "ended",
216
216
  "log.starting": "starting",
217
+ "log.streamTiming": "stream timing",
218
+ "log.eventLoopDelay": "event loop delay",
217
219
  } as const;
218
220
 
219
221
  export type TranslationKey = keyof typeof enUS;
@@ -426,6 +428,8 @@ const zhCN: Record<TranslationKey, string> = {
426
428
  "log.messageReceived": "收到消息",
427
429
  "log.ended": "已结束",
428
430
  "log.starting": "启动中",
431
+ "log.streamTiming": "流式时序",
432
+ "log.eventLoopDelay": "事件循环延迟",
429
433
  };
430
434
 
431
435
  const dictionaries: Record<Language, Record<TranslationKey, string>> = {
@@ -500,6 +504,8 @@ const LOG_MESSAGE_KEYS: Record<string, TranslationKey> = {
500
504
  start: "log.toolStart",
501
505
  started: "log.sessionStarted",
502
506
  starting: "log.botStarting",
507
+ "stream timing": "log.streamTiming",
508
+ "event loop delay": "log.eventLoopDelay",
503
509
  "starting bot": "log.sessionStartingBot",
504
510
  "starting bot after login failed": "log.startBotAfterLoginFailed",
505
511
  "stream error": "log.streamError",
@@ -77,7 +77,21 @@ export class BubbleWriter {
77
77
  this.toolOpen = true;
78
78
  const newBubble = this.lastKind !== "none";
79
79
  const prefix = this.beginBlock("tool", newBubble);
80
- this.push(`${prefix}${formatToolLine(name, args)}\n\n`, prefix.length > 0 || newBubble, false, newBubble);
80
+ log.debug("stream", "stream timing", {
81
+ phase: "tool queued",
82
+ msgId: this.logMsgId(),
83
+ tool: name,
84
+ at: Date.now(),
85
+ hasStream: Boolean(this.cur),
86
+ });
87
+ this.push(
88
+ `${prefix}${formatToolLine(name, args)}\n\n`,
89
+ prefix.length > 0 || newBubble,
90
+ false,
91
+ newBubble,
92
+ false,
93
+ "tool",
94
+ );
81
95
  }
82
96
 
83
97
  pushSkill(name: string): void {
@@ -85,7 +99,7 @@ export class BubbleWriter {
85
99
  this.toolOpen = false;
86
100
  const newBubble = true;
87
101
  const prefix = this.beginBlock("tool", newBubble);
88
- this.push(`${prefix}${formatSkillBlock(name)}`, prefix.length > 0 || newBubble, false, newBubble);
102
+ this.push(`${prefix}${formatSkillBlock(name)}`, prefix.length > 0 || newBubble, false, newBubble, false, "skill");
89
103
  }
90
104
 
91
105
  pushToolResult(result: unknown, isError: boolean): void {
@@ -221,10 +235,27 @@ export class BubbleWriter {
221
235
  }
222
236
  }
223
237
 
224
- private push(text: string, blockBoundary = false, endTool = false, newBubble = false, thinking = false): void {
238
+ private push(
239
+ text: string,
240
+ blockBoundary = false,
241
+ endTool = false,
242
+ newBubble = false,
243
+ thinking = false,
244
+ trace?: string,
245
+ ): void {
225
246
  if (!text || this.streamDead || this.disposed) return;
247
+ const queuedAt = trace ? Date.now() : 0;
226
248
  void this.enqueue(async () => {
227
249
  if (this.streamDead || this.disposed) return;
250
+ if (trace) {
251
+ log.debug("stream", "stream timing", {
252
+ phase: "append start",
253
+ trace,
254
+ msgId: this.logMsgId(),
255
+ waitedMs: Date.now() - queuedAt,
256
+ hasStream: Boolean(this.cur),
257
+ });
258
+ }
228
259
  if (blockBoundary && !(await this.closeOpenFence())) return;
229
260
  if (newBubble && this.cur && this.bubbleChars > 0 && !this.pendingResume) {
230
261
  await this.rotateStream();
@@ -252,6 +283,15 @@ export class BubbleWriter {
252
283
  this.trackFences(outgoing);
253
284
  this.lastChar = outgoing.slice(-1);
254
285
  if (endTool) this.toolOpen = false;
286
+ if (trace) {
287
+ log.debug("stream", "stream timing", {
288
+ phase: "append done",
289
+ trace,
290
+ msgId: this.logMsgId(),
291
+ totalMs: Date.now() - queuedAt,
292
+ bubbleChars: this.bubbleChars,
293
+ });
294
+ }
255
295
  } catch (err) {
256
296
  if (this.cur === stream) this.handleStreamError(err as Error);
257
297
  }
@@ -83,16 +83,24 @@ export class AppendStream {
83
83
  if (this.doneSent || !delta) return;
84
84
  this.buffer += delta;
85
85
  const elapsed = Date.now() - this.lastFlushAt;
86
- if (this.flushing) return;
87
- if (elapsed >= this.throttleMs()) {
86
+ const throttle = this.throttleMs();
87
+ if (this.flushing) {
88
+ this.opts.onDebug?.(`append: while flushing, buffer=${this.buffer.length}`);
89
+ return;
90
+ }
91
+ if (elapsed >= throttle) {
92
+ this.opts.onDebug?.(`append: immediate, elapsed=${elapsed}, buffer=${this.buffer.length}`);
88
93
  await this.doFlush("generating");
89
94
  return;
90
95
  }
91
96
  if (!this.flushTimer) {
97
+ const waitMs = throttle - elapsed;
98
+ this.opts.onDebug?.(`append: buffered, elapsed=${elapsed}, wait=${waitMs}, buffer=${this.buffer.length}`);
92
99
  this.flushTimer = setTimeout(() => {
93
100
  this.flushTimer = null;
101
+ this.opts.onDebug?.(`timer: fired after ${waitMs}, buffer=${this.buffer.length}`);
94
102
  void this.doFlush("generating").catch((err) => this.opts.onError?.(err as Error));
95
- }, this.throttleMs() - elapsed);
103
+ }, waitMs);
96
104
  }
97
105
  }
98
106
 
@@ -123,6 +131,7 @@ export class AppendStream {
123
131
  if (this.flushing) return;
124
132
  const content = state === "done" ? "" : this.buffer;
125
133
  if (!content && state === "generating") return;
134
+ this.opts.onDebug?.(`flush: start state=${state}, content=${content.length}, index=${this.index}`);
126
135
  this.flushing = true;
127
136
  let failed = false;
128
137
  try {
@@ -143,6 +152,7 @@ export class AppendStream {
143
152
  if (resp?.id && !this.streamMsgId) this.streamMsgId = resp.id;
144
153
  if (state === "generating") this.buffer = this.buffer.slice(content.length);
145
154
  this.lastFlushAt = Date.now();
155
+ this.opts.onDebug?.(`flush: done state=${state}, remaining=${this.buffer.length}`);
146
156
  } catch (err) {
147
157
  failed = true;
148
158
  throw err;