@linjz/opencode-qqbot 0.3.12 → 0.3.14

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 (46) hide show
  1. package/README.md +12 -7
  2. package/bin/openqq-setup.mjs +50 -50
  3. package/bin/openqq.js +47 -47
  4. package/dist/opencode-qqbot-plugin.js +4 -4
  5. package/dist/openqq-bot.js +1072 -208
  6. package/package.json +2 -2
  7. package/src/_FOLDER.md +19 -19
  8. package/src/bridge.ts +141 -15
  9. package/src/commands.ts +554 -554
  10. package/src/config.ts +118 -121
  11. package/src/core/bot-launcher.ts +146 -146
  12. package/src/core/card-approval.ts +146 -146
  13. package/src/core/context-buffer.ts +78 -78
  14. package/src/core/delivery.ts +115 -18
  15. package/src/core/discovery.ts +151 -151
  16. package/src/core/error-rescue.ts +33 -33
  17. package/src/core/file-log.ts +45 -45
  18. package/src/core/form-bridge.ts +388 -72
  19. package/src/core/form-journal.ts +214 -0
  20. package/src/core/gateway-state.ts +68 -0
  21. package/src/core/inbound-dedupe.ts +43 -0
  22. package/src/core/inflight-journal.ts +170 -22
  23. package/src/core/instance-lock.ts +28 -1
  24. package/src/core/linkwatch.ts +195 -195
  25. package/src/core/message-queue.ts +11 -0
  26. package/src/core/mirror.ts +182 -182
  27. package/src/core/outbox.ts +522 -0
  28. package/src/core/permission.ts +301 -301
  29. package/src/core/reply-limiter.ts +106 -106
  30. package/src/core/send-media.ts +90 -90
  31. package/src/core/util.ts +8 -8
  32. package/src/index.ts +162 -162
  33. package/src/opencode/_FOLDER.md +11 -11
  34. package/src/opencode/client.ts +98 -13
  35. package/src/opencode/eventstream.ts +138 -138
  36. package/src/opencode/history.ts +143 -143
  37. package/src/opencode/mirror.ts +85 -85
  38. package/src/opencode/sessions.ts +158 -158
  39. package/src/plugin-entry.ts +112 -112
  40. package/src/qq/_FOLDER.md +13 -13
  41. package/src/qq/api.ts +546 -539
  42. package/src/qq/gateway.ts +69 -20
  43. package/src/qq/media.ts +219 -219
  44. package/src/qq/sender.ts +303 -300
  45. package/src/qq/types.ts +154 -154
  46. package/tsconfig.json +24 -24
@@ -1,20 +1,26 @@
1
- // @input: ../opencode/client (FormInfo/FormField/FormOption), ../qq/types (MessageContext)
1
+ // @input: ../opencode/client (FormInfo/FormField/FormOption), ../qq/types (MessageContext), ./form-journal
2
2
  // @output: renderFormPrompt, parseFormAnswer, createFormBridge, FORM_PROMPT_TTL_MS
3
- // @pos: core - 表单桥接(L 项 2026-10-30):V2 Form(选择弹窗 A/B/C/D)的 QQ 同步与作答回传。
3
+ // @pos: core - 表单桥接:QQ 同步、作答回传、跨重启恢复与服务端对账。
4
4
  //
5
- // 背景:昨晚"卡到今天"事故的真凶即此类弹窗(V2 Form:MCP input form/选择表单)。
6
- // 2.1.3 即有完整 REST(GET /api/form 全局列表 / POST .../form/{id}/reply)+ SSE 事件
7
- // (form.created/form.replied,探针实采)——纯外部 bot 可桥,无需插件无需升级。
8
5
  // MVP 边界:单交互字段完整支持(选择/多选/布尔/自由文本);多字段表单提示回桌面。
6
+ // 所有服务端成功状态才允许清槽;点击 ACK、submitting 与取消失败均同步落盘,重启后可续交。
9
7
  import type { FormInfo, OpencodeClient } from "../opencode/client.js"
10
8
  import type { MessageContext } from "../qq/types.js"
11
9
  import type { InlineKeyboard, KeyboardButton } from "../qq/api.js"
12
10
  import { redactSecrets } from "../opencode/history.js"
