@linjz/opencode-qqbot 0.3.12 → 0.3.13

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.
Files changed (45) hide show
  1. package/bin/openqq-setup.mjs +50 -50
  2. package/bin/openqq.js +47 -47
  3. package/dist/opencode-qqbot-plugin.js +3 -3
  4. package/dist/openqq-bot.js +1033 -191
  5. package/package.json +2 -2
  6. package/src/_FOLDER.md +19 -19
  7. package/src/bridge.ts +135 -15
  8. package/src/commands.ts +554 -554
  9. package/src/config.ts +121 -121
  10. package/src/core/bot-launcher.ts +146 -146
  11. package/src/core/card-approval.ts +146 -146
  12. package/src/core/context-buffer.ts +78 -78
  13. package/src/core/delivery.ts +105 -13
  14. package/src/core/discovery.ts +151 -151
  15. package/src/core/error-rescue.ts +33 -33
  16. package/src/core/file-log.ts +45 -45
  17. package/src/core/form-bridge.ts +388 -72
  18. package/src/core/form-journal.ts +214 -0
  19. package/src/core/gateway-state.ts +68 -0
  20. package/src/core/inbound-dedupe.ts +43 -0
  21. package/src/core/inflight-journal.ts +148 -21
  22. package/src/core/instance-lock.ts +28 -1
  23. package/src/core/linkwatch.ts +195 -195
  24. package/src/core/message-queue.ts +11 -0
  25. package/src/core/mirror.ts +182 -182
  26. package/src/core/outbox.ts +522 -0
  27. package/src/core/permission.ts +301 -301
  28. package/src/core/reply-limiter.ts +106 -106
  29. package/src/core/send-media.ts +90 -90
  30. package/src/core/util.ts +8 -8
  31. package/src/index.ts +162 -162
  32. package/src/opencode/_FOLDER.md +11 -11
  33. package/src/opencode/client.ts +89 -8
  34. package/src/opencode/eventstream.ts +138 -138
  35. package/src/opencode/history.ts +143 -143
  36. package/src/opencode/mirror.ts +85 -85
  37. package/src/opencode/sessions.ts +158 -158
  38. package/src/plugin-entry.ts +112 -112
  39. package/src/qq/_FOLDER.md +13 -13
  40. package/src/qq/api.ts +539 -539
  41. package/src/qq/gateway.ts +69 -20
  42. package/src/qq/media.ts +219 -219
  43. package/src/qq/sender.ts +300 -300
  44. package/src/qq/types.ts +154 -154
  45. package/tsconfig.json +24 -24
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linjz/opencode-qqbot",
3
- "version": "0.3.12",
3
+ "version": "0.3.13",
4
4
  "type": "module",
5
5
  "description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
