@openclaw/feishu 2026.2.25 → 2026.3.2

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 (73) hide show
  1. package/index.ts +2 -0
  2. package/package.json +2 -1
  3. package/skills/feishu-doc/SKILL.md +109 -3
  4. package/src/accounts.test.ts +161 -0
  5. package/src/accounts.ts +76 -8
  6. package/src/async.ts +62 -0
  7. package/src/bitable.ts +189 -215
  8. package/src/bot.card-action.test.ts +63 -0
  9. package/src/bot.checkBotMentioned.test.ts +56 -1
  10. package/src/bot.test.ts +1271 -56
  11. package/src/bot.ts +499 -215
  12. package/src/card-action.ts +79 -0
  13. package/src/channel.ts +26 -4
  14. package/src/chat-schema.ts +24 -0
  15. package/src/chat.test.ts +89 -0
  16. package/src/chat.ts +130 -0
  17. package/src/client.test.ts +121 -0
  18. package/src/client.ts +13 -0
  19. package/src/config-schema.test.ts +101 -1
  20. package/src/config-schema.ts +66 -11
  21. package/src/dedup.ts +47 -1
  22. package/src/doc-schema.ts +135 -0
  23. package/src/docx-batch-insert.ts +190 -0
  24. package/src/docx-color-text.ts +149 -0
  25. package/src/docx-table-ops.ts +298 -0
  26. package/src/docx.account-selection.test.ts +70 -0
  27. package/src/docx.test.ts +331 -9
  28. package/src/docx.ts +996 -72
  29. package/src/drive.ts +38 -33
  30. package/src/media.test.ts +227 -7
  31. package/src/media.ts +52 -11
  32. package/src/mention.ts +1 -1
  33. package/src/monitor.account.ts +534 -0
  34. package/src/monitor.reaction.test.ts +578 -0
  35. package/src/monitor.startup.test.ts +203 -0
  36. package/src/monitor.startup.ts +51 -0
  37. package/src/monitor.state.defaults.test.ts +46 -0
  38. package/src/monitor.state.ts +152 -0
  39. package/src/monitor.test-mocks.ts +12 -0
  40. package/src/monitor.transport.ts +163 -0
  41. package/src/monitor.ts +44 -346
  42. package/src/monitor.webhook-security.test.ts +53 -10
  43. package/src/onboarding.status.test.ts +25 -0
  44. package/src/onboarding.ts +144 -52
  45. package/src/outbound.test.ts +181 -0
  46. package/src/outbound.ts +94 -7
  47. package/src/perm.ts +37 -30
  48. package/src/policy.test.ts +56 -1
  49. package/src/policy.ts +5 -1
  50. package/src/post.test.ts +105 -0
  51. package/src/post.ts +274 -0
  52. package/src/probe.test.ts +271 -0
  53. package/src/probe.ts +131 -19
  54. package/src/reply-dispatcher.test.ts +300 -0
  55. package/src/reply-dispatcher.ts +159 -46
  56. package/src/secret-input.ts +19 -0
  57. package/src/send-target.test.ts +74 -0
  58. package/src/send-target.ts +6 -2
  59. package/src/send.reply-fallback.test.ts +105 -0
  60. package/src/send.test.ts +168 -0
  61. package/src/send.ts +143 -18
  62. package/src/streaming-card.ts +131 -43
  63. package/src/targets.test.ts +55 -1
  64. package/src/targets.ts +32 -7
  65. package/src/tool-account-routing.test.ts +129 -0
  66. package/src/tool-account.ts +70 -0
  67. package/src/tool-factory-test-harness.ts +76 -0
  68. package/src/tools-config.test.ts +21 -0
  69. package/src/tools-config.ts +2 -1
  70. package/src/types.ts +10 -1
  71. package/src/typing.test.ts +144 -0
  72. package/src/typing.ts +140 -10
  73. package/src/wiki.ts +55 -50