11
+ import {
12
+ createFormJournal,
13
+ minimalFormContext,
14
+ type FormJournal,
15
+ type FormJournalEntry,
16
+ type FormLifecycleState,
17
+ } from "./form-journal.js"
13
18
 
14
19
  export const FORM_PROMPT_TTL_MS = 30 * 60 * 1000
15
20
  const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
16
21
  const BUTTON_LABEL_MAX = 10
17
22
  const BUTTONS_PER_ROW = 2
23
+ const DEFAULT_DRAIN_TIMEOUT_MS = 5_000
18
24
 
19
25
  // 宽松字段视图:V2 字段类型可能扩展(external 等),运行时用宽类型读取可选属性,
20
26
  // 未知类型走自由文本兜底而不是报错。
@@ -70,13 +76,10 @@ function tokenToOption(token: string, field: FieldLike): string | undefined {
70
76
  const t = token.trim()
71
77
  if (!t) return undefined
72
78
  const opts = field.options ?? []
73
- // 字母 A/B/C...
74
79
  const letterIdx = LETTERS.indexOf(t.toUpperCase())
75
80
  if (letterIdx >= 0 && letterIdx < opts.length) return opts[letterIdx].value
76
- // 1-based 序号
77
81
  const num = Number(t)
78
82
  if (Number.isInteger(num) && num >= 1 && num <= opts.length) return opts[num - 1].value
79
- // 精确匹配 value 或 label
80
83
  const hit = opts.find((o) => o.value === t || o.label === t)
81
84
  return hit?.value
82
85
  }
@@ -118,24 +121,27 @@ export function parseFormAnswer(form: FormInfo, text: string): Record<string, un
118
121
  const v = tokenToOption(t, field)
119
122
  return v === undefined ? null : { [field.key]: v }
120
123
  }
121
- // string 无选项 / 未知类型 = 自由文本兜底
122
124
  return { [field.key]: t }
123
125
  }
124
126
 