6
6
  "exports": {
@@ -14,7 +14,7 @@
14
14
  "dev": "bun run --watch src/index.ts",
15
15
  "start": "bun run src/index.ts",
16
16
  "typecheck": "tsc --noEmit",
17
- "test": "bun run test/decision-cases.ts && bun run test/milestone-cases.ts && bun run test/attachment-cases.ts && bun run test/r2-hardening-cases.ts && bun run test/e1-mirror-digest.ts && bun run test/mask-headers-cases.ts && bun run test/perm-mock.ts && bun run test/discovery-cases.ts && bun run test/linkwatch-cases.ts && bun run test/reply-limiter-cases.ts && bun run test/card-approval-cases.ts && bun run test/message-split-cases.ts && bun run test/sync-batch1-cases.ts && bun run test/stream-stagger-cases.ts && bun run test/history-render-cases.ts && bun run test/stall-nudge-cases.ts && bun run test/interaction-watch-cases.ts && bun run test/quote-voice-dedup-cases.ts && bun run test/send-media-cases.ts && bun run test/rival-absorb-cases.ts && bun run test/inflight-recovery-cases.ts && bun run test/plugin-launcher-cases.ts && bun run test/pi-absorb-cases.ts && bun run test/recovery-history-cases.ts",
17
+ "test": "bun run test/decision-cases.ts && bun run test/milestone-cases.ts && bun run test/attachment-cases.ts && bun run test/r2-hardening-cases.ts && bun run test/e1-mirror-digest.ts && bun run test/mask-headers-cases.ts && bun run test/perm-mock.ts && bun run test/discovery-cases.ts && bun run test/linkwatch-cases.ts && bun run test/reply-limiter-cases.ts && bun run test/card-approval-cases.ts && bun run test/message-split-cases.ts && bun run test/sync-batch1-cases.ts && bun run test/delivery-dedupe-cases.ts && bun run test/stream-stagger-cases.ts && bun run test/history-render-cases.ts && bun run test/stall-nudge-cases.ts && bun run test/interaction-watch-cases.ts && bun run test/quote-voice-dedup-cases.ts && bun run test/send-media-cases.ts && bun run test/rival-absorb-cases.ts && bun run test/inflight-recovery-cases.ts && bun run test/plugin-launcher-cases.ts && bun run test/pi-absorb-cases.ts && bun run test/recovery-history-cases.ts && bun run test/inbound-dedupe-cases.ts && bun run test/gateway-state-cases.ts && bun run test/turn-attribution-cases.ts && bun run test/qq-render-cases.ts",
18
18
  "test:e2e": "bun run test/watch-history-e2e.ts && bun run test/d1-subagent-ask-e2e.ts && bun run test/d2-conflict-e2e.ts && bun run test/perm-e2e.ts && bun run test/perm-real-e2e.ts",
19
19
  "verify": "bun run typecheck && bun run test",
20
20
  "verify:full": "bun run verify && bun run test:e2e",
package/src/_FOLDER.md CHANGED
@@ -1,19 +1,19 @@
1
- # src
2
-
3
- OpenCode QQ Bot 源码根目录。QQ 消息 -> OpenCode AI -> QQ 回复。
4
-
5
- ## 文件
6
-
7
- | 文件 | 职责 |
8
- |------|------|
9
- | config.ts | 环境变量加载 + 校验 |
10
- | bridge.ts | 核心桥接: QQ 消息 -> OpenCode -> QQ 回复 |
11
- | commands.ts | 命令系统: /new /stop /status /sessions /help /model /agent /rename |
12
- | index.ts | 入口: 启动编排 + 优雅关闭 |
13
-
14
- ## 子目录
15
-
16
- | 目录 | 职责 |
17
- |------|------|
18
- | qq/ | QQ Bot 接入层 (WebSocket + REST API + 消息收发) |
19
- | opencode/ | OpenCode 对接层 (SDK + SSE 事件 + 会话管理) |
1
+ # src
2
+
3
+ OpenCode QQ Bot 源码根目录。QQ 消息 -> OpenCode AI -> QQ 回复。
4
+
5
+ ## 文件
6
+
7
+ | 文件 | 职责 |
8
+ |------|------|
9
+ | config.ts | 环境变量加载 + 校验 |
10
+ | bridge.ts | 核心桥接: QQ 消息 -> OpenCode -> QQ 回复 |
11
+ | commands.ts | 命令系统: /new /stop /status /sessions /help /model /agent /rename |
12
+ | index.ts | 入口: 启动编排 + 优雅关闭 |
13
+
14
+ ## 子目录
15
+
16
+ | 目录 | 职责 |
17
+ |------|------|
18
+ | qq/ | QQ Bot 接入层 (WebSocket + REST API + 消息收发) |
19
+ | opencode/ | OpenCode 对接层 (SDK + SSE 事件 + 会话管理) |
package/src/bridge.ts CHANGED
@@ -10,7 +10,7 @@ import type { MessageContext } from "./qq/types.js"
10
10
  import { getAccessToken, sendC2CInputNotify, sendC2CMessage, sendGroupMessage } from "./qq/api.js"
11
11
  import { prepareQQAttachments, augmentPromptWithAttachments, purgeOldQQImages } from "./qq/media.js"
12
12
  import type { OpencodeClient, SessionMessage } from "./opencode/client.js"
13
- import { collectReplyText } from "./opencode/client.js"
13
+ import { collectReplyText, turnStateOf } from "./opencode/client.js"
14
14
  import { createEventStream, type V2Event } from "./opencode/eventstream.js"
15
15
  import { summarizeInput, redactSecrets } from "./opencode/history.js"
16
16
  import { SessionManager } from "./opencode/sessions.js"
@@ -25,7 +25,7 @@ import {
25
25
  type WatchApi,
26
26
  } from "./commands.js"
27
27
  import { createMirror } from "./core/mirror.js"
28
- import { MessageQueue, previewText, agoLabel } from "./core/message-queue.js"
28
+ import { MessageQueue, previewText, agoLabel, intentKeyOf } from "./core/message-queue.js"
29
29
  import { classifyProviderError, rescueText } from "./core/error-rescue.js"
30
30
 
31
31
  const QUEUE_MAX = 20 // Q1:忙碌队列上限(学习 pi-qqbot queue.max 默认)
@@ -41,14 +41,16 @@ import { handleApprovalInteraction, sendApprovalCard } from "./core/card-approva
41
41
  import { createFormBridge, renderFormPrompt } from "./core/form-bridge.js"
42
42
  import { recordMessage, resolveQuote, scopeKeyOf, extractEmbeddedQuote } from "./core/context-buffer.js"
43
43
  import {
44
- claimInflight,
44
+ claimInflightDetailed,
45
45
  recordInflight,
46
46
  settleInflight,
47
47
  pendingInflight,
48
48
  classifyInflight,
49
+ markInflightPromptId,
49
50
  INFLIGHT_MAX_AGE_MS,
50
51
  redispatchMaxAgeMs,
51
52
  } from "./core/inflight-journal.js"
53
+ import { messageFingerprint } from "./core/inbound-dedupe.js"
52
54
  import { extractSendFileMarkers, sendLocalFile } from "./core/send-media.js"
53
55
  import type { InteractionEvent } from "./qq/types.js"
54
56
  // O7b:解析/格式化保持经 bridge 再导出——单测与既有调用方导入路径不变
@@ -70,6 +72,27 @@ export function evictableIdleSessions(
70
72
  return out
71
73
  }
72
74
 
75
+ // H2 停滞提醒决策(导出供测试,2026-10-30):bgWait 零进展时提醒用户处置桌面弹窗。
76
+ // 首次:startedAt 后 firstMs;之后:上次进展/提醒后 intervalMs;最多 maxNudges 次。
77
+ // 停滞提醒附带任务状态(2026-11-03 用户拍板:提示语改为「执行超过 N 分钟|状态:…」)。
78
+ // 状态源=回合边界归属(turnStateOf)+ 本地 turnStats 最近工具;纯文本无 markdown 依赖。
79
+ // 注意口径:本提醒只在「零进展」时触发(marker 无变化),所以 anchored 态几乎恒为
80
+ // 「已停滞(回合尚未终结)」——「执行中而仍发提醒」的语义留给 roundRunning=false 的
81
+ // 异常态表达,不臆造。
82
+ export function stallNudgeText(
83
+ minsExec: number,
84
+ s: { anchored: boolean; roundRunning: boolean; idleMin: number; lastAction?: string },
85
+ ): string {
86
+ const status =
87
+ !s.anchored
88
+ ? "状态不明(历史账无归属锚点)"
89
+ : s.roundRunning
90
+ ? "已停滞(回合尚未终结,可能被桌面端审批/选择弹窗阻塞)"
91
+ : "已终结但未回传(异常)"
92
+ const action = s.lastAction ? `|最近动作:${s.lastAction}` : ""
93
+ return `⚠️ 后台任务执行超过 ${minsExec} 分钟|状态:${status}|已 ${s.idleMin} 分钟无进展${action}\n桌面端确实空闲请忽略本提醒;或回复 /stop 中止该回合后重发。`
94
+ }
95
+
73
96
  // H2 停滞提醒决策(导出供测试,2026-10-30):bgWait 零进展时提醒用户处置桌面弹窗。
74
97
  // 首次:startedAt 后 firstMs;之后:上次进展/提醒后 intervalMs;最多 maxNudges 次。
75
98
  export function stallNudgeDecision(
@@ -102,9 +125,20 @@ export function createBridge(
102
125
  client: OpencodeClient,
103
126
  sessions: SessionManager,
104
127
  ): Bridge {
128
+ // H2 停滞提醒文案状态开关就用现成 env 读取风格;这里同步实现⑦开关——
129
+ // 2026-11-03 用户拍板:「已收到」回执默认不发(非调试无价值),调试期在
130
+ // ~/.openqq/.env 设 QQ_ACK_RECEIPT=1 开启。loadEnvFile 全量注入 process.env,
131
+ // 排队回执「已排队 #N」为功能性提示不受此开关影响。
132
+ const ackReceiptEnabled = /^(1|true|on)$/i.test(process.env.QQ_ACK_RECEIPT ?? "")
133
+
105
134
  const busyUsers = new Set<string>()
106
135
  // 队列 drain 会重入 handleMessage;标记本 ctx 已认领,避免把合法出队当成平台重投。
107
136
  const claimedContexts = new WeakSet<MessageContext>()
137
+ // 修复⑦:队列 drain 重入的 ctx——受理回执跳过(drain 已有「开始执行队列」节点,
138
+ // 不在同一 intent 上重复点头)。
139
+ const drainReentries = new WeakSet<MessageContext>()
140
+ // 忙碌期间按用户意图去重:不同 msgId 的相同问题/同图重发不得重复执行或重复排队。
141
+ const activeIntents = new Map<string, string>()
108
142
  // Q1:忙碌消息队列(该用户当前回合结束后自动 drain)
109
143
  const msgQueue = new MessageQueue(QUEUE_MAX)
110
144
  const draining = new Set<string>()
@@ -210,7 +244,9 @@ export function createBridge(
210
244
  const STALL_NUDGE_INTERVAL_MS = 30 * 60 * 1000
211
245
  const STALL_NUDGE_MAX = 3
212
246
 
213
- function startBackgroundWait(sessionId: string, ctx: MessageContext, baseline: number, trackId?: string): void {
247
+ function startBackgroundWait(sessionId: string, ctx: MessageContext, baseline: number, trackId?: string, promptId = ""): void {
248
+ // 同会话只允许一个后台等待:恢复多条在途账/超时重挂不得留下多个完成回调重复投递。
249
+ bgWaits.get(sessionId)?.cancel()
214
250
  let cancelled = false
215
251
  let finished = false
216
252
  const startedAt = Date.now()
@@ -228,8 +264,31 @@ export function createBridge(
228
264
  mirror.scheduleUnlock(sessionId)
229
265
  }
230
266
 
267
+ /** 完成判定+文本提取统一走回合边界归属(修复⑧);锚点完整时用注释里的分布 */
268
+ function classifyNow(listJson: { data?: SessionMessage[] } | undefined): { done: boolean; text: string } {
269
+ const msgs = listJson?.data ?? []
270
+ const turn = turnStateOf(msgs, promptId, baseline)
271
+ if (!turn.anchored) return { done: turn.hasIdle, text: collectReplyText(msgs, baseline) }
272
+ // 有 idle 才算完;超早事件(别回合完成唬人)由调用方跳过
273
+ return { done: turn.hasIdle, text: turn.text }
274
+ }
275
+
231
276
  async function finish(kind: "done" | "giveup"): Promise<void> {
232
277
  if (cancelled || finished) return
278
+ // 修复⑧防早交:SSE 的 execution.succeeded / 别回合 idle 可能唬人——
279
+ // promptId 锚点可用时先核实本回合是否真的有 idle 终结标记。
280
+ if (kind === "done" && promptId) {
281
+ try {
282
+ const probe = await client.session.messages({ path: { id: sessionId } })
283
+ const turn = turnStateOf(probe?.data ?? [], promptId, baseline)
284
+ if (turn.anchored && !turn.hasIdle) {
285
+ console.log(`[bridge] 忽略他回合完成事件(本后台回合尚未结束)session=${sessionId}`)
286
+ return
287
+ }
288
+ } catch {
289
+ /* 探测失败落到既定逻辑,不当早交 */
290
+ }
291
+ }
233
292
  finished = true
234
293
  cleanup()
235
294
  // R 项:后台等待到达终态(完成投递/放弃告知)即销账
@@ -244,7 +303,7 @@ export function createBridge(
244
303
  await new Promise((r) => setTimeout(r, 2000))
245
304
  try {
246
305
  const listJson = await client.session.messages({ path: { id: sessionId } })
247
- const text = collectReplyText(listJson?.data ?? [], baseline)
306
+ const { text } = classifyNow(listJson)
248
307
  await safeDeliver(
249
308
  ctx,
250
309
  text
@@ -263,7 +322,9 @@ export function createBridge(
263
322
  const listJson = await client.session.messages({ path: { id: sessionId } })
264
323
  const msgs = listJson?.data ?? []
265
324
 
266
- // H2 停滞检测:消息数或最新 created 变化=有进展;零进展超窗则提醒用户
325
+ // H2 停滞检测:消息数或最新 created 变化=有进展;零进展超窗则提醒用户。
326
+ // 回合状态先于提醒计算(2026-11-03:提醒文案要带「执行中/已停滞/状态不明」)。
327
+ const turn = turnStateOf(msgs, promptId, baseline)
267
328
  let maxCreated = 0
268
329
  for (const m of msgs) {
269
330
  const created = m.time?.created ?? 0
@@ -279,14 +340,21 @@ export function createBridge(
279
340
  ) {
280
341
  nudges += 1
281
342
  lastProgressAt = now
282
- console.log(`[bridge] 后台任务停滞提醒 #${nudges} session=${sessionId}`)
343
+ const st = turnStats.get(sessionId)
344
+ const lastAction = st?.lastTool && st?.lastAt ? `${st.lastTool}(${agoLabel(st.lastAt)})` : undefined
345
+ console.log(`[bridge] 后台任务状态通告 #${nudges} session=${sessionId} anchored=${turn.anchored}`)
283
346
  void safeDeliver(
284
347
  ctx,
285
- "⚠️ 后台任务已停滞超过 30 分钟——很可能在桌面端等待确认(审批/选择弹窗无法同步到 QQ)。请到桌面端查看处理;或回复 /stop 终止该任务后重发。",
348
+ stallNudgeText(Math.round((now - startedAt) / 60000), {
349
+ anchored: turn.anchored,
350
+ roundRunning: turn.anchored && !turn.hasIdle,
351
+ idleMin: Math.round((now - lastProgressAt) / 60000),
352
+ lastAction,
353
+ }),
286
354
  ).catch(() => {})
287
355
  }
288
356
 
289
- if (msgs.some((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline)) {
357
+ if (turn.hasIdle) {
290
358
  await finish("done")
291
359
  }
292
360
  } catch (error) {
@@ -506,6 +574,7 @@ export function createBridge(
506
574
 
507
575
  const handleMessage = async (ctx: MessageContext): Promise<void> => {
508
576
  let claimedMsgId = ""
577
+ const intentKey = intentKeyOf(ctx)
509
578
  try {
510
579
  if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
511
580
  await sendReply(ctx, "你不在允许使用的名单里")
@@ -564,20 +633,40 @@ export function createBridge(
564
633
  return
565
634
  }
566
635
 
567
- // Durable gate:网关 Set 只能防本进程重投;多执行体/重启共用台账认领,
568
- // 同一 QQ msgId 在附件下载、排队和 promptAndWait 之前就被去重。
636
+ // Durable gate(修复①):K1 跨进程 msgId 占位 + K2 同内容在途指纹——
637
+ // 判定与写入在台账单临界区内原子完成(跨进程互斥读改写),
638
+ // 多 believer 并发受理与「连发不同 msgId 同问」都在此拦下。
639
+ // 回执纪律:duplicate-msgid 静默(最先放行的 believer 负责答案,本侧任何出站
640
+ // 都是重复气泡);duplicate-intent 给一句短提示(首投方不会发,不构成重复)。
569
641
  if (ctx.msgId) {
570
642
  if (!claimedContexts.has(ctx)) {
571
- const claimed = claimInflight({ msgId: ctx.msgId, userId: ctx.userId, sessionId: "", text: content.slice(0, 300), at: Date.now() })
572
- if (!claimed) {
643
+ const admitted = claimInflightDetailed(
644
+ { msgId: ctx.msgId, userId: ctx.userId, sessionId: "", text: content.slice(0, 300), at: Date.now() },
645
+ { fingerprint: messageFingerprint(ctx.userId, intentKey) },
646
+ )
647
+ if (admitted === "duplicate-msgid") {
573
648
  console.log(`[bridge] 重复消息已跳过 msgId=${ctx.msgId}`)
574
649
  return
575
650
  }
651
+ if (admitted === "duplicate-intent") {
652
+ console.log(`[admit-dedupe] 同内容意图在途,本次重发已忽略 msgId=${ctx.msgId}`)
653
+ await sendReply(ctx, "你的相同问题正在处理中,本次重发已忽略")
654
+ return
655
+ }
576
656
  claimedContexts.add(ctx)
577
657
  }
578
658
  claimedMsgId = ctx.msgId
579
659
  }
580
660
 
661
+ if (busyUsers.has(ctx.userId) && !claimedContexts.has(ctx)) {
662
+ const duplicateIntent = activeIntents.get(ctx.userId) === intentKey || msgQueue.hasIntent(ctx.userId, intentKey)
663
+ if (duplicateIntent) {
664
+ settleInflight(ctx.msgId) // 重复意图已有原回合负责,直接结清,禁止恢复时再跑
665
+ console.log(`[bridge] 相同意图已在执行/队列,跳过 msgId=${ctx.msgId}`)
666
+ return
667
+ }
668
+ }
669
+
581
670
  if (busyUsers.has(ctx.userId)) {
582
671
  // Q1(学习 pi-qqbot 队列 UX):忙碌不再拒绝——FIFO 排队,回合结束自动执行
583
672
  // 自检补强:入队即下载附件——QQ 签名 URL 短时效,drain 时下载必过期
@@ -600,8 +689,18 @@ export function createBridge(
600
689
  return
601
690
  }
602
691
 
692
+ activeIntents.set(ctx.userId, intentKey)
603
693
  busyUsers.add(ctx.userId)
604
694
 
695
+ // 修复⑦(2026-11-03):受理即回执——前台回合立刻短句确认,消除静默期
696
+ // (expA 实证:无受理回执时用户观感=「没有任何回复」)。Queue 路径此前
697
+ // 已回「已排队 #N」、drain 重入已有「开始执行队列」、重派路径有「重启恢复」
698
+ // 通知——这三处都不进本分支,同一 intent 不重复点头。
699
+ // (同日迭代:改为开关制、默认不发——见顶部 ackReceiptEnabled。)
700
+ if (ackReceiptEnabled && ctx.msgId && !drainReentries.has(ctx)) {
701
+ await sendReply(ctx, "✅ 已收到,正在处理,完成后自动回复你")
702
+ }
703
+
605
704
  // B3(2026-10-29 同步升级):C2C typing 指示——长回合处理中给用户
606
705
  // "对方正在输入"体感(官方 input_notify,仅 C2C;失败静默不阻塞主流程)
607
706
  // R 项:重派回合无真实 msgId(空串),跳过 typing 防无效请求
@@ -614,6 +713,7 @@ export function createBridge(
614
713
  let sessionId = ""
615
714
  let turnStart = 0
616
715
  let trackId = "" // R 项:在途台账跟踪键(try/catch 跨块可见)
716
+ let promptId = "" // 修复⑧:本回合 user 消息 id(直答归属锚点)
617
717
  try {
618
718
  const session = await sessions.getOrCreate(ctx.userId)
619
719
  sessionId = session.sessionId
@@ -652,6 +752,11 @@ export function createBridge(
652
752
  recordInflight({ msgId: trackId, userId: ctx.userId, sessionId, text: content.slice(0, 300), at: Date.now() })
653
753
  const replyText = await client.promptAndWait(sessionId, promptText, {
654
754
  files: files.length ? files : undefined,
755
+ // 修复⑧:受领即落台账锚点 + 本地闭合变量(前台超时转后台等待要带上)
756
+ onAccepted: (info) => {
757
+ promptId = info.promptId
758
+ markInflightPromptId(trackId, info.promptId)
759
+ },
655
760
  onPermission: (req) => perm.waitForDecision(ctx, req, sessionId),
656
761
  onPermissionReplied: (d) => {
657
762
  void safeDeliver(ctx, `已${DECISION_LABELS[d]},AI 将继续执行…`)
@@ -687,7 +792,7 @@ export function createBridge(
687
792
  ctx,
688
793
  "⏳ 回合超过前台时限,已转后台等待:任务继续执行,完成即回传结果(最长 24 小时)。期间可用 /history 查看进展。",
689
794
  )
690
- startBackgroundWait(sessionId, ctx, turnStart, trackId)
795
+ startBackgroundWait(sessionId, ctx, turnStart, trackId, promptId)
691
796
  } else {
692
797
  // Q3:额度/鉴权错误给救援话术(报类别+原文+恢复路径),不死胡同报错
693
798
  const errText = toErrorMessage(error)
@@ -700,6 +805,7 @@ export function createBridge(
700
805
  // 镜像解锁:转后台的任务由 bgWait 完成时解锁,其余延迟 5 秒(SSE 事件宽限)
701
806
  if (sessionId && !bgWaits.has(sessionId)) mirror.scheduleUnlock(sessionId)
702
807
  busyUsers.delete(ctx.userId)
808
+ if (activeIntents.get(ctx.userId) === intentKey) activeIntents.delete(ctx.userId)
703
809
  // Q1:回合结束(成功/失败/转后台)→ 自动执行该用户队列下一条;
704
810
  // 转后台等待的会话保持串行——由 bgWait 完成时再 drain(不与前序后台任务并发)
705
811
  if (sessionId && !bgWaits.has(sessionId)) void drainQueue(ctx.userId)
@@ -708,6 +814,7 @@ export function createBridge(
708
814
  // 认领后、内层回合兜底之前的异常(如排队附件预下载失败)也必须结清,
709
815
  // 否则重启对账会把已反馈失败的消息再执行一次。
710
816
  if (claimedMsgId) settleInflight(claimedMsgId)
817
+ if (activeIntents.get(ctx.userId) === intentKey) activeIntents.delete(ctx.userId)
711
818
  console.error("[bridge] handleMessage failed:", error)
712
819
  try {
713
820
  await sendReply(ctx, `处理消息失败:${toErrorMessage(error)}`)
@@ -733,6 +840,18 @@ export function createBridge(
733
840
  }
734
841
  // 恢复投递走主动通道(原 msgId 的被动窗口早已过期)
735
842
  const ctx: MessageContext = { type: "c2c", userId: entry.userId, msgId: "", content: entry.text }
843
+ // 修复③(2026-11-03):排队空账治本——sessionId 为空=「从未进过会话」
844
+ // (忙碌排队阶段重启丢队)。这类账对永远拿 400 永挂(openqq422 五连铁证),
845
+ // 且按用户重投哲学不得自动重派执行——只清账通知,请用户重发。
846
+ if (!entry.sessionId) {
847
+ settleInflight(entry.msgId)
848
+ await deliver(
849
+ ctx,
850
+ `⚠️ 重启前队列里有一条消息未执行(「${entry.text.length > 50 ? `${entry.text.slice(0, 50)}…` : entry.text}」)。为避免重复执行不自动重派,需要的话请重发一次`,
851
+ )
852
+ console.log(`[bridge] 启动对账:排队空账已通知销账 msgId=${entry.msgId}`)
853
+ continue
854
+ }
736
855
  try {
737
856
  const listJson = { data: await fetchRecoveryMessages(client, entry.sessionId) }
738
857
  const cls = classifyInflight(entry, listJson.data)
@@ -744,7 +863,7 @@ export function createBridge(
744
863
  // 跨重启也要保持 QQ 回合同一身份:后台直答完成时,镜像不得再投摘要。
745
864
  mirror.beginTurn(entry.sessionId)
746
865
  // 不单独发“仍在执行”通知;完成时统一回传最终答案,避免通知也占一条回复。
747
- startBackgroundWait(entry.sessionId, ctx, entry.at, entry.msgId)
866
+ startBackgroundWait(entry.sessionId, ctx, entry.at, entry.msgId, entry.promptId ?? "")
748
867
  console.log(`[bridge] 启动对账:在途任务已重挂后台等待 msgId=${entry.msgId}`)
749
868
  } else if (ageMs <= redispatchMaxAgeMs()) {
750
869
  settleInflight(entry.msgId) // 旧账结清,重派回合走新账(合成 trackId)
@@ -771,6 +890,7 @@ export function createBridge(
771
890
  draining.add(userId)
772
891
  try {
773
892
  await sendReply(job.ctx, `开始执行队列 #${job.id}`)
893
+ drainReentries.add(job.ctx) // 修复⑦:drain 重入跳过受理回执
774
894
  await handleMessage(job.ctx)
775
895
  } catch (error) {
776
896
  console.error("[bridge] 队列执行失败:", error)