@@ -0,0 +1,578 @@
1
+ import type { ClawdbotConfig, RuntimeEnv } from "openclaw/plugin-sdk";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { hasControlCommand } from "../../../src/auto-reply/command-detection.js";
4
+ import {
5
+ createInboundDebouncer,
6
+ resolveInboundDebounceMs,
7
+ } from "../../../src/auto-reply/inbound-debounce.js";
8
+ import { createPluginRuntimeMock } from "../../test-utils/plugin-runtime-mock.js";
9
+ import { parseFeishuMessageEvent, type FeishuMessageEvent } from "./bot.js";
10
+ import * as dedup from "./dedup.js";
11
+ import { monitorSingleAccount } from "./monitor.account.js";
12
+ import { resolveReactionSyntheticEvent, type FeishuReactionCreatedEvent } from "./monitor.js";
13
+ import { setFeishuRuntime } from "./runtime.js";
14
+ import type { ResolvedFeishuAccount } from "./types.js";
15
+
16
+ const handleFeishuMessageMock = vi.hoisted(() => vi.fn(async (_params: { event?: unknown }) => {}));
17
+ const createEventDispatcherMock = vi.hoisted(() => vi.fn());
18
+ const monitorWebSocketMock = vi.hoisted(() => vi.fn(async () => {}));
19
+ const monitorWebhookMock = vi.hoisted(() => vi.fn(async () => {}));
20
+
21
+ let handlers: Record<string, (data: unknown) => Promise<void>> = {};
22
+
23
+ vi.mock("./client.js", () => ({
24
+ createEventDispatcher: createEventDispatcherMock,
25
+ }));
26
+
27
+ vi.mock("./bot.js", async () => {
28
+ const actual = await vi.importActual<typeof import("./bot.js")>("./bot.js");
29
+ return {
30
+ ...actual,
31
+ handleFeishuMessage: handleFeishuMessageMock,
32
+ };
33
+ });
34
+
35
+ vi.mock("./monitor.transport.js", () => ({
36
+ monitorWebSocket: monitorWebSocketMock,
37
+ monitorWebhook: monitorWebhookMock,
38
+ }));
39
+
40
+ const cfg = {} as ClawdbotConfig;
41
+
42
+ function makeReactionEvent(
43
+ overrides: Partial<FeishuReactionCreatedEvent> = {},
44
+ ): FeishuReactionCreatedEvent {
45
+ return {
46
+ message_id: "om_msg1",
47
+ reaction_type: { emoji_type: "THUMBSUP" },
48
+ operator_type: "user",
49
+ user_id: { open_id: "ou_user1" },
50
+ ...overrides,
51
+ };
52
+ }
53
+
54
+ type FeishuMention = NonNullable<FeishuMessageEvent["message"]["mentions"]>[number];
55
+
56
+ function buildDebounceConfig(): ClawdbotConfig {
57
+ return {
58
+ messages: {
59
+ inbound: {
60
+ debounceMs: 0,
61
+ byChannel: {
62
+ feishu: 20,
63
+ },
64
+ },
65
+ },
66
+ channels: {
67
+ feishu: {
68
+ enabled: true,
69
+ },
70
+ },
71
+ } as ClawdbotConfig;
72
+ }
73
+
74
+ function buildDebounceAccount(): ResolvedFeishuAccount {
75
+ return {
76
+ accountId: "default",
77
+ enabled: true,
78
+ configured: true,
79
+ appId: "cli_test",
80
+ appSecret: "secret_test",
81
+ domain: "feishu",
82
+ config: {
83
+ enabled: true,
84
+ connectionMode: "websocket",
85
+ },
86
+ } as ResolvedFeishuAccount;
87
+ }
88
+
89
+ function createTextEvent(params: {
90
+ messageId: string;
91
+ text: string;
92
+ senderId?: string;
93
+ mentions?: FeishuMention[];
94
+ }): FeishuMessageEvent {
95
+ const senderId = params.senderId ?? "ou_sender";
96
+ return {
97
+ sender: {
98
+ sender_id: { open_id: senderId },
99
+ sender_type: "user",
100
+ },
101
+ message: {
102
+ message_id: params.messageId,
103
+ chat_id: "oc_group_1",
104
+ chat_type: "group",
105
+ message_type: "text",
106
+ content: JSON.stringify({ text: params.text }),
107
+ mentions: params.mentions,
108
+ },
109
+ };
110
+ }
111
+
112
+ async function setupDebounceMonitor(): Promise<(data: unknown) => Promise<void>> {
113
+ const register = vi.fn((registered: Record<string, (data: unknown) => Promise<void>>) => {
114
+ handlers = registered;
115
+ });
116
+ createEventDispatcherMock.mockReturnValue({ register });
117
+
118
+ await monitorSingleAccount({
119
+ cfg: buildDebounceConfig(),
120
+ account: buildDebounceAccount(),
121
+ runtime: {
122
+ log: vi.fn(),
123
+ error: vi.fn(),
124
+ exit: vi.fn(),
125
+ } as RuntimeEnv,
126
+ botOpenIdSource: { kind: "prefetched", botOpenId: "ou_bot" },
127
+ });
128
+
129
+ const onMessage = handlers["im.message.receive_v1"];
130
+ if (!onMessage) {
131
+ throw new Error("missing im.message.receive_v1 handler");
132
+ }
133
+ return onMessage;
134
+ }
135
+
136
+ function getFirstDispatchedEvent(): FeishuMessageEvent {
137
+ const firstCall = handleFeishuMessageMock.mock.calls[0];
138
+ if (!firstCall) {
139
+ throw new Error("missing dispatch call");
140
+ }
141
+ const firstParams = firstCall[0] as { event?: FeishuMessageEvent } | undefined;
142
+ if (!firstParams?.event) {
143
+ throw new Error("missing dispatched event payload");
144
+ }
145
+ return firstParams.event;
146
+ }
147
+
148
+ describe("resolveReactionSyntheticEvent", () => {
149
+ it("filters app self-reactions", async () => {
150
+ const event = makeReactionEvent({ operator_type: "app" });
151
+ const result = await resolveReactionSyntheticEvent({
152
+ cfg,
153
+ accountId: "default",
154
+ event,
155
+ botOpenId: "ou_bot",
156
+ });
157
+ expect(result).toBeNull();
158
+ });
159
+
160
+ it("filters Typing reactions", async () => {
161
+ const event = makeReactionEvent({ reaction_type: { emoji_type: "Typing" } });
162
+ const result = await resolveReactionSyntheticEvent({
163
+ cfg,
164
+ accountId: "default",
165
+ event,
166
+ botOpenId: "ou_bot",
167
+ });
168
+ expect(result).toBeNull();
169
+ });
170
+
171
+ it("fails closed when bot open_id is unavailable", async () => {
172
+ const event = makeReactionEvent();
173
+ const result = await resolveReactionSyntheticEvent({
174
+ cfg,
175
+ accountId: "default",
176
+ event,
177
+ });
178
+ expect(result).toBeNull();
179
+ });
180
+
181
+ it("drops reactions when reactionNotifications is off", async () => {
182
+ const event = makeReactionEvent();
183
+ const result = await resolveReactionSyntheticEvent({
184
+ cfg: {
185
+ channels: {
186
+ feishu: {
187
+ reactionNotifications: "off",
188
+ },
189
+ },
190
+ } as ClawdbotConfig,
191
+ accountId: "default",
192
+ event,
193
+ botOpenId: "ou_bot",
194
+ fetchMessage: async () => ({
195
+ messageId: "om_msg1",
196
+ chatId: "oc_group",
197
+ senderOpenId: "ou_bot",
198
+ senderType: "app",
199
+ content: "hello",
200
+ contentType: "text",
201
+ }),
202
+ });
203
+ expect(result).toBeNull();
204
+ });
205
+
206
+ it("filters reactions on non-bot messages", async () => {
207
+ const event = makeReactionEvent();
208
+ const result = await resolveReactionSyntheticEvent({
209
+ cfg,
210
+ accountId: "default",
211
+ event,
212
+ botOpenId: "ou_bot",
213
+ fetchMessage: async () => ({
214
+ messageId: "om_msg1",
215
+ chatId: "oc_group",
216
+ senderOpenId: "ou_other",
217
+ senderType: "user",
218
+ content: "hello",
219
+ contentType: "text",
220
+ }),
221
+ });
222
+ expect(result).toBeNull();
223
+ });
224
+
225
+ it("allows non-bot reactions when reactionNotifications is all", async () => {
226
+ const event = makeReactionEvent();
227
+ const result = await resolveReactionSyntheticEvent({
228
+ cfg: {
229
+ channels: {
230
+ feishu: {
231
+ reactionNotifications: "all",
232
+ },
233
+ },
234
+ } as ClawdbotConfig,
235
+ accountId: "default",
236
+ event,
237
+ botOpenId: "ou_bot",
238
+ fetchMessage: async () => ({
239
+ messageId: "om_msg1",
240
+ chatId: "oc_group",
241
+ senderOpenId: "ou_other",
242
+ senderType: "user",
243
+ content: "hello",
244
+ contentType: "text",
245
+ }),
246
+ uuid: () => "fixed-uuid",
247
+ });
248
+ expect(result?.message.message_id).toBe("om_msg1:reaction:THUMBSUP:fixed-uuid");
249
+ });
250
+
251
+ it("drops unverified reactions when sender verification times out", async () => {
252
+ const event = makeReactionEvent();
253
+ const result = await resolveReactionSyntheticEvent({
254
+ cfg,
255
+ accountId: "default",
256
+ event,
257
+ botOpenId: "ou_bot",
258
+ verificationTimeoutMs: 1,
259
+ fetchMessage: async () =>
260
+ await new Promise<never>(() => {
261
+ // Never resolves
262
+ }),
263
+ });
264
+ expect(result).toBeNull();
265
+ });
266
+
267
+ it("uses event chat context when provided", async () => {
268
+ const event = makeReactionEvent({
269
+ chat_id: "oc_group_from_event",
270
+ chat_type: "group",
271
+ });
272
+ const result = await resolveReactionSyntheticEvent({
273
+ cfg,
274
+ accountId: "default",
275
+ event,
276
+ botOpenId: "ou_bot",
277
+ fetchMessage: async () => ({
278
+ messageId: "om_msg1",
279
+ chatId: "oc_group_from_lookup",
280
+ senderOpenId: "ou_bot",
281
+ content: "hello",
282
+ contentType: "text",
283
+ }),
284
+ uuid: () => "fixed-uuid",
285
+ });
286
+
287
+ expect(result).toEqual({
288
+ sender: {
289
+ sender_id: { open_id: "ou_user1" },
290
+ sender_type: "user",
291
+ },
292
+ message: {
293
+ message_id: "om_msg1:reaction:THUMBSUP:fixed-uuid",
294
+ chat_id: "oc_group_from_event",
295
+ chat_type: "group",
296
+ message_type: "text",
297
+ content: JSON.stringify({
298
+ text: "[reacted with THUMBSUP to message om_msg1]",
299
+ }),
300
+ },
301
+ });
302
+ });
303
+
304
+ it("falls back to reacted message chat_id when event chat_id is absent", async () => {
305
+ const event = makeReactionEvent();
306
+ const result = await resolveReactionSyntheticEvent({
307
+ cfg,
308
+ accountId: "default",
309
+ event,
310
+ botOpenId: "ou_bot",
311
+ fetchMessage: async () => ({
312
+ messageId: "om_msg1",
313
+ chatId: "oc_group_from_lookup",
314
+ senderOpenId: "ou_bot",
315
+ content: "hello",
316
+ contentType: "text",
317
+ }),
318
+ uuid: () => "fixed-uuid",
319
+ });
320
+
321
+ expect(result?.message.chat_id).toBe("oc_group_from_lookup");
322
+ expect(result?.message.chat_type).toBe("p2p");
323
+ });
324
+
325
+ it("falls back to sender p2p chat when lookup returns empty chat_id", async () => {
326
+ const event = makeReactionEvent();
327
+ const result = await resolveReactionSyntheticEvent({
328
+ cfg,
329
+ accountId: "default",
330
+ event,
331
+ botOpenId: "ou_bot",
332
+ fetchMessage: async () => ({
333
+ messageId: "om_msg1",
334
+ chatId: "",
335
+ senderOpenId: "ou_bot",
336
+ content: "hello",
337
+ contentType: "text",
338
+ }),
339
+ uuid: () => "fixed-uuid",
340
+ });
341
+
342
+ expect(result?.message.chat_id).toBe("p2p:ou_user1");
343
+ expect(result?.message.chat_type).toBe("p2p");
344
+ });
345
+
346
+ it("logs and drops reactions when lookup throws", async () => {
347
+ const log = vi.fn();
348
+ const event = makeReactionEvent();
349
+ const result = await resolveReactionSyntheticEvent({
350
+ cfg,
351
+ accountId: "acct1",
352
+ event,
353
+ botOpenId: "ou_bot",
354
+ fetchMessage: async () => {
355
+ throw new Error("boom");
356
+ },
357
+ logger: log,
358
+ });
359
+ expect(result).toBeNull();
360
+ expect(log).toHaveBeenCalledWith(
361
+ expect.stringContaining("ignoring reaction on non-bot/unverified message om_msg1"),
362
+ );
363
+ });
364
+ });
365
+
366
+ describe("Feishu inbound debounce regressions", () => {
367
+ beforeEach(() => {
368
+ vi.useFakeTimers();
369
+ handlers = {};
370
+ handleFeishuMessageMock.mockClear();
371
+ setFeishuRuntime(
372
+ createPluginRuntimeMock({
373
+ channel: {
374
+ debounce: {
375
+ createInboundDebouncer,
376
+ resolveInboundDebounceMs,
377
+ },
378
+ text: {
379
+ hasControlCommand,
380
+ },
381
+ },
382
+ }),
383
+ );
384
+ });
385
+
386
+ afterEach(() => {
387
+ vi.useRealTimers();
388
+ vi.restoreAllMocks();
389
+ });
390
+
391
+ it("keeps bot mention when per-message mention keys collide across non-forward messages", async () => {
392
+ vi.spyOn(dedup, "tryRecordMessage").mockReturnValue(true);
393
+ vi.spyOn(dedup, "tryRecordMessagePersistent").mockResolvedValue(true);
394
+ vi.spyOn(dedup, "hasRecordedMessage").mockReturnValue(false);
395
+ vi.spyOn(dedup, "hasRecordedMessagePersistent").mockResolvedValue(false);
396
+ const onMessage = await setupDebounceMonitor();
397
+
398
+ await onMessage(
399
+ createTextEvent({
400
+ messageId: "om_1",
401
+ text: "first",
402
+ mentions: [
403
+ {
404
+ key: "@_user_1",
405
+ id: { open_id: "ou_user_a" },
406
+ name: "user-a",
407
+ },
408
+ ],
409
+ }),
410
+ );
411
+ await Promise.resolve();
412
+ await Promise.resolve();
413
+ await onMessage(
414
+ createTextEvent({
415
+ messageId: "om_2",
416
+ text: "@bot second",
417
+ mentions: [
418
+ {
419
+ key: "@_user_1",
420
+ id: { open_id: "ou_bot" },
421
+ name: "bot",
422
+ },
423
+ ],
424
+ }),
425
+ );
426
+ await Promise.resolve();
427
+ await Promise.resolve();
428
+ await vi.advanceTimersByTimeAsync(25);
429
+
430
+ expect(handleFeishuMessageMock).toHaveBeenCalledTimes(1);
431
+ const dispatched = getFirstDispatchedEvent();
432
+ const mergedMentions = dispatched.message.mentions ?? [];
433
+ expect(mergedMentions.some((mention) => mention.id.open_id === "ou_bot")).toBe(true);
434
+ expect(mergedMentions.some((mention) => mention.id.open_id === "ou_user_a")).toBe(false);
435
+ });
436
+
437
+ it("does not synthesize mention-forward intent across separate messages", async () => {
438
+ vi.spyOn(dedup, "tryRecordMessage").mockReturnValue(true);
439
+ vi.spyOn(dedup, "tryRecordMessagePersistent").mockResolvedValue(true);
440
+ vi.spyOn(dedup, "hasRecordedMessage").mockReturnValue(false);
441
+ vi.spyOn(dedup, "hasRecordedMessagePersistent").mockResolvedValue(false);
442
+ const onMessage = await setupDebounceMonitor();
443
+
444
+ await onMessage(
445
+ createTextEvent({
446
+ messageId: "om_user_mention",
447
+ text: "@alice first",
448
+ mentions: [
449
+ {
450
+ key: "@_user_1",
451
+ id: { open_id: "ou_alice" },
452
+ name: "alice",
453
+ },
454
+ ],
455
+ }),
456
+ );
457
+ await Promise.resolve();
458
+ await Promise.resolve();
459
+ await onMessage(
460
+ createTextEvent({
461
+ messageId: "om_bot_mention",
462
+ text: "@bot second",
463
+ mentions: [
464
+ {
465
+ key: "@_user_1",
466
+ id: { open_id: "ou_bot" },
467
+ name: "bot",
468
+ },
469
+ ],
470
+ }),
471
+ );
472
+ await Promise.resolve();
473
+ await Promise.resolve();
474
+ await vi.advanceTimersByTimeAsync(25);
475
+
476
+ expect(handleFeishuMessageMock).toHaveBeenCalledTimes(1);
477
+ const dispatched = getFirstDispatchedEvent();
478
+ const parsed = parseFeishuMessageEvent(dispatched, "ou_bot");
479
+ expect(parsed.mentionedBot).toBe(true);
480
+ expect(parsed.mentionTargets).toBeUndefined();
481
+ const mergedMentions = dispatched.message.mentions ?? [];
482
+ expect(mergedMentions.every((mention) => mention.id.open_id === "ou_bot")).toBe(true);
483
+ });
484
+
485
+ it("preserves bot mention signal when the latest merged message has no mentions", async () => {
486
+ vi.spyOn(dedup, "tryRecordMessage").mockReturnValue(true);
487
+ vi.spyOn(dedup, "tryRecordMessagePersistent").mockResolvedValue(true);
488
+ vi.spyOn(dedup, "hasRecordedMessage").mockReturnValue(false);
489
+ vi.spyOn(dedup, "hasRecordedMessagePersistent").mockResolvedValue(false);
490
+ const onMessage = await setupDebounceMonitor();
491
+
492
+ await onMessage(
493
+ createTextEvent({
494
+ messageId: "om_bot_first",
495
+ text: "@bot first",
496
+ mentions: [
497
+ {
498
+ key: "@_user_1",
499
+ id: { open_id: "ou_bot" },
500
+ name: "bot",
501
+ },
502
+ ],
503
+ }),
504
+ );
505
+ await Promise.resolve();
506
+ await Promise.resolve();
507
+ await onMessage(
508
+ createTextEvent({
509
+ messageId: "om_plain_second",
510
+ text: "plain follow-up",
511
+ }),
512
+ );
513
+ await Promise.resolve();
514
+ await Promise.resolve();
515
+ await vi.advanceTimersByTimeAsync(25);
516
+
517
+ expect(handleFeishuMessageMock).toHaveBeenCalledTimes(1);
518
+ const dispatched = getFirstDispatchedEvent();
519
+ const parsed = parseFeishuMessageEvent(dispatched, "ou_bot");
520
+ expect(parsed.mentionedBot).toBe(true);
521
+ });
522
+
523
+ it("excludes previously processed retries from combined debounce text", async () => {
524
+ vi.spyOn(dedup, "tryRecordMessage").mockReturnValue(true);
525
+ vi.spyOn(dedup, "tryRecordMessagePersistent").mockResolvedValue(true);
526
+ vi.spyOn(dedup, "hasRecordedMessage").mockImplementation((key) => key.endsWith(":om_old"));
527
+ vi.spyOn(dedup, "hasRecordedMessagePersistent").mockImplementation(
528
+ async (messageId) => messageId === "om_old",
529
+ );
530
+ const onMessage = await setupDebounceMonitor();
531
+
532
+ await onMessage(createTextEvent({ messageId: "om_old", text: "stale" }));
533
+ await Promise.resolve();
534
+ await Promise.resolve();
535
+ await onMessage(createTextEvent({ messageId: "om_new_1", text: "first" }));
536
+ await Promise.resolve();
537
+ await Promise.resolve();
538
+ await onMessage(createTextEvent({ messageId: "om_old", text: "stale" }));
539
+ await Promise.resolve();
540
+ await Promise.resolve();
541
+ await onMessage(createTextEvent({ messageId: "om_new_2", text: "second" }));
542
+ await Promise.resolve();
543
+ await Promise.resolve();
544
+ await vi.advanceTimersByTimeAsync(25);
545
+
546
+ expect(handleFeishuMessageMock).toHaveBeenCalledTimes(1);
547
+ const dispatched = getFirstDispatchedEvent();
548
+ expect(dispatched.message.message_id).toBe("om_new_2");
549
+ const combined = JSON.parse(dispatched.message.content) as { text?: string };
550
+ expect(combined.text).toBe("first\nsecond");
551
+ });
552
+
553
+ it("uses latest fresh message id when debounce batch ends with stale retry", async () => {
554
+ const recordSpy = vi.spyOn(dedup, "tryRecordMessage").mockReturnValue(true);
555
+ vi.spyOn(dedup, "tryRecordMessagePersistent").mockResolvedValue(true);
556
+ vi.spyOn(dedup, "hasRecordedMessage").mockImplementation((key) => key.endsWith(":om_old"));
557
+ vi.spyOn(dedup, "hasRecordedMessagePersistent").mockImplementation(
558
+ async (messageId) => messageId === "om_old",
559
+ );
560
+ const onMessage = await setupDebounceMonitor();
561
+
562
+ await onMessage(createTextEvent({ messageId: "om_new", text: "fresh" }));
563
+ await Promise.resolve();
564
+ await Promise.resolve();
565
+ await onMessage(createTextEvent({ messageId: "om_old", text: "stale" }));
566
+ await Promise.resolve();
567
+ await Promise.resolve();
568
+ await vi.advanceTimersByTimeAsync(25);
569
+
570
+ expect(handleFeishuMessageMock).toHaveBeenCalledTimes(1);
571
+ const dispatched = getFirstDispatchedEvent();
572
+ expect(dispatched.message.message_id).toBe("om_new");
573
+ const combined = JSON.parse(dispatched.message.content) as { text?: string };
574
+ expect(combined.text).toBe("fresh");
575
+ expect(recordSpy).toHaveBeenCalledWith("default:om_old");
576
+ expect(recordSpy).not.toHaveBeenCalledWith("default:om_new");
577
+ });
578
+ });