125
- export interface PendingForm {
126
- form: FormInfo
127
- ctx: MessageContext
127
+ export interface PendingForm extends FormJournalEntry {
128
128
  timer: ReturnType<typeof setTimeout> | null
129
+ restored?: boolean
129
130
  }
130
131
 
131
- // ── 表单按钮(2026-10-30 弹窗验证前置:点选式作答)──
132
+ interface InternalPendingForm extends PendingForm {
133
+ replying: boolean
134
+ cancelling: boolean
135
+ }
136
+
137
+ // ── 表单按钮:兼容旧 t/form/f/k/v 协议,可选 i 为交互回调 id ──
132
138
 
133
- /** button_data:t 判别 + formID + 字段 key + 选项 value(明文 JSON,与审批同款 P0 格式) */
134
139
  export interface FormButtonData {
135
140
  t: "form"
136
141
  f: string
137
142
  k: string
138
143
  v: string
144
+ i?: string
139
145
  }
140
146
 
141
147
  export function encodeFormButton(data: FormButtonData): string {
@@ -145,9 +151,15 @@ export function encodeFormButton(data: FormButtonData): string {
145
151
  export function decodeFormButton(raw: string | undefined): FormButtonData | undefined {
146
152
  if (!raw) return undefined
147
153
  try {
148
- const parsed = JSON.parse(raw) as Partial<FormButtonData>
149
- if (parsed && typeof parsed === "object" && parsed.t === "form" && typeof parsed.f === "string" && typeof parsed.k === "string" && typeof parsed.v === "string") {
150
- return parsed as FormButtonData
154
+ const parsed = JSON.parse(raw) as Partial<FormButtonData> & { interactionId?: unknown }
155
+ if (
156
+ parsed && typeof parsed === "object" && parsed.t === "form" &&
157
+ typeof parsed.f === "string" && typeof parsed.k === "string" && typeof parsed.v === "string"
158
+ ) {
159
+ const interactionId = typeof parsed.i === "string"
160
+ ? parsed.i
161
+ : typeof parsed.interactionId === "string" ? parsed.interactionId : undefined
162
+ return { t: "form", f: parsed.f, k: parsed.k, v: parsed.v, ...(interactionId ? { i: interactionId } : {}) }
151
163
  }
152
164
  } catch {
153
165
  // fall through
@@ -160,10 +172,7 @@ function clipButtonLabel(text: string): string {
160
172
  return s.length > BUTTON_LABEL_MAX ? s.slice(0, BUTTON_LABEL_MAX - 1) + "…" : s
161
173
  }
162
174
 
163
- /**
164
- * 构建表单选项键盘:单可见字段 + 有 options 时可用(string=单选直点直交;
165
- * multiselect=点一个先交单值数组,多值仍走文字)。多字段/无选项 → null(文字作答)。
166
- */
175
+ /** 单选直接提交字符串;多选按钮与文字路径一致,提交单值数组。 */
167
176
  export function buildFormKeyboard(form: FormInfo, ownerOpenid: string): InlineKeyboard | null {
168
177
  const visible = form.fields.filter((f) => !(f as FieldLike).hidden)
169
178
  if (visible.length !== 1) return null
@@ -173,7 +182,6 @@ export function buildFormKeyboard(form: FormInfo, ownerOpenid: string): InlineKe
173
182
  if (field.type !== "string" && field.type !== "multiselect") return null
174
183
  const buttons: KeyboardButton[] = opts.slice(0, 20).map((opt) => ({
175
184
  id: `form-${form.id}-${opt.value}`.slice(0, 64),
176
- // visited_label:点击后原生回显(按钮变已访问态、其余置灰),不再发明文确认消息
177
185
  render_data: { label: clipButtonLabel(opt.label), visited_label: clipButtonLabel(`✓ ${opt.label}`), style: 1 },
178
186
  action: {
179
187
  type: 1,
@@ -188,117 +196,425 @@ export function buildFormKeyboard(form: FormInfo, ownerOpenid: string): InlineKe
188
196
  return { content: { rows } }
189
197
  }
190
198
 
199
+ export interface FormInteractionEvent {
200
+ id?: string
201
+ user_openid?: string
202
+ group_openid?: string
203
+ group_member_openid?: string
204
+ data?: { resolved?: { button_id?: string; button_data?: string } }
205
+ }
206
+
191
207
  export interface FormBridgeDeps {
192
208
  client: OpencodeClient
193
209
  sendReply: (ctx: MessageContext, text: string) => Promise<void>
194
210
  safeDeliver: (ctx: MessageContext, text: string) => Promise<void>
195
- /** 按钮卡片发送(有键盘时优先;返回 false 自动降级文字) */
196
211
  sendFormCard?: (ctx: MessageContext, form: FormInfo, keyboard: InlineKeyboard) => Promise<boolean>
212
+ /** 测试/嵌入方可显式指定台账;生产默认 ~/.openqq/forms.json 或 QQ_FORM_JOURNAL_FILE。 */
213
+ journalPath?: string
214
+ journal?: FormJournal
215
+ /** 以下时钟/TTL 参数供可控测试使用,生产无需传入。 */
216
+ now?: () => number
217
+ ttlMs?: number
197
218
  }
198
219
 
199
220
  export interface FormBridge {
200
221
  pushForm: (userId: string, ctx: MessageContext, form: FormInfo) => void
201
222
  tryResolveText: (userId: string, text: string) => boolean
202
- /** 按钮互动回调:匹配挂起表单则提交并返回 true;非本域返回 false */
203
- handleButton: (event: { user_openid?: string; group_member_openid?: string; data?: { resolved?: { button_data?: string } } }) => boolean
223
+ handleButton: (event: FormInteractionEvent) => boolean
204
224
  hasPending: (userId: string) => boolean
205
225
  getPending: (userId: string) => PendingForm | undefined
226
+ /** 仅读本地磁盘,不访问网络;返回恢复记录涉及的 sessionID(含当前映射之外的会话)。 */
227
+ restore: () => string[]
228
+ /** 查询指定会话;列表失败 fail-closed 保留本地,成功才清理或续交。 */
229
+ reconcile: (sessionID: string) => Promise<boolean>
230
+ /** 等待所有已跟踪 reply/cancel/通知完成;超时返回 false。 */
231
+ drainInteractions: (timeoutMs?: number) => Promise<boolean>
232
+ /** 停止接受新交互并清 TTL 定时器;在途 Promise 仍可由 drainInteractions 等待。 */
233
+ stopAccepting: () => void
206
234
  }
207
235
 
208
236
  export function createFormBridge(deps: FormBridgeDeps): FormBridge {
209
- const pending = new Map<string, PendingForm>()
237
+ const pending = new Map<string, InternalPendingForm>()
238
+ const journal = deps.journal ?? createFormJournal(deps.journalPath)
239
+ const now = deps.now ?? Date.now
240
+ const ttlMs = deps.ttlMs ?? FORM_PROMPT_TTL_MS
241
+ const operations = new Set<Promise<unknown>>()
242
+ let accepting = true
210
243
 
211
- function clear(userId: string): PendingForm | undefined {
212
- const entry = pending.get(userId)
213
- if (!entry) return undefined
244
+ function track<T>(promise: Promise<T>): Promise<T> {
245
+ const tracked = promise.finally(() => operations.delete(tracked))
246
+ operations.add(tracked)
247
+ return tracked
248
+ }
249
+
250
+ function deliver(ctx: MessageContext, text: string): Promise<void> {
251
+ return track(deps.safeDeliver(ctx, text).catch((error) => {
252
+ console.error("[form-bridge] 回执投递失败:", error instanceof Error ? error.message : error)
253
+ }))
254
+ }
255
+
256
+ function journalSnapshot(entry: InternalPendingForm): FormJournalEntry {
257
+ return {
258
+ form: entry.form,
259
+ ctx: minimalFormContext(entry.ctx),
260
+ userId: entry.userId,
261
+ createdAt: entry.createdAt,
262
+ state: entry.state,
263
+ ...(entry.answer ? { answer: entry.answer } : {}),
264
+ ...(entry.display !== undefined ? { display: entry.display } : {}),
265
+ ...(entry.interactionId ? { interactionId: entry.interactionId } : {}),
266
+ updatedAt: entry.updatedAt,
267
+ }
268
+ }
269
+
270
+ function transition(entry: InternalPendingForm, state: FormLifecycleState): void {
271
+ const previous = entry.state
272
+ const previousUpdatedAt = entry.updatedAt
273
+ entry.state = state
274
+ entry.updatedAt = now()
275
+ try {
276
+ journal.put(journalSnapshot(entry))
277
+ } catch (error) {
278
+ entry.state = previous
279
+ entry.updatedAt = previousUpdatedAt
280
+ throw error
281
+ }
282
+ }
283
+
284
+ function clearEntry(userId: string, entry: InternalPendingForm): boolean {
285
+ if (pending.get(userId) !== entry) return false
214
286
  if (entry.timer) clearTimeout(entry.timer)
287
+ entry.timer = null
215
288
  pending.delete(userId)
216
- return entry
289
+ try {
290
+ journal.remove(userId, entry.form.id)
291
+ } catch (error) {
292
+ // 服务端已成功时才进入这里;残留账会由下次成功 reconcile 清理。
293
+ console.error("[form-bridge] 清理表单台账失败:", error instanceof Error ? error.message : error)
294
+ }
295
+ return true
217
296
  }
218
297
 
219
- function submit(userId: string, form: FormInfo, ctx: MessageContext, answer: Record<string, unknown>, display: string, silent = false): void {
220
- clear(userId)
221
- void (async () => {
298
+ function isCurrent(userId: string, entry: InternalPendingForm): boolean {
299
+ return pending.get(userId) === entry
300
+ }
301
+
302
+ function submit(userId: string, entry: InternalPendingForm, answer: Record<string, unknown>, display: string, interactionId?: string): void {
303
+ if (!isCurrent(userId, entry) || entry.replying || entry.cancelling) return
304
+ entry.answer = answer
305
+ entry.display = display
306
+ if (interactionId) entry.interactionId = interactionId
307
+ entry.replying = true
308
+ try {
309
+ // 先同步落 submitting,再发起网络请求;崩溃后 reconcile 可续交同一答案。
310
+ transition(entry, "submitting")
311
+ } catch (error) {
312
+ entry.replying = false
313
+ const msg = error instanceof Error ? error.message : String(error)
314
+ void deliver(entry.ctx, `⚠️ 无法保存提交状态,尚未向服务端作答:${msg};请回桌面处理`)
315
+ return
316
+ }
317
+
318
+ const operation = (async () => {
222
319
  try {
223
- await deps.client.form.reply({ path: { sessionID: form.sessionID, formID: form.id }, body: { answer } })
224
- // 按钮路径静默(visited_label 原生回显已表达结果);文字路径保留明文回执
225
- if (!silent) {
226
- void deps.safeDeliver(ctx, `✅ 已提交选择:${display}`).catch(() => {})
227
- }
228
- console.log(`[form-bridge] 表单已作答 user=${userId.slice(0, 8)}… form=${form.id} answer=${display}`)
320
+ await deps.client.form.reply({
321
+ path: { sessionID: entry.form.sessionID, formID: entry.form.id },
322
+ body: { answer },
323
+ })
229
324
  } catch (error) {
325
+ entry.replying = false
230
326
  const msg = error instanceof Error ? error.message : String(error)
231
- if (msg.includes("AlreadySettled") || msg.includes("already")) {
232
- void deps.safeDeliver(ctx, "该选择已在桌面端处理过,任务应已继续").catch(() => {})
327
+ if (/AlreadySettled|already|OpenCode API 404/i.test(msg)) {
328
+ // 桌面端先答/先取消是终态;只有明确的服务端冲突才清理。
329
+ if (isCurrent(userId, entry)) clearEntry(userId, entry)
330
+ await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效")
233
331
  } else {
234
- void deps.safeDeliver(ctx, `⚠️ 提交失败:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`).catch(() => {})
332
+ // submitting + answer 保留在内存和磁盘,可手动重试或由 reconcile 续交。
333
+ await deliver(entry.ctx, `⚠️ 提交失败,选择已保留、可在重启后续交:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`)
235
334
  }
335
+ return
236
336
  }
237
- })()
337
+
338
+ entry.replying = false
339
+ if (isCurrent(userId, entry)) {
340
+ try {
341
+ transition(entry, "replied")
342
+ } catch (error) {
343
+ console.error("[form-bridge] replied 状态落盘失败:", error instanceof Error ? error.message : error)
344
+ }
345
+ clearEntry(userId, entry)
346
+ }
347
+ console.log(`[form-bridge] 表单已作答 user=${userId.slice(0, 8)}… form=${entry.form.id} answer=${display}`)
348
+ })().catch((error) => {
349
+ entry.replying = false
350
+ console.error("[form-bridge] 提交流程异常:", error instanceof Error ? error.message : error)
351
+ })
352
+ void track(operation)
353
+ }
354
+
355
+ async function expireEntry(userId: string, entry: InternalPendingForm): Promise<void> {
356
+ if (!isCurrent(userId, entry) || entry.replying || entry.cancelling || entry.state === "expired" && entry.cancelling) return
357
+ entry.cancelling = true
358
+ if (entry.timer) clearTimeout(entry.timer)
359
+ entry.timer = null
360
+ try {
361
+ transition(entry, "expired")
362
+ } catch (error) {
363
+ entry.cancelling = false
364
+ await deliver(entry.ctx, `⚠️ 选择已到期,但取消状态无法落盘;请回桌面处理:${error instanceof Error ? error.message : error}`)
365
+ return
366
+ }
367
+ try {
368
+ await deps.client.form.cancel({ path: { sessionID: entry.form.sessionID, formID: entry.form.id } })
369
+ } catch (error) {
370
+ entry.cancelling = false
371
+ const msg = error instanceof Error ? error.message : String(error)
372
+ await deliver(entry.ctx, `⚠️ 选择请求已到期,但服务端取消失败(${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg});本地已保留恢复记录,请回桌面确认`)
373
+ return
374
+ }
375
+ entry.cancelling = false
376
+ if (isCurrent(userId, entry)) {
377
+ try {
378
+ transition(entry, "cancelled")
379
+ } catch (error) {
380
+ console.error("[form-bridge] cancelled 状态落盘失败:", error instanceof Error ? error.message : error)
381
+ }
382
+ clearEntry(userId, entry)
383
+ }
384
+ await deliver(entry.ctx, "⏰ 选择请求已满 30 分钟未作答,服务端已确认取消;如需继续请回桌面重试")
385
+ }
386
+
387
+ function scheduleExpiry(userId: string, entry: InternalPendingForm): void {
388
+ if (!accepting) return
389
+ const remaining = Math.max(0, entry.createdAt + ttlMs - now())
390
+ entry.timer = setTimeout(() => {
391
+ void track(expireEntry(userId, entry))
392
+ }, remaining)
393
+ entry.timer.unref?.()
394
+ }
395
+
396
+ function restore(): string[] {
397
+ const sessions = new Set<string>()
398
+ for (const saved of journal.load()) {
399
+ sessions.add(saved.form.sessionID)
400
+ if (saved.state === "replied" || saved.state === "cancelled") {
401
+ try { journal.remove(saved.userId, saved.form.id) } catch { /* 下次启动再清理 */ }
402
+ continue
403
+ }
404
+ const entry: InternalPendingForm = {
405
+ ...saved,
406
+ ctx: minimalFormContext({ ...saved.ctx, userId: saved.userId }),
407
+ timer: null,
408
+ restored: true,
409
+ replying: false,
410
+ cancelling: false,
411
+ }
412
+ const previous = pending.get(saved.userId)
413
+ if (previous && previous.updatedAt > entry.updatedAt) continue
414
+ if (previous?.timer) clearTimeout(previous.timer)
415
+ pending.set(saved.userId, entry)
416
+ scheduleExpiry(saved.userId, entry)
417
+ console.log(`[form-bridge] 恢复本地表单 user=${saved.userId.slice(0, 8)}… form=${saved.form.id} state=${saved.state}`)
418
+ }
419
+ return [...sessions]
420
+ }
421
+
422
+ async function reconcile(sessionID: string): Promise<boolean> {
423
+ let forms: FormInfo[]
424
+ try {
425
+ forms = (await deps.client.form.list({ sessionID })).data ?? []
426
+ } catch (error) {
427
+ // fail-closed:列表不可信时绝不清槽,也不把未确认的服务端状态告知用户。
428
+ console.error(`[form-bridge] 会话表单对账失败 session=${sessionID}:`, error instanceof Error ? error.message : error)
429
+ return false
430
+ }
431
+
432
+ const candidates = [...pending.entries()].filter(([, entry]) => entry.form.sessionID === sessionID)
433
+ for (const [userId, entry] of candidates) {
434
+ if (!isCurrent(userId, entry)) continue
435
+ const server = forms.find((form) => form.id === entry.form.id) as (FormInfo & { state?: { status?: string } | string }) | undefined
436
+ const serverStatus = typeof server?.state === "string" ? server.state : server?.state?.status
437
+ const serverPending = server !== undefined && (!serverStatus || serverStatus === "pending")
438
+ if (!serverPending) {
439
+ clearEntry(userId, entry)
440
+ await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效")
441
+ continue
442
+ }
443
+ if (entry.state === "expired") {
444
+ if (!entry.cancelling) await track(expireEntry(userId, entry))
445
+ } else if ((entry.state === "clickReceived" || entry.state === "submitting") && entry.answer && !entry.replying) {
446
+ submit(userId, entry, entry.answer, entry.display ?? "已恢复的选择", entry.interactionId)
447
+ }
448
+ }
449
+ return true
238
450
  }
239
451
 
240
452
  function pushForm(userId: string, ctx: MessageContext, form: FormInfo): void {
241
- // 去重:同表单已在挂起中
453
+ if (!accepting) {
454
+ void deliver(ctx, "⚠️ 表单桥正在停止,暂不接受新的 QQ 作答;请回桌面处理")
455
+ return
456
+ }
242
457
  if (pending.get(userId)?.form.id === form.id) return
243
- // 单一交互槽:新表单取代旧槽(提示旧表单失效)
244
- const prev = clear(userId)
245
- if (prev) {
246
- void deps.safeDeliver(ctx, "⚠️ 有新的选择请求,上一个表单已取消在 QQ 的作答(仍可回桌面处理)").catch(() => {})
458
+
459
+ const liveCtx: MessageContext = { ...minimalFormContext(ctx), msgId: ctx.msgId }
460
+ const timestamp = now()
461
+ const entry: InternalPendingForm = {
462
+ form,
463
+ ctx: liveCtx,
464
+ userId,
465
+ createdAt: timestamp,
466
+ state: "pending",
467
+ updatedAt: timestamp,
468
+ timer: null,
469
+ replying: false,
470
+ cancelling: false,
247
471
  }
248
- const entry: PendingForm = { form, ctx, timer: null }
249
- entry.timer = setTimeout(() => {
250
- if (pending.get(userId)?.form.id !== form.id) return
251
- clear(userId)
252
- void deps.safeDeliver(ctx, "⏰ 选择请求超时(30 分钟未作答),任务可能已被取消;可回桌面重试").catch(() => {})
253
- }, FORM_PROMPT_TTL_MS)
472
+ try {
473
+ // 推送前先持久化:发送崩溃也至少能恢复旧按钮和服务端对账。
474
+ journal.put(journalSnapshot(entry))
475
+ } catch (error) {
476
+ console.error("[form-bridge] 表单落盘失败,取消 QQ 推送:", error instanceof Error ? error.message : error)
477
+ void deliver(ctx, "⚠️ 选择请求无法保存恢复记录,本次未推送到 QQ;请回桌面处理")
478
+ return
479
+ }
480
+
481
+ const previous = pending.get(userId)
482
+ if (previous?.timer) clearTimeout(previous.timer)
254
483
  pending.set(userId, entry)
484
+ scheduleExpiry(userId, entry)
485
+ if (previous) {
486
+ void deliver(previous.ctx, "⚠️ 有新的选择请求,上一个表单已取消在 QQ 的作答(仍可回桌面处理)")
487
+ }
255
488
  console.log(`[form-bridge] 表单已推送 user=${userId.slice(0, 8)}… form=${form.id} title=${form.title.slice(0, 40)}`)
256
- void (async () => {
257
- const keyboard = buildFormKeyboard(form, ctx.userId)
489
+ const operation = (async () => {
490
+ const keyboard = buildFormKeyboard(form, liveCtx.userId)
258
491
  if (keyboard && deps.sendFormCard) {
259
- const sent = await deps.sendFormCard(ctx, form, keyboard).catch(() => false)
492
+ const sent = await deps.sendFormCard(liveCtx, form, keyboard).catch(() => false)
260
493
  if (sent) return
261
494
  }
262
- await deps.sendReply(ctx, renderFormPrompt(form)).catch((error) => {
495
+ await deps.sendReply(liveCtx, renderFormPrompt(form)).catch((error) => {
263
496
  console.error("[form-bridge] 表单推送失败:", error instanceof Error ? error.message : error)
264
497
  })
265
498
  })()
499
+ void track(operation)
266
500
  }
267
501
 
268
- /** 有挂起表单则消费本条文本(解析成功→提交;失败→提示),返回 true;无挂起返回 false。 */
269
502
  function tryResolveText(userId: string, text: string): boolean {
270
503
  const entry = pending.get(userId)
271
504
  if (!entry) return false
505
+ if (!accepting) {
506
+ void deliver(entry.ctx, "⚠️ 表单桥正在停止,本次答案未提交;请回桌面处理")
507
+ return true
508
+ }
509
+ if (entry.state === "expired") {
510
+ void deliver(entry.ctx, "⚠️ 按钮和文字答案已失效,请使用新卡或回桌面处理")
511
+ return true
512
+ }
513
+ if (entry.replying || entry.cancelling) {
514
+ void deliver(entry.ctx, "⏳ 选择正在提交或取消,请勿重复操作;稍后会给出最终回执")
515
+ return true
516
+ }
272
517
  const answer = parseFormAnswer(entry.form, text)
273
518
  if (!answer) {
274
519
  const field = primaryField(entry.form)
275
- const hint =
276
- field?.type === "multiselect"
277
- ? '没看懂,请按选项字母回复(多选用逗号,如 "A,C")'
278
- : field?.type === "boolean"
279
- ? "请回复 是 或 否"
280
- : "没看懂,请按提示回复"
520
+ const hint = field?.type === "multiselect"
521
+ ? '没看懂,请按选项字母回复(多选用逗号,如 "A,C")'
522
+ : field?.type === "boolean" ? "请回复 是 或 否" : "没看懂,请按提示回复"
281
523
  void deps.sendReply(entry.ctx, hint).catch(() => {})
282
524
  return true
283
525
  }
284
- submit(userId, entry.form, entry.ctx, answer, text.trim())
526
+ submit(userId, entry, answer, text.trim())
285
527
  return true
286
528
  }
287
529
 
288
- function handleButton(event: { user_openid?: string; group_member_openid?: string; data?: { resolved?: { button_data?: string } } }): boolean {
530
+ function eventContext(event: FormInteractionEvent, userId: string): MessageContext {
531
+ return {
532
+ type: event.group_member_openid ? "group" : "c2c",
533
+ userId,
534
+ ...(event.group_member_openid && event.group_openid ? { groupId: event.group_openid } : {}),
535
+ msgId: "",
536
+ content: "",
537
+ }
538
+ }
539
+
540
+ function rejectButton(ctx: MessageContext): void {
541
+ void deliver(ctx, "⚠️ 按钮已失效、已处理或不属于当前选择,请使用新卡或回桌面处理")
542
+ }
543
+
544
+ function handleButton(event: FormInteractionEvent): boolean {
289
545
  const userId = event.user_openid ?? event.group_member_openid
290
546
  if (!userId) return false
291
547
  const button = decodeFormButton(event.data?.resolved?.button_data)
292
548
  if (!button) return false
293
549
  const entry = pending.get(userId)
294
- if (!entry || entry.form.id !== button.f) {
550
+ const ctx = entry?.ctx ?? eventContext(event, userId)
551
+ if (!accepting || !entry || entry.form.id !== button.f || entry.state === "expired") {
295
552
  console.log(`[form-bridge] 拒识过期表单按钮 user=${userId.slice(0, 8)}… form=${button.f}`)
296
- return true // 已消费(拒识),不再下放
553
+ rejectButton(ctx)
554
+ return true
555
+ }
556
+ if (entry.replying || entry.cancelling) {
557
+ void deliver(ctx, "⏳ 该按钮已受理,正在等待服务端最终结果,请勿重复点击")
558
+ return true
559
+ }
560
+
561
+ const field = entry.form.fields.find((candidate) => (candidate as FieldLike).key === button.k && !(candidate as FieldLike).hidden) as FieldLike | undefined
562
+ const option = field?.options?.find((candidate) => candidate.value === button.v)
563
+ if (!field || (field.type !== "string" && field.type !== "multiselect") || !option) {
564
+ rejectButton(ctx)
565
+ return true
566
+ }
567
+ const interactionId = button.i ?? event.data?.resolved?.button_id ?? event.id
568
+ const answer: Record<string, unknown> = { [button.k]: field.type === "multiselect" ? [button.v] : button.v }
569
+
570
+ // clickReceived 是“QQ ACK 后、reply 前”崩溃窗口的可恢复锚。
571
+ entry.answer = answer
572
+ entry.display = button.v
573
+ if (interactionId) entry.interactionId = interactionId
574
+ try {
575
+ transition(entry, "clickReceived")
576
+ } catch (error) {
577
+ void deliver(ctx, `⚠️ 无法保存按钮受理状态,尚未提交:${error instanceof Error ? error.message : error}`)
578
+ return true
579
+ }
580
+ submit(userId, entry, answer, button.v, interactionId)
581
+ return true
582
+ }
583
+
584
+ async function drainInteractions(timeoutMs: number = DEFAULT_DRAIN_TIMEOUT_MS): Promise<boolean> {
585
+ const deadline = Date.now() + Math.max(0, timeoutMs)
586
+ while (operations.size > 0) {
587
+ const remaining = deadline - Date.now()
588
+ if (remaining <= 0) return false
589
+ let timer: ReturnType<typeof setTimeout> | undefined
590
+ const timeout = new Promise<"timeout">((resolve) => {
591
+ timer = setTimeout(() => resolve("timeout"), remaining)
592
+ })
593
+ const drained = Promise.allSettled([...operations]).then(() => "drained" as const)
594
+ const result = await Promise.race([drained, timeout])
595
+ if (timer) clearTimeout(timer)
596
+ if (result === "timeout") return false
297
597
  }
298
- const answer: Record<string, unknown> = { [button.k]: button.v }
299
- submit(userId, entry.form, entry.ctx, answer, button.v, true) // 按钮路径静默(visited_label 原生回显)
300
598
  return true
301
599
  }
302
600
 
303
- return { pushForm, tryResolveText, handleButton, hasPending: (u) => pending.has(u), getPending: (u) => pending.get(u) }
601
+ function stopAccepting(): void {
602
+ accepting = false
603
+ for (const entry of pending.values()) {
604
+ if (entry.timer) clearTimeout(entry.timer)
605
+ entry.timer = null
606
+ }
607
+ }
608
+
609
+ return {
610
+ pushForm,
611
+ tryResolveText,
612
+ handleButton,
613
+ hasPending: (userId) => pending.has(userId),
614
+ getPending: (userId) => pending.get(userId),
615
+ restore,
616
+ reconcile,
617
+ drainInteractions,
618
+ stopAccepting,
619
+ }
304
620
  }