@nextclaw/channel-plugin-feishu 0.2.12 → 0.2.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 (102) hide show
  1. package/README.md +3 -1
  2. package/index.ts +65 -0
  3. package/openclaw.plugin.json +3 -7
  4. package/package.json +33 -9
  5. package/skills/feishu-doc/SKILL.md +211 -0
  6. package/skills/feishu-doc/references/block-types.md +103 -0
  7. package/skills/feishu-drive/SKILL.md +97 -0
  8. package/skills/feishu-perm/SKILL.md +119 -0
  9. package/skills/feishu-wiki/SKILL.md +111 -0
  10. package/src/accounts.test.ts +371 -0
  11. package/src/accounts.ts +244 -0
  12. package/src/async.ts +62 -0
  13. package/src/bitable.ts +725 -0
  14. package/src/bot.card-action.test.ts +63 -0
  15. package/src/bot.checkBotMentioned.test.ts +193 -0
  16. package/src/bot.stripBotMention.test.ts +134 -0
  17. package/src/bot.test.ts +2107 -0
  18. package/src/bot.ts +1556 -0
  19. package/src/card-action.ts +79 -0
  20. package/src/channel.test.ts +48 -0
  21. package/src/channel.ts +369 -0
  22. package/src/chat-schema.ts +24 -0
  23. package/src/chat.test.ts +89 -0
  24. package/src/chat.ts +130 -0
  25. package/src/client.test.ts +324 -0
  26. package/src/client.ts +196 -0
  27. package/src/config-schema.test.ts +247 -0
  28. package/src/config-schema.ts +306 -0
  29. package/src/dedup.ts +203 -0
  30. package/src/directory.test.ts +40 -0
  31. package/src/directory.ts +156 -0
  32. package/src/doc-schema.ts +182 -0
  33. package/src/docx-batch-insert.test.ts +90 -0
  34. package/src/docx-batch-insert.ts +187 -0
  35. package/src/docx-color-text.ts +149 -0
  36. package/src/docx-table-ops.ts +298 -0
  37. package/src/docx.account-selection.test.ts +70 -0
  38. package/src/docx.test.ts +445 -0
  39. package/src/docx.ts +1460 -0
  40. package/src/drive-schema.ts +46 -0
  41. package/src/drive.ts +228 -0
  42. package/src/dynamic-agent.ts +131 -0
  43. package/src/external-keys.test.ts +20 -0
  44. package/src/external-keys.ts +19 -0
  45. package/src/feishu-command-handler.ts +59 -0
  46. package/src/media.test.ts +523 -0
  47. package/src/media.ts +484 -0
  48. package/src/mention.ts +133 -0
  49. package/src/monitor.account.ts +562 -0
  50. package/src/monitor.reaction.test.ts +653 -0
  51. package/src/monitor.startup.test.ts +190 -0
  52. package/src/monitor.startup.ts +64 -0
  53. package/src/monitor.state.defaults.test.ts +46 -0
  54. package/src/monitor.state.ts +155 -0
  55. package/src/monitor.test-mocks.ts +45 -0
  56. package/src/monitor.transport.ts +264 -0
  57. package/src/monitor.ts +95 -0
  58. package/src/monitor.webhook-e2e.test.ts +214 -0
  59. package/src/monitor.webhook-security.test.ts +142 -0
  60. package/src/monitor.webhook.test-helpers.ts +98 -0
  61. package/src/onboarding.status.test.ts +25 -0
  62. package/src/onboarding.test.ts +143 -0
  63. package/src/onboarding.ts +489 -0
  64. package/src/outbound.test.ts +356 -0
  65. package/src/outbound.ts +176 -0
  66. package/src/perm-schema.ts +52 -0
  67. package/src/perm.ts +176 -0
  68. package/src/policy.test.ts +154 -0
  69. package/src/policy.ts +123 -0
  70. package/src/post.test.ts +105 -0
  71. package/src/post.ts +274 -0
  72. package/src/probe.test.ts +270 -0
  73. package/src/probe.ts +156 -0
  74. package/src/reactions.ts +153 -0
  75. package/src/reply-dispatcher.test.ts +513 -0
  76. package/src/reply-dispatcher.ts +397 -0
  77. package/src/runtime.ts +6 -0
  78. package/src/secret-input.ts +13 -0
  79. package/src/send-message.ts +71 -0
  80. package/src/send-result.ts +29 -0
  81. package/src/send-target.test.ts +74 -0
  82. package/src/send-target.ts +29 -0
  83. package/src/send.reply-fallback.test.ts +189 -0
  84. package/src/send.test.ts +168 -0
  85. package/src/send.ts +481 -0
  86. package/src/streaming-card.test.ts +54 -0
  87. package/src/streaming-card.ts +374 -0
  88. package/src/targets.test.ts +70 -0
  89. package/src/targets.ts +107 -0
  90. package/src/tool-account-routing.test.ts +129 -0
  91. package/src/tool-account.ts +70 -0
  92. package/src/tool-factory-test-harness.ts +76 -0
  93. package/src/tool-result.test.ts +32 -0
  94. package/src/tool-result.ts +14 -0
  95. package/src/tools-config.test.ts +21 -0
  96. package/src/tools-config.ts +22 -0
  97. package/src/types.ts +103 -0
  98. package/src/typing.test.ts +144 -0
  99. package/src/typing.ts +210 -0
  100. package/src/wiki-schema.ts +55 -0
  101. package/src/wiki.ts +233 -0
  102. package/index.js +0 -27
@@ -0,0 +1,2107 @@
1
+ import type { ClawdbotConfig, PluginRuntime, RuntimeEnv } from "openclaw/plugin-sdk/feishu";
2
+ import { beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { createPluginRuntimeMock } from "../../test-utils/plugin-runtime-mock.js";
4
+ import type { FeishuMessageEvent } from "./bot.js";
5
+ import {
6
+ buildBroadcastSessionKey,
7
+ buildFeishuAgentBody,
8
+ handleFeishuMessage,
9
+ resolveBroadcastAgents,
10
+ toMessageResourceType,
11
+ } from "./bot.js";
12
+ import { setFeishuRuntime } from "./runtime.js";
13
+
14
+ const {
15
+ mockCreateFeishuReplyDispatcher,
16
+ mockSendMessageFeishu,
17
+ mockGetMessageFeishu,
18
+ mockDownloadMessageResourceFeishu,
19
+ mockCreateFeishuClient,
20
+ mockResolveAgentRoute,
21
+ } = vi.hoisted(() => ({
22
+ mockCreateFeishuReplyDispatcher: vi.fn(() => ({
23
+ dispatcher: vi.fn(),
24
+ replyOptions: {},
25
+ markDispatchIdle: vi.fn(),
26
+ })),
27
+ mockSendMessageFeishu: vi.fn().mockResolvedValue({ messageId: "pairing-msg", chatId: "oc-dm" }),
28
+ mockGetMessageFeishu: vi.fn().mockResolvedValue(null),
29
+ mockDownloadMessageResourceFeishu: vi.fn().mockResolvedValue({
30
+ buffer: Buffer.from("video"),
31
+ contentType: "video/mp4",
32
+ fileName: "clip.mp4",
33
+ }),
34
+ mockCreateFeishuClient: vi.fn(),
35
+ mockResolveAgentRoute: vi.fn(() => ({
36
+ agentId: "main",
37
+ channel: "feishu",
38
+ accountId: "default",
39
+ sessionKey: "agent:main:feishu:dm:ou-attacker",
40
+ mainSessionKey: "agent:main:main",
41
+ matchedBy: "default",
42
+ })),
43
+ }));
44
+
45
+ vi.mock("./reply-dispatcher.js", () => ({
46
+ createFeishuReplyDispatcher: mockCreateFeishuReplyDispatcher,
47
+ }));
48
+
49
+ vi.mock("./send.js", () => ({
50
+ sendMessageFeishu: mockSendMessageFeishu,
51
+ getMessageFeishu: mockGetMessageFeishu,
52
+ }));
53
+
54
+ vi.mock("./media.js", () => ({
55
+ downloadMessageResourceFeishu: mockDownloadMessageResourceFeishu,
56
+ }));
57
+
58
+ vi.mock("./client.js", () => ({
59
+ createFeishuClient: mockCreateFeishuClient,
60
+ }));
61
+
62
+ function createRuntimeEnv(): RuntimeEnv {
63
+ return {
64
+ log: vi.fn(),
65
+ error: vi.fn(),
66
+ exit: vi.fn((code: number): never => {
67
+ throw new Error(`exit ${code}`);
68
+ }),
69
+ } as RuntimeEnv;
70
+ }
71
+
72
+ async function dispatchMessage(params: { cfg: ClawdbotConfig; event: FeishuMessageEvent }) {
73
+ await handleFeishuMessage({
74
+ cfg: params.cfg,
75
+ event: params.event,
76
+ runtime: createRuntimeEnv(),
77
+ });
78
+ }
79
+
80
+ describe("buildFeishuAgentBody", () => {
81
+ it("builds message id, speaker, quoted content, mentions, and permission notice in order", () => {
82
+ const body = buildFeishuAgentBody({
83
+ ctx: {
84
+ content: "hello world",
85
+ senderName: "Sender Name",
86
+ senderOpenId: "ou-sender",
87
+ messageId: "msg-42",
88
+ mentionTargets: [{ openId: "ou-target", name: "Target User", key: "@_user_1" }],
89
+ },
90
+ quotedContent: "previous message",
91
+ permissionErrorForAgent: {
92
+ code: 99991672,
93
+ message: "permission denied",
94
+ grantUrl: "https://open.feishu.cn/app/cli_test",
95
+ },
96
+ });
97
+
98
+ expect(body).toBe(
99
+ '[message_id: msg-42]\nSender Name: [Replying to: "previous message"]\n\nhello world\n\n[System: Your reply will automatically @mention: Target User. Do not write @xxx yourself.]\n\n[System: The bot encountered a Feishu API permission error. Please inform the user about this issue and provide the permission grant URL for the admin to authorize. Permission grant URL: https://open.feishu.cn/app/cli_test]',
100
+ );
101
+ });
102
+ });
103
+
104
+ describe("handleFeishuMessage command authorization", () => {
105
+ const mockFinalizeInboundContext = vi.fn((ctx: unknown) => ctx);
106
+ const mockDispatchReplyFromConfig = vi
107
+ .fn()
108
+ .mockResolvedValue({ queuedFinal: false, counts: { final: 1 } });
109
+ const mockWithReplyDispatcher = vi.fn(
110
+ async ({
111
+ dispatcher,
112
+ run,
113
+ onSettled,
114
+ }: Parameters<PluginRuntime["channel"]["reply"]["withReplyDispatcher"]>[0]) => {
115
+ try {
116
+ return await run();
117
+ } finally {
118
+ dispatcher.markComplete();
119
+ try {
120
+ await dispatcher.waitForIdle();
121
+ } finally {
122
+ await onSettled?.();
123
+ }
124
+ }
125
+ },
126
+ );
127
+ const mockResolveCommandAuthorizedFromAuthorizers = vi.fn(() => false);
128
+ const mockShouldComputeCommandAuthorized = vi.fn(() => true);
129
+ const mockReadAllowFromStore = vi.fn().mockResolvedValue([]);
130
+ const mockUpsertPairingRequest = vi.fn().mockResolvedValue({ code: "ABCDEFGH", created: false });
131
+ const mockBuildPairingReply = vi.fn(() => "Pairing response");
132
+ const mockEnqueueSystemEvent = vi.fn();
133
+ const mockSaveMediaBuffer = vi.fn().mockResolvedValue({
134
+ id: "inbound-clip.mp4",
135
+ path: "/tmp/inbound-clip.mp4",
136
+ size: Buffer.byteLength("video"),
137
+ contentType: "video/mp4",
138
+ });
139
+
140
+ beforeEach(() => {
141
+ vi.clearAllMocks();
142
+ mockShouldComputeCommandAuthorized.mockReset().mockReturnValue(true);
143
+ mockResolveAgentRoute.mockReturnValue({
144
+ agentId: "main",
145
+ channel: "feishu",
146
+ accountId: "default",
147
+ sessionKey: "agent:main:feishu:dm:ou-attacker",
148
+ mainSessionKey: "agent:main:main",
149
+ matchedBy: "default",
150
+ });
151
+ mockCreateFeishuClient.mockReturnValue({
152
+ contact: {
153
+ user: {
154
+ get: vi.fn().mockResolvedValue({ data: { user: { name: "Sender" } } }),
155
+ },
156
+ },
157
+ });
158
+ mockEnqueueSystemEvent.mockReset();
159
+ setFeishuRuntime(
160
+ createPluginRuntimeMock({
161
+ system: {
162
+ enqueueSystemEvent: mockEnqueueSystemEvent,
163
+ },
164
+ channel: {
165
+ routing: {
166
+ resolveAgentRoute:
167
+ mockResolveAgentRoute as unknown as PluginRuntime["channel"]["routing"]["resolveAgentRoute"],
168
+ },
169
+ reply: {
170
+ resolveEnvelopeFormatOptions: vi.fn(
171
+ () => ({}),
172
+ ) as unknown as PluginRuntime["channel"]["reply"]["resolveEnvelopeFormatOptions"],
173
+ formatAgentEnvelope: vi.fn((params: { body: string }) => params.body),
174
+ finalizeInboundContext:
175
+ mockFinalizeInboundContext as unknown as PluginRuntime["channel"]["reply"]["finalizeInboundContext"],
176
+ dispatchReplyFromConfig: mockDispatchReplyFromConfig,
177
+ withReplyDispatcher:
178
+ mockWithReplyDispatcher as unknown as PluginRuntime["channel"]["reply"]["withReplyDispatcher"],
179
+ },
180
+ commands: {
181
+ shouldComputeCommandAuthorized: mockShouldComputeCommandAuthorized,
182
+ resolveCommandAuthorizedFromAuthorizers: mockResolveCommandAuthorizedFromAuthorizers,
183
+ },
184
+ media: {
185
+ saveMediaBuffer:
186
+ mockSaveMediaBuffer as unknown as PluginRuntime["channel"]["media"]["saveMediaBuffer"],
187
+ },
188
+ pairing: {
189
+ readAllowFromStore: mockReadAllowFromStore,
190
+ upsertPairingRequest: mockUpsertPairingRequest,
191
+ buildPairingReply: mockBuildPairingReply,
192
+ },
193
+ },
194
+ media: {
195
+ detectMime: vi.fn(async () => "application/octet-stream"),
196
+ },
197
+ }),
198
+ );
199
+ });
200
+
201
+ it("does not enqueue inbound preview text as system events", async () => {
202
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
203
+
204
+ const cfg: ClawdbotConfig = {
205
+ channels: {
206
+ feishu: {
207
+ dmPolicy: "open",
208
+ },
209
+ },
210
+ } as ClawdbotConfig;
211
+
212
+ const event: FeishuMessageEvent = {
213
+ sender: {
214
+ sender_id: {
215
+ open_id: "ou-attacker",
216
+ },
217
+ },
218
+ message: {
219
+ message_id: "msg-no-system-preview",
220
+ chat_id: "oc-dm",
221
+ chat_type: "p2p",
222
+ message_type: "text",
223
+ content: JSON.stringify({ text: "hi there" }),
224
+ },
225
+ };
226
+
227
+ await dispatchMessage({ cfg, event });
228
+
229
+ expect(mockEnqueueSystemEvent).not.toHaveBeenCalled();
230
+ });
231
+
232
+ it("uses authorizer resolution instead of hardcoded CommandAuthorized=true", async () => {
233
+ const cfg: ClawdbotConfig = {
234
+ commands: { useAccessGroups: true },
235
+ channels: {
236
+ feishu: {
237
+ dmPolicy: "open",
238
+ allowFrom: ["ou-admin"],
239
+ },
240
+ },
241
+ } as ClawdbotConfig;
242
+
243
+ const event: FeishuMessageEvent = {
244
+ sender: {
245
+ sender_id: {
246
+ open_id: "ou-attacker",
247
+ },
248
+ },
249
+ message: {
250
+ message_id: "msg-auth-bypass-regression",
251
+ chat_id: "oc-dm",
252
+ chat_type: "p2p",
253
+ message_type: "text",
254
+ content: JSON.stringify({ text: "/status" }),
255
+ },
256
+ };
257
+
258
+ await dispatchMessage({ cfg, event });
259
+
260
+ expect(mockResolveCommandAuthorizedFromAuthorizers).toHaveBeenCalledWith({
261
+ useAccessGroups: true,
262
+ authorizers: [{ configured: true, allowed: false }],
263
+ });
264
+ expect(mockFinalizeInboundContext).toHaveBeenCalledTimes(1);
265
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
266
+ expect.objectContaining({
267
+ CommandAuthorized: false,
268
+ SenderId: "ou-attacker",
269
+ Surface: "feishu",
270
+ }),
271
+ );
272
+ });
273
+
274
+ it("reads pairing allow store for non-command DMs when dmPolicy is pairing", async () => {
275
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
276
+ mockReadAllowFromStore.mockResolvedValue(["ou-attacker"]);
277
+
278
+ const cfg: ClawdbotConfig = {
279
+ commands: { useAccessGroups: true },
280
+ channels: {
281
+ feishu: {
282
+ dmPolicy: "pairing",
283
+ allowFrom: [],
284
+ },
285
+ },
286
+ } as ClawdbotConfig;
287
+
288
+ const event: FeishuMessageEvent = {
289
+ sender: {
290
+ sender_id: {
291
+ open_id: "ou-attacker",
292
+ },
293
+ },
294
+ message: {
295
+ message_id: "msg-read-store-non-command",
296
+ chat_id: "oc-dm",
297
+ chat_type: "p2p",
298
+ message_type: "text",
299
+ content: JSON.stringify({ text: "hello there" }),
300
+ },
301
+ };
302
+
303
+ await dispatchMessage({ cfg, event });
304
+
305
+ expect(mockReadAllowFromStore).toHaveBeenCalledWith({
306
+ channel: "feishu",
307
+ accountId: "default",
308
+ });
309
+ expect(mockResolveCommandAuthorizedFromAuthorizers).not.toHaveBeenCalled();
310
+ expect(mockFinalizeInboundContext).toHaveBeenCalledTimes(1);
311
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
312
+ });
313
+
314
+ it("skips sender-name lookup when resolveSenderNames is false", async () => {
315
+ const cfg: ClawdbotConfig = {
316
+ channels: {
317
+ feishu: {
318
+ dmPolicy: "open",
319
+ allowFrom: ["*"],
320
+ resolveSenderNames: false,
321
+ },
322
+ },
323
+ } as ClawdbotConfig;
324
+
325
+ const event: FeishuMessageEvent = {
326
+ sender: {
327
+ sender_id: {
328
+ open_id: "ou-attacker",
329
+ },
330
+ },
331
+ message: {
332
+ message_id: "msg-skip-sender-lookup",
333
+ chat_id: "oc-dm",
334
+ chat_type: "p2p",
335
+ message_type: "text",
336
+ content: JSON.stringify({ text: "hello" }),
337
+ },
338
+ };
339
+
340
+ await dispatchMessage({ cfg, event });
341
+
342
+ expect(mockCreateFeishuClient).not.toHaveBeenCalled();
343
+ });
344
+
345
+ it("propagates parent/root message ids into inbound context for reply reconstruction", async () => {
346
+ mockGetMessageFeishu.mockResolvedValueOnce({
347
+ messageId: "om_parent_001",
348
+ chatId: "oc-group",
349
+ content: "quoted content",
350
+ contentType: "text",
351
+ });
352
+
353
+ const cfg: ClawdbotConfig = {
354
+ channels: {
355
+ feishu: {
356
+ enabled: true,
357
+ dmPolicy: "open",
358
+ },
359
+ },
360
+ } as ClawdbotConfig;
361
+
362
+ const event: FeishuMessageEvent = {
363
+ sender: {
364
+ sender_id: {
365
+ open_id: "ou-replier",
366
+ },
367
+ },
368
+ message: {
369
+ message_id: "om_reply_001",
370
+ root_id: "om_root_001",
371
+ parent_id: "om_parent_001",
372
+ chat_id: "oc-dm",
373
+ chat_type: "p2p",
374
+ message_type: "text",
375
+ content: JSON.stringify({ text: "reply text" }),
376
+ },
377
+ };
378
+
379
+ await dispatchMessage({ cfg, event });
380
+
381
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
382
+ expect.objectContaining({
383
+ ReplyToId: "om_parent_001",
384
+ RootMessageId: "om_root_001",
385
+ ReplyToBody: "quoted content",
386
+ }),
387
+ );
388
+ });
389
+
390
+ it("replies pairing challenge to DM chat_id instead of user:sender id", async () => {
391
+ const cfg: ClawdbotConfig = {
392
+ channels: {
393
+ feishu: {
394
+ dmPolicy: "pairing",
395
+ },
396
+ },
397
+ } as ClawdbotConfig;
398
+
399
+ const event: FeishuMessageEvent = {
400
+ sender: {
401
+ sender_id: {
402
+ user_id: "u_mobile_only",
403
+ },
404
+ },
405
+ message: {
406
+ message_id: "msg-pairing-chat-reply",
407
+ chat_id: "oc_dm_chat_1",
408
+ chat_type: "p2p",
409
+ message_type: "text",
410
+ content: JSON.stringify({ text: "hello" }),
411
+ },
412
+ };
413
+
414
+ mockReadAllowFromStore.mockResolvedValue([]);
415
+ mockUpsertPairingRequest.mockResolvedValue({ code: "ABCDEFGH", created: true });
416
+
417
+ await dispatchMessage({ cfg, event });
418
+
419
+ expect(mockSendMessageFeishu).toHaveBeenCalledWith(
420
+ expect.objectContaining({
421
+ to: "chat:oc_dm_chat_1",
422
+ }),
423
+ );
424
+ });
425
+ it("creates pairing request and drops unauthorized DMs in pairing mode", async () => {
426
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
427
+ mockReadAllowFromStore.mockResolvedValue([]);
428
+ mockUpsertPairingRequest.mockResolvedValue({ code: "ABCDEFGH", created: true });
429
+
430
+ const cfg: ClawdbotConfig = {
431
+ channels: {
432
+ feishu: {
433
+ dmPolicy: "pairing",
434
+ allowFrom: [],
435
+ },
436
+ },
437
+ } as ClawdbotConfig;
438
+
439
+ const event: FeishuMessageEvent = {
440
+ sender: {
441
+ sender_id: {
442
+ open_id: "ou-unapproved",
443
+ },
444
+ },
445
+ message: {
446
+ message_id: "msg-pairing-flow",
447
+ chat_id: "oc-dm",
448
+ chat_type: "p2p",
449
+ message_type: "text",
450
+ content: JSON.stringify({ text: "hello" }),
451
+ },
452
+ };
453
+
454
+ await dispatchMessage({ cfg, event });
455
+
456
+ expect(mockUpsertPairingRequest).toHaveBeenCalledWith({
457
+ channel: "feishu",
458
+ accountId: "default",
459
+ id: "ou-unapproved",
460
+ meta: { name: undefined },
461
+ });
462
+ expect(mockSendMessageFeishu).toHaveBeenCalledWith(
463
+ expect.objectContaining({
464
+ to: "chat:oc-dm",
465
+ text: expect.stringContaining("Your Feishu user id: ou-unapproved"),
466
+ accountId: "default",
467
+ }),
468
+ );
469
+ expect(mockSendMessageFeishu).toHaveBeenCalledWith(
470
+ expect.objectContaining({
471
+ to: "chat:oc-dm",
472
+ text: expect.stringContaining("Pairing code: ABCDEFGH"),
473
+ accountId: "default",
474
+ }),
475
+ );
476
+ expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
477
+ expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
478
+ });
479
+
480
+ it("computes group command authorization from group allowFrom", async () => {
481
+ mockShouldComputeCommandAuthorized.mockReturnValue(true);
482
+ mockResolveCommandAuthorizedFromAuthorizers.mockReturnValue(false);
483
+
484
+ const cfg: ClawdbotConfig = {
485
+ commands: { useAccessGroups: true },
486
+ channels: {
487
+ feishu: {
488
+ groups: {
489
+ "oc-group": {
490
+ requireMention: false,
491
+ },
492
+ },
493
+ },
494
+ },
495
+ } as ClawdbotConfig;
496
+
497
+ const event: FeishuMessageEvent = {
498
+ sender: {
499
+ sender_id: {
500
+ open_id: "ou-attacker",
501
+ },
502
+ },
503
+ message: {
504
+ message_id: "msg-group-command-auth",
505
+ chat_id: "oc-group",
506
+ chat_type: "group",
507
+ message_type: "text",
508
+ content: JSON.stringify({ text: "/status" }),
509
+ },
510
+ };
511
+
512
+ await dispatchMessage({ cfg, event });
513
+
514
+ expect(mockResolveCommandAuthorizedFromAuthorizers).toHaveBeenCalledWith({
515
+ useAccessGroups: true,
516
+ authorizers: [{ configured: false, allowed: false }],
517
+ });
518
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
519
+ expect.objectContaining({
520
+ ChatType: "group",
521
+ CommandAuthorized: false,
522
+ SenderId: "ou-attacker",
523
+ }),
524
+ );
525
+ });
526
+
527
+ it("normalizes group mention-prefixed slash commands before command-auth probing", async () => {
528
+ mockShouldComputeCommandAuthorized.mockReturnValue(true);
529
+
530
+ const cfg: ClawdbotConfig = {
531
+ channels: {
532
+ feishu: {
533
+ groups: {
534
+ "oc-group": {
535
+ requireMention: false,
536
+ },
537
+ },
538
+ },
539
+ },
540
+ } as ClawdbotConfig;
541
+
542
+ const event: FeishuMessageEvent = {
543
+ sender: {
544
+ sender_id: {
545
+ open_id: "ou-attacker",
546
+ },
547
+ },
548
+ message: {
549
+ message_id: "msg-group-mention-command-probe",
550
+ chat_id: "oc-group",
551
+ chat_type: "group",
552
+ message_type: "text",
553
+ content: JSON.stringify({ text: "@_user_1/model" }),
554
+ mentions: [{ key: "@_user_1", id: { open_id: "ou-bot" }, name: "Bot", tenant_key: "" }],
555
+ },
556
+ };
557
+
558
+ await dispatchMessage({ cfg, event });
559
+
560
+ expect(mockShouldComputeCommandAuthorized).toHaveBeenCalledWith("/model", cfg);
561
+ });
562
+
563
+ it("falls back to top-level allowFrom for group command authorization", async () => {
564
+ mockShouldComputeCommandAuthorized.mockReturnValue(true);
565
+ mockResolveCommandAuthorizedFromAuthorizers.mockReturnValue(true);
566
+
567
+ const cfg: ClawdbotConfig = {
568
+ commands: { useAccessGroups: true },
569
+ channels: {
570
+ feishu: {
571
+ allowFrom: ["ou-admin"],
572
+ groups: {
573
+ "oc-group": {
574
+ requireMention: false,
575
+ },
576
+ },
577
+ },
578
+ },
579
+ } as ClawdbotConfig;
580
+
581
+ const event: FeishuMessageEvent = {
582
+ sender: {
583
+ sender_id: {
584
+ open_id: "ou-admin",
585
+ },
586
+ },
587
+ message: {
588
+ message_id: "msg-group-command-fallback",
589
+ chat_id: "oc-group",
590
+ chat_type: "group",
591
+ message_type: "text",
592
+ content: JSON.stringify({ text: "/status" }),
593
+ },
594
+ };
595
+
596
+ await dispatchMessage({ cfg, event });
597
+
598
+ expect(mockResolveCommandAuthorizedFromAuthorizers).toHaveBeenCalledWith({
599
+ useAccessGroups: true,
600
+ authorizers: [{ configured: true, allowed: true }],
601
+ });
602
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
603
+ expect.objectContaining({
604
+ ChatType: "group",
605
+ CommandAuthorized: true,
606
+ SenderId: "ou-admin",
607
+ }),
608
+ );
609
+ });
610
+
611
+ it("allows group sender when global groupSenderAllowFrom includes sender", async () => {
612
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
613
+
614
+ const cfg: ClawdbotConfig = {
615
+ channels: {
616
+ feishu: {
617
+ groupPolicy: "open",
618
+ groupSenderAllowFrom: ["ou-allowed"],
619
+ groups: {
620
+ "oc-group": {
621
+ requireMention: false,
622
+ },
623
+ },
624
+ },
625
+ },
626
+ } as ClawdbotConfig;
627
+
628
+ const event: FeishuMessageEvent = {
629
+ sender: {
630
+ sender_id: {
631
+ open_id: "ou-allowed",
632
+ },
633
+ },
634
+ message: {
635
+ message_id: "msg-global-group-sender-allow",
636
+ chat_id: "oc-group",
637
+ chat_type: "group",
638
+ message_type: "text",
639
+ content: JSON.stringify({ text: "hello" }),
640
+ },
641
+ };
642
+
643
+ await dispatchMessage({ cfg, event });
644
+
645
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
646
+ expect.objectContaining({
647
+ ChatType: "group",
648
+ SenderId: "ou-allowed",
649
+ }),
650
+ );
651
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
652
+ });
653
+
654
+ it("blocks group sender when global groupSenderAllowFrom excludes sender", async () => {
655
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
656
+
657
+ const cfg: ClawdbotConfig = {
658
+ channels: {
659
+ feishu: {
660
+ groupPolicy: "open",
661
+ groupSenderAllowFrom: ["ou-allowed"],
662
+ groups: {
663
+ "oc-group": {
664
+ requireMention: false,
665
+ },
666
+ },
667
+ },
668
+ },
669
+ } as ClawdbotConfig;
670
+
671
+ const event: FeishuMessageEvent = {
672
+ sender: {
673
+ sender_id: {
674
+ open_id: "ou-blocked",
675
+ },
676
+ },
677
+ message: {
678
+ message_id: "msg-global-group-sender-block",
679
+ chat_id: "oc-group",
680
+ chat_type: "group",
681
+ message_type: "text",
682
+ content: JSON.stringify({ text: "hello" }),
683
+ },
684
+ };
685
+
686
+ await dispatchMessage({ cfg, event });
687
+
688
+ expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
689
+ expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
690
+ });
691
+
692
+ it("prefers per-group allowFrom over global groupSenderAllowFrom", async () => {
693
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
694
+
695
+ const cfg: ClawdbotConfig = {
696
+ channels: {
697
+ feishu: {
698
+ groupPolicy: "open",
699
+ groupSenderAllowFrom: ["ou-global"],
700
+ groups: {
701
+ "oc-group": {
702
+ allowFrom: ["ou-group-only"],
703
+ requireMention: false,
704
+ },
705
+ },
706
+ },
707
+ },
708
+ } as ClawdbotConfig;
709
+
710
+ const event: FeishuMessageEvent = {
711
+ sender: {
712
+ sender_id: {
713
+ open_id: "ou-global",
714
+ },
715
+ },
716
+ message: {
717
+ message_id: "msg-per-group-precedence",
718
+ chat_id: "oc-group",
719
+ chat_type: "group",
720
+ message_type: "text",
721
+ content: JSON.stringify({ text: "hello" }),
722
+ },
723
+ };
724
+
725
+ await dispatchMessage({ cfg, event });
726
+
727
+ expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
728
+ expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
729
+ });
730
+
731
+ it("drops message when groupConfig.enabled is false", async () => {
732
+ const cfg: ClawdbotConfig = {
733
+ channels: {
734
+ feishu: {
735
+ groups: {
736
+ "oc-disabled-group": {
737
+ enabled: false,
738
+ },
739
+ },
740
+ },
741
+ },
742
+ } as ClawdbotConfig;
743
+
744
+ const event: FeishuMessageEvent = {
745
+ sender: {
746
+ sender_id: { open_id: "ou-sender" },
747
+ },
748
+ message: {
749
+ message_id: "msg-disabled-group",
750
+ chat_id: "oc-disabled-group",
751
+ chat_type: "group",
752
+ message_type: "text",
753
+ content: JSON.stringify({ text: "hello" }),
754
+ },
755
+ };
756
+
757
+ await dispatchMessage({ cfg, event });
758
+
759
+ expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
760
+ expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
761
+ });
762
+
763
+ it("uses video file_key (not thumbnail image_key) for inbound video download", async () => {
764
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
765
+
766
+ const cfg: ClawdbotConfig = {
767
+ channels: {
768
+ feishu: {
769
+ dmPolicy: "open",
770
+ },
771
+ },
772
+ } as ClawdbotConfig;
773
+
774
+ const event: FeishuMessageEvent = {
775
+ sender: {
776
+ sender_id: {
777
+ open_id: "ou-sender",
778
+ },
779
+ },
780
+ message: {
781
+ message_id: "msg-video-inbound",
782
+ chat_id: "oc-dm",
783
+ chat_type: "p2p",
784
+ message_type: "video",
785
+ content: JSON.stringify({
786
+ file_key: "file_video_payload",
787
+ image_key: "img_thumb_payload",
788
+ file_name: "clip.mp4",
789
+ }),
790
+ },
791
+ };
792
+
793
+ await dispatchMessage({ cfg, event });
794
+
795
+ expect(mockDownloadMessageResourceFeishu).toHaveBeenCalledWith(
796
+ expect.objectContaining({
797
+ messageId: "msg-video-inbound",
798
+ fileKey: "file_video_payload",
799
+ type: "file",
800
+ }),
801
+ );
802
+ expect(mockSaveMediaBuffer).toHaveBeenCalledWith(
803
+ expect.any(Buffer),
804
+ "video/mp4",
805
+ "inbound",
806
+ expect.any(Number),
807
+ "clip.mp4",
808
+ );
809
+ });
810
+
811
+ it("uses media message_type file_key (not thumbnail image_key) for inbound mobile video download", async () => {
812
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
813
+
814
+ const cfg: ClawdbotConfig = {
815
+ channels: {
816
+ feishu: {
817
+ dmPolicy: "open",
818
+ },
819
+ },
820
+ } as ClawdbotConfig;
821
+
822
+ const event: FeishuMessageEvent = {
823
+ sender: {
824
+ sender_id: {
825
+ open_id: "ou-sender",
826
+ },
827
+ },
828
+ message: {
829
+ message_id: "msg-media-inbound",
830
+ chat_id: "oc-dm",
831
+ chat_type: "p2p",
832
+ message_type: "media",
833
+ content: JSON.stringify({
834
+ file_key: "file_media_payload",
835
+ image_key: "img_media_thumb",
836
+ file_name: "mobile.mp4",
837
+ }),
838
+ },
839
+ };
840
+
841
+ await dispatchMessage({ cfg, event });
842
+
843
+ expect(mockDownloadMessageResourceFeishu).toHaveBeenCalledWith(
844
+ expect.objectContaining({
845
+ messageId: "msg-media-inbound",
846
+ fileKey: "file_media_payload",
847
+ type: "file",
848
+ }),
849
+ );
850
+ expect(mockSaveMediaBuffer).toHaveBeenCalledWith(
851
+ expect.any(Buffer),
852
+ "video/mp4",
853
+ "inbound",
854
+ expect.any(Number),
855
+ "clip.mp4",
856
+ );
857
+ });
858
+
859
+ it("downloads embedded media tags from post messages as files", async () => {
860
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
861
+
862
+ const cfg: ClawdbotConfig = {
863
+ channels: {
864
+ feishu: {
865
+ dmPolicy: "open",
866
+ },
867
+ },
868
+ } as ClawdbotConfig;
869
+
870
+ const event: FeishuMessageEvent = {
871
+ sender: {
872
+ sender_id: {
873
+ open_id: "ou-sender",
874
+ },
875
+ },
876
+ message: {
877
+ message_id: "msg-post-media",
878
+ chat_id: "oc-dm",
879
+ chat_type: "p2p",
880
+ message_type: "post",
881
+ content: JSON.stringify({
882
+ title: "Rich text",
883
+ content: [
884
+ [
885
+ {
886
+ tag: "media",
887
+ file_key: "file_post_media_payload",
888
+ file_name: "embedded.mov",
889
+ },
890
+ ],
891
+ ],
892
+ }),
893
+ },
894
+ };
895
+
896
+ await dispatchMessage({ cfg, event });
897
+
898
+ expect(mockDownloadMessageResourceFeishu).toHaveBeenCalledWith(
899
+ expect.objectContaining({
900
+ messageId: "msg-post-media",
901
+ fileKey: "file_post_media_payload",
902
+ type: "file",
903
+ }),
904
+ );
905
+ expect(mockSaveMediaBuffer).toHaveBeenCalledWith(
906
+ expect.any(Buffer),
907
+ "video/mp4",
908
+ "inbound",
909
+ expect.any(Number),
910
+ );
911
+ });
912
+
913
+ it("includes message_id in BodyForAgent on its own line", async () => {
914
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
915
+
916
+ const cfg: ClawdbotConfig = {
917
+ channels: {
918
+ feishu: {
919
+ dmPolicy: "open",
920
+ },
921
+ },
922
+ } as ClawdbotConfig;
923
+
924
+ const event: FeishuMessageEvent = {
925
+ sender: {
926
+ sender_id: {
927
+ open_id: "ou-msgid",
928
+ },
929
+ },
930
+ message: {
931
+ message_id: "msg-message-id-line",
932
+ chat_id: "oc-dm",
933
+ chat_type: "p2p",
934
+ message_type: "text",
935
+ content: JSON.stringify({ text: "hello" }),
936
+ },
937
+ };
938
+
939
+ await dispatchMessage({ cfg, event });
940
+
941
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
942
+ expect.objectContaining({
943
+ BodyForAgent: "[message_id: msg-message-id-line]\nou-msgid: hello",
944
+ }),
945
+ );
946
+ });
947
+
948
+ it("expands merge_forward content from API sub-messages", async () => {
949
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
950
+ const mockGetMerged = vi.fn().mockResolvedValue({
951
+ code: 0,
952
+ data: {
953
+ items: [
954
+ {
955
+ message_id: "container",
956
+ msg_type: "merge_forward",
957
+ body: { content: JSON.stringify({ text: "Merged and Forwarded Message" }) },
958
+ },
959
+ {
960
+ message_id: "sub-2",
961
+ upper_message_id: "container",
962
+ msg_type: "file",
963
+ body: { content: JSON.stringify({ file_name: "report.pdf" }) },
964
+ create_time: "2000",
965
+ },
966
+ {
967
+ message_id: "sub-1",
968
+ upper_message_id: "container",
969
+ msg_type: "text",
970
+ body: { content: JSON.stringify({ text: "alpha" }) },
971
+ create_time: "1000",
972
+ },
973
+ ],
974
+ },
975
+ });
976
+ mockCreateFeishuClient.mockReturnValue({
977
+ contact: {
978
+ user: {
979
+ get: vi.fn().mockResolvedValue({ data: { user: { name: "Sender" } } }),
980
+ },
981
+ },
982
+ im: {
983
+ message: {
984
+ get: mockGetMerged,
985
+ },
986
+ },
987
+ });
988
+
989
+ const cfg: ClawdbotConfig = {
990
+ channels: {
991
+ feishu: {
992
+ dmPolicy: "open",
993
+ },
994
+ },
995
+ } as ClawdbotConfig;
996
+
997
+ const event: FeishuMessageEvent = {
998
+ sender: {
999
+ sender_id: {
1000
+ open_id: "ou-merge",
1001
+ },
1002
+ },
1003
+ message: {
1004
+ message_id: "msg-merge-forward",
1005
+ chat_id: "oc-dm",
1006
+ chat_type: "p2p",
1007
+ message_type: "merge_forward",
1008
+ content: JSON.stringify({ text: "Merged and Forwarded Message" }),
1009
+ },
1010
+ };
1011
+
1012
+ await dispatchMessage({ cfg, event });
1013
+
1014
+ expect(mockGetMerged).toHaveBeenCalledWith({
1015
+ path: { message_id: "msg-merge-forward" },
1016
+ });
1017
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
1018
+ expect.objectContaining({
1019
+ BodyForAgent: expect.stringContaining(
1020
+ "[Merged and Forwarded Messages]\n- alpha\n- [File: report.pdf]",
1021
+ ),
1022
+ }),
1023
+ );
1024
+ });
1025
+
1026
+ it("falls back when merge_forward API returns no sub-messages", async () => {
1027
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1028
+ mockCreateFeishuClient.mockReturnValue({
1029
+ contact: {
1030
+ user: {
1031
+ get: vi.fn().mockResolvedValue({ data: { user: { name: "Sender" } } }),
1032
+ },
1033
+ },
1034
+ im: {
1035
+ message: {
1036
+ get: vi.fn().mockResolvedValue({ code: 0, data: { items: [] } }),
1037
+ },
1038
+ },
1039
+ });
1040
+
1041
+ const cfg: ClawdbotConfig = {
1042
+ channels: {
1043
+ feishu: {
1044
+ dmPolicy: "open",
1045
+ },
1046
+ },
1047
+ } as ClawdbotConfig;
1048
+
1049
+ const event: FeishuMessageEvent = {
1050
+ sender: {
1051
+ sender_id: {
1052
+ open_id: "ou-merge-empty",
1053
+ },
1054
+ },
1055
+ message: {
1056
+ message_id: "msg-merge-empty",
1057
+ chat_id: "oc-dm",
1058
+ chat_type: "p2p",
1059
+ message_type: "merge_forward",
1060
+ content: JSON.stringify({ text: "Merged and Forwarded Message" }),
1061
+ },
1062
+ };
1063
+
1064
+ await dispatchMessage({ cfg, event });
1065
+
1066
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
1067
+ expect.objectContaining({
1068
+ BodyForAgent: expect.stringContaining("[Merged and Forwarded Message - could not fetch]"),
1069
+ }),
1070
+ );
1071
+ });
1072
+
1073
+ it("dispatches once and appends permission notice to the main agent body", async () => {
1074
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1075
+ mockCreateFeishuClient.mockReturnValue({
1076
+ contact: {
1077
+ user: {
1078
+ get: vi.fn().mockRejectedValue({
1079
+ response: {
1080
+ data: {
1081
+ code: 99991672,
1082
+ msg: "permission denied https://open.feishu.cn/app/cli_test",
1083
+ },
1084
+ },
1085
+ }),
1086
+ },
1087
+ },
1088
+ });
1089
+
1090
+ const cfg: ClawdbotConfig = {
1091
+ channels: {
1092
+ feishu: {
1093
+ appId: "cli_test",
1094
+ appSecret: "sec_test", // pragma: allowlist secret
1095
+ groups: {
1096
+ "oc-group": {
1097
+ requireMention: false,
1098
+ },
1099
+ },
1100
+ },
1101
+ },
1102
+ } as ClawdbotConfig;
1103
+
1104
+ const event: FeishuMessageEvent = {
1105
+ sender: {
1106
+ sender_id: {
1107
+ open_id: "ou-perm",
1108
+ },
1109
+ },
1110
+ message: {
1111
+ message_id: "msg-perm-1",
1112
+ chat_id: "oc-group",
1113
+ chat_type: "group",
1114
+ message_type: "text",
1115
+ content: JSON.stringify({ text: "hello group" }),
1116
+ },
1117
+ };
1118
+
1119
+ await dispatchMessage({ cfg, event });
1120
+
1121
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
1122
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
1123
+ expect.objectContaining({
1124
+ BodyForAgent: expect.stringContaining(
1125
+ "Permission grant URL: https://open.feishu.cn/app/cli_test",
1126
+ ),
1127
+ }),
1128
+ );
1129
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
1130
+ expect.objectContaining({
1131
+ BodyForAgent: expect.stringContaining("ou-perm: hello group"),
1132
+ }),
1133
+ );
1134
+ });
1135
+
1136
+ it("ignores stale non-existent contact scope permission errors", async () => {
1137
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1138
+ mockCreateFeishuClient.mockReturnValue({
1139
+ contact: {
1140
+ user: {
1141
+ get: vi.fn().mockRejectedValue({
1142
+ response: {
1143
+ data: {
1144
+ code: 99991672,
1145
+ msg: "permission denied: contact:contact.base:readonly https://open.feishu.cn/app/cli_scope_bug",
1146
+ },
1147
+ },
1148
+ }),
1149
+ },
1150
+ },
1151
+ });
1152
+
1153
+ const cfg: ClawdbotConfig = {
1154
+ channels: {
1155
+ feishu: {
1156
+ appId: "cli_scope_bug",
1157
+ appSecret: "sec_scope_bug", // pragma: allowlist secret
1158
+ groups: {
1159
+ "oc-group": {
1160
+ requireMention: false,
1161
+ },
1162
+ },
1163
+ },
1164
+ },
1165
+ } as ClawdbotConfig;
1166
+
1167
+ const event: FeishuMessageEvent = {
1168
+ sender: {
1169
+ sender_id: {
1170
+ open_id: "ou-perm-scope",
1171
+ },
1172
+ },
1173
+ message: {
1174
+ message_id: "msg-perm-scope-1",
1175
+ chat_id: "oc-group",
1176
+ chat_type: "group",
1177
+ message_type: "text",
1178
+ content: JSON.stringify({ text: "hello group" }),
1179
+ },
1180
+ };
1181
+
1182
+ await dispatchMessage({ cfg, event });
1183
+
1184
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
1185
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
1186
+ expect.objectContaining({
1187
+ BodyForAgent: expect.not.stringContaining("Permission grant URL"),
1188
+ }),
1189
+ );
1190
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
1191
+ expect.objectContaining({
1192
+ BodyForAgent: expect.stringContaining("ou-perm-scope: hello group"),
1193
+ }),
1194
+ );
1195
+ });
1196
+
1197
+ it("routes group sessions by sender when groupSessionScope=group_sender", async () => {
1198
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1199
+
1200
+ const cfg: ClawdbotConfig = {
1201
+ channels: {
1202
+ feishu: {
1203
+ groups: {
1204
+ "oc-group": {
1205
+ requireMention: false,
1206
+ groupSessionScope: "group_sender",
1207
+ },
1208
+ },
1209
+ },
1210
+ },
1211
+ } as ClawdbotConfig;
1212
+
1213
+ const event: FeishuMessageEvent = {
1214
+ sender: { sender_id: { open_id: "ou-scope-user" } },
1215
+ message: {
1216
+ message_id: "msg-scope-group-sender",
1217
+ chat_id: "oc-group",
1218
+ chat_type: "group",
1219
+ message_type: "text",
1220
+ content: JSON.stringify({ text: "group sender scope" }),
1221
+ },
1222
+ };
1223
+
1224
+ await dispatchMessage({ cfg, event });
1225
+
1226
+ expect(mockResolveAgentRoute).toHaveBeenCalledWith(
1227
+ expect.objectContaining({
1228
+ peer: { kind: "group", id: "oc-group:sender:ou-scope-user" },
1229
+ parentPeer: null,
1230
+ }),
1231
+ );
1232
+ });
1233
+
1234
+ it("routes topic sessions and parentPeer when groupSessionScope=group_topic_sender", async () => {
1235
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1236
+
1237
+ const cfg: ClawdbotConfig = {
1238
+ channels: {
1239
+ feishu: {
1240
+ groups: {
1241
+ "oc-group": {
1242
+ requireMention: false,
1243
+ groupSessionScope: "group_topic_sender",
1244
+ },
1245
+ },
1246
+ },
1247
+ },
1248
+ } as ClawdbotConfig;
1249
+
1250
+ const event: FeishuMessageEvent = {
1251
+ sender: { sender_id: { open_id: "ou-topic-user" } },
1252
+ message: {
1253
+ message_id: "msg-scope-topic-sender",
1254
+ chat_id: "oc-group",
1255
+ chat_type: "group",
1256
+ root_id: "om_root_topic",
1257
+ message_type: "text",
1258
+ content: JSON.stringify({ text: "topic sender scope" }),
1259
+ },
1260
+ };
1261
+
1262
+ await dispatchMessage({ cfg, event });
1263
+
1264
+ expect(mockResolveAgentRoute).toHaveBeenCalledWith(
1265
+ expect.objectContaining({
1266
+ peer: { kind: "group", id: "oc-group:topic:om_root_topic:sender:ou-topic-user" },
1267
+ parentPeer: { kind: "group", id: "oc-group" },
1268
+ }),
1269
+ );
1270
+ });
1271
+
1272
+ it("keeps root_id as topic key when root_id and thread_id both exist", async () => {
1273
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1274
+
1275
+ const cfg: ClawdbotConfig = {
1276
+ channels: {
1277
+ feishu: {
1278
+ groups: {
1279
+ "oc-group": {
1280
+ requireMention: false,
1281
+ groupSessionScope: "group_topic_sender",
1282
+ },
1283
+ },
1284
+ },
1285
+ },
1286
+ } as ClawdbotConfig;
1287
+
1288
+ const event: FeishuMessageEvent = {
1289
+ sender: { sender_id: { open_id: "ou-topic-user" } },
1290
+ message: {
1291
+ message_id: "msg-scope-topic-thread-id",
1292
+ chat_id: "oc-group",
1293
+ chat_type: "group",
1294
+ root_id: "om_root_topic",
1295
+ thread_id: "omt_topic_1",
1296
+ message_type: "text",
1297
+ content: JSON.stringify({ text: "topic sender scope" }),
1298
+ },
1299
+ };
1300
+
1301
+ await dispatchMessage({ cfg, event });
1302
+
1303
+ expect(mockResolveAgentRoute).toHaveBeenCalledWith(
1304
+ expect.objectContaining({
1305
+ peer: { kind: "group", id: "oc-group:topic:om_root_topic:sender:ou-topic-user" },
1306
+ parentPeer: { kind: "group", id: "oc-group" },
1307
+ }),
1308
+ );
1309
+ });
1310
+
1311
+ it("uses thread_id as topic key when root_id is missing", async () => {
1312
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1313
+
1314
+ const cfg: ClawdbotConfig = {
1315
+ channels: {
1316
+ feishu: {
1317
+ groups: {
1318
+ "oc-group": {
1319
+ requireMention: false,
1320
+ groupSessionScope: "group_topic_sender",
1321
+ },
1322
+ },
1323
+ },
1324
+ },
1325
+ } as ClawdbotConfig;
1326
+
1327
+ const event: FeishuMessageEvent = {
1328
+ sender: { sender_id: { open_id: "ou-topic-user" } },
1329
+ message: {
1330
+ message_id: "msg-scope-topic-thread-only",
1331
+ chat_id: "oc-group",
1332
+ chat_type: "group",
1333
+ thread_id: "omt_topic_1",
1334
+ message_type: "text",
1335
+ content: JSON.stringify({ text: "topic sender scope" }),
1336
+ },
1337
+ };
1338
+
1339
+ await dispatchMessage({ cfg, event });
1340
+
1341
+ expect(mockResolveAgentRoute).toHaveBeenCalledWith(
1342
+ expect.objectContaining({
1343
+ peer: { kind: "group", id: "oc-group:topic:omt_topic_1:sender:ou-topic-user" },
1344
+ parentPeer: { kind: "group", id: "oc-group" },
1345
+ }),
1346
+ );
1347
+ });
1348
+
1349
+ it("maps legacy topicSessionMode=enabled to group_topic routing", async () => {
1350
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1351
+
1352
+ const cfg: ClawdbotConfig = {
1353
+ channels: {
1354
+ feishu: {
1355
+ topicSessionMode: "enabled",
1356
+ groups: {
1357
+ "oc-group": {
1358
+ requireMention: false,
1359
+ },
1360
+ },
1361
+ },
1362
+ },
1363
+ } as ClawdbotConfig;
1364
+
1365
+ const event: FeishuMessageEvent = {
1366
+ sender: { sender_id: { open_id: "ou-legacy" } },
1367
+ message: {
1368
+ message_id: "msg-legacy-topic-mode",
1369
+ chat_id: "oc-group",
1370
+ chat_type: "group",
1371
+ root_id: "om_root_legacy",
1372
+ message_type: "text",
1373
+ content: JSON.stringify({ text: "legacy topic mode" }),
1374
+ },
1375
+ };
1376
+
1377
+ await dispatchMessage({ cfg, event });
1378
+
1379
+ expect(mockResolveAgentRoute).toHaveBeenCalledWith(
1380
+ expect.objectContaining({
1381
+ peer: { kind: "group", id: "oc-group:topic:om_root_legacy" },
1382
+ parentPeer: { kind: "group", id: "oc-group" },
1383
+ }),
1384
+ );
1385
+ });
1386
+
1387
+ it("maps legacy topicSessionMode=enabled to root_id when both root_id and thread_id exist", async () => {
1388
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1389
+
1390
+ const cfg: ClawdbotConfig = {
1391
+ channels: {
1392
+ feishu: {
1393
+ topicSessionMode: "enabled",
1394
+ groups: {
1395
+ "oc-group": {
1396
+ requireMention: false,
1397
+ },
1398
+ },
1399
+ },
1400
+ },
1401
+ } as ClawdbotConfig;
1402
+
1403
+ const event: FeishuMessageEvent = {
1404
+ sender: { sender_id: { open_id: "ou-legacy-thread-id" } },
1405
+ message: {
1406
+ message_id: "msg-legacy-topic-thread-id",
1407
+ chat_id: "oc-group",
1408
+ chat_type: "group",
1409
+ root_id: "om_root_legacy",
1410
+ thread_id: "omt_topic_legacy",
1411
+ message_type: "text",
1412
+ content: JSON.stringify({ text: "legacy topic mode" }),
1413
+ },
1414
+ };
1415
+
1416
+ await dispatchMessage({ cfg, event });
1417
+
1418
+ expect(mockResolveAgentRoute).toHaveBeenCalledWith(
1419
+ expect.objectContaining({
1420
+ peer: { kind: "group", id: "oc-group:topic:om_root_legacy" },
1421
+ parentPeer: { kind: "group", id: "oc-group" },
1422
+ }),
1423
+ );
1424
+ });
1425
+
1426
+ it("uses message_id as topic root when group_topic + replyInThread and no root_id", async () => {
1427
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1428
+
1429
+ const cfg: ClawdbotConfig = {
1430
+ channels: {
1431
+ feishu: {
1432
+ groups: {
1433
+ "oc-group": {
1434
+ requireMention: false,
1435
+ groupSessionScope: "group_topic",
1436
+ replyInThread: "enabled",
1437
+ },
1438
+ },
1439
+ },
1440
+ },
1441
+ } as ClawdbotConfig;
1442
+
1443
+ const event: FeishuMessageEvent = {
1444
+ sender: { sender_id: { open_id: "ou-topic-init" } },
1445
+ message: {
1446
+ message_id: "msg-new-topic-root",
1447
+ chat_id: "oc-group",
1448
+ chat_type: "group",
1449
+ message_type: "text",
1450
+ content: JSON.stringify({ text: "create topic" }),
1451
+ },
1452
+ };
1453
+
1454
+ await dispatchMessage({ cfg, event });
1455
+
1456
+ expect(mockResolveAgentRoute).toHaveBeenCalledWith(
1457
+ expect.objectContaining({
1458
+ peer: { kind: "group", id: "oc-group:topic:msg-new-topic-root" },
1459
+ parentPeer: { kind: "group", id: "oc-group" },
1460
+ }),
1461
+ );
1462
+ });
1463
+
1464
+ it("keeps topic session key stable after first turn creates a thread", async () => {
1465
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1466
+
1467
+ const cfg: ClawdbotConfig = {
1468
+ channels: {
1469
+ feishu: {
1470
+ groups: {
1471
+ "oc-group": {
1472
+ requireMention: false,
1473
+ groupSessionScope: "group_topic",
1474
+ replyInThread: "enabled",
1475
+ },
1476
+ },
1477
+ },
1478
+ },
1479
+ } as ClawdbotConfig;
1480
+
1481
+ const firstTurn: FeishuMessageEvent = {
1482
+ sender: { sender_id: { open_id: "ou-topic-init" } },
1483
+ message: {
1484
+ message_id: "msg-topic-first",
1485
+ chat_id: "oc-group",
1486
+ chat_type: "group",
1487
+ message_type: "text",
1488
+ content: JSON.stringify({ text: "create topic" }),
1489
+ },
1490
+ };
1491
+ const secondTurn: FeishuMessageEvent = {
1492
+ sender: { sender_id: { open_id: "ou-topic-init" } },
1493
+ message: {
1494
+ message_id: "msg-topic-second",
1495
+ chat_id: "oc-group",
1496
+ chat_type: "group",
1497
+ root_id: "msg-topic-first",
1498
+ thread_id: "omt_topic_created",
1499
+ message_type: "text",
1500
+ content: JSON.stringify({ text: "follow up in same topic" }),
1501
+ },
1502
+ };
1503
+
1504
+ await dispatchMessage({ cfg, event: firstTurn });
1505
+ await dispatchMessage({ cfg, event: secondTurn });
1506
+
1507
+ expect(mockResolveAgentRoute).toHaveBeenNthCalledWith(
1508
+ 1,
1509
+ expect.objectContaining({
1510
+ peer: { kind: "group", id: "oc-group:topic:msg-topic-first" },
1511
+ }),
1512
+ );
1513
+ expect(mockResolveAgentRoute).toHaveBeenNthCalledWith(
1514
+ 2,
1515
+ expect.objectContaining({
1516
+ peer: { kind: "group", id: "oc-group:topic:msg-topic-first" },
1517
+ }),
1518
+ );
1519
+ });
1520
+
1521
+ it("replies to the topic root when handling a message inside an existing topic", async () => {
1522
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1523
+
1524
+ const cfg: ClawdbotConfig = {
1525
+ channels: {
1526
+ feishu: {
1527
+ groups: {
1528
+ "oc-group": {
1529
+ requireMention: false,
1530
+ replyInThread: "enabled",
1531
+ },
1532
+ },
1533
+ },
1534
+ },
1535
+ } as ClawdbotConfig;
1536
+
1537
+ const event: FeishuMessageEvent = {
1538
+ sender: { sender_id: { open_id: "ou-topic-user" } },
1539
+ message: {
1540
+ message_id: "om_child_message",
1541
+ root_id: "om_root_topic",
1542
+ chat_id: "oc-group",
1543
+ chat_type: "group",
1544
+ message_type: "text",
1545
+ content: JSON.stringify({ text: "reply inside topic" }),
1546
+ },
1547
+ };
1548
+
1549
+ await dispatchMessage({ cfg, event });
1550
+
1551
+ expect(mockCreateFeishuReplyDispatcher).toHaveBeenCalledWith(
1552
+ expect.objectContaining({
1553
+ replyToMessageId: "om_root_topic",
1554
+ rootId: "om_root_topic",
1555
+ }),
1556
+ );
1557
+ });
1558
+
1559
+ it("replies to triggering message in normal group even when root_id is present (#32980)", async () => {
1560
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1561
+
1562
+ const cfg: ClawdbotConfig = {
1563
+ channels: {
1564
+ feishu: {
1565
+ groups: {
1566
+ "oc-group": {
1567
+ requireMention: false,
1568
+ groupSessionScope: "group",
1569
+ },
1570
+ },
1571
+ },
1572
+ },
1573
+ } as ClawdbotConfig;
1574
+
1575
+ const event: FeishuMessageEvent = {
1576
+ sender: { sender_id: { open_id: "ou-normal-user" } },
1577
+ message: {
1578
+ message_id: "om_quote_reply",
1579
+ root_id: "om_original_msg",
1580
+ chat_id: "oc-group",
1581
+ chat_type: "group",
1582
+ message_type: "text",
1583
+ content: JSON.stringify({ text: "hello in normal group" }),
1584
+ },
1585
+ };
1586
+
1587
+ await dispatchMessage({ cfg, event });
1588
+
1589
+ expect(mockCreateFeishuReplyDispatcher).toHaveBeenCalledWith(
1590
+ expect.objectContaining({
1591
+ replyToMessageId: "om_quote_reply",
1592
+ rootId: "om_original_msg",
1593
+ }),
1594
+ );
1595
+ });
1596
+
1597
+ it("replies to topic root in topic-mode group with root_id", async () => {
1598
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1599
+
1600
+ const cfg: ClawdbotConfig = {
1601
+ channels: {
1602
+ feishu: {
1603
+ groups: {
1604
+ "oc-group": {
1605
+ requireMention: false,
1606
+ groupSessionScope: "group_topic",
1607
+ },
1608
+ },
1609
+ },
1610
+ },
1611
+ } as ClawdbotConfig;
1612
+
1613
+ const event: FeishuMessageEvent = {
1614
+ sender: { sender_id: { open_id: "ou-topic-user" } },
1615
+ message: {
1616
+ message_id: "om_topic_reply",
1617
+ root_id: "om_topic_root",
1618
+ chat_id: "oc-group",
1619
+ chat_type: "group",
1620
+ message_type: "text",
1621
+ content: JSON.stringify({ text: "hello in topic group" }),
1622
+ },
1623
+ };
1624
+
1625
+ await dispatchMessage({ cfg, event });
1626
+
1627
+ expect(mockCreateFeishuReplyDispatcher).toHaveBeenCalledWith(
1628
+ expect.objectContaining({
1629
+ replyToMessageId: "om_topic_root",
1630
+ rootId: "om_topic_root",
1631
+ }),
1632
+ );
1633
+ });
1634
+
1635
+ it("replies to topic root in topic-sender group with root_id", async () => {
1636
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1637
+
1638
+ const cfg: ClawdbotConfig = {
1639
+ channels: {
1640
+ feishu: {
1641
+ groups: {
1642
+ "oc-group": {
1643
+ requireMention: false,
1644
+ groupSessionScope: "group_topic_sender",
1645
+ },
1646
+ },
1647
+ },
1648
+ },
1649
+ } as ClawdbotConfig;
1650
+
1651
+ const event: FeishuMessageEvent = {
1652
+ sender: { sender_id: { open_id: "ou-topic-sender-user" } },
1653
+ message: {
1654
+ message_id: "om_topic_sender_reply",
1655
+ root_id: "om_topic_sender_root",
1656
+ chat_id: "oc-group",
1657
+ chat_type: "group",
1658
+ message_type: "text",
1659
+ content: JSON.stringify({ text: "hello in topic sender group" }),
1660
+ },
1661
+ };
1662
+
1663
+ await dispatchMessage({ cfg, event });
1664
+
1665
+ expect(mockCreateFeishuReplyDispatcher).toHaveBeenCalledWith(
1666
+ expect.objectContaining({
1667
+ replyToMessageId: "om_topic_sender_root",
1668
+ rootId: "om_topic_sender_root",
1669
+ }),
1670
+ );
1671
+ });
1672
+
1673
+ it("forces thread replies when inbound message contains thread_id", async () => {
1674
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1675
+
1676
+ const cfg: ClawdbotConfig = {
1677
+ channels: {
1678
+ feishu: {
1679
+ groups: {
1680
+ "oc-group": {
1681
+ requireMention: false,
1682
+ groupSessionScope: "group",
1683
+ replyInThread: "disabled",
1684
+ },
1685
+ },
1686
+ },
1687
+ },
1688
+ } as ClawdbotConfig;
1689
+
1690
+ const event: FeishuMessageEvent = {
1691
+ sender: { sender_id: { open_id: "ou-thread-reply" } },
1692
+ message: {
1693
+ message_id: "msg-thread-reply",
1694
+ chat_id: "oc-group",
1695
+ chat_type: "group",
1696
+ thread_id: "omt_topic_thread_reply",
1697
+ message_type: "text",
1698
+ content: JSON.stringify({ text: "thread content" }),
1699
+ },
1700
+ };
1701
+
1702
+ await dispatchMessage({ cfg, event });
1703
+
1704
+ expect(mockCreateFeishuReplyDispatcher).toHaveBeenCalledWith(
1705
+ expect.objectContaining({
1706
+ replyInThread: true,
1707
+ threadReply: true,
1708
+ }),
1709
+ );
1710
+ });
1711
+
1712
+ it("does not dispatch twice for the same image message_id (concurrent dedupe)", async () => {
1713
+ mockShouldComputeCommandAuthorized.mockReturnValue(false);
1714
+
1715
+ const cfg: ClawdbotConfig = {
1716
+ channels: {
1717
+ feishu: {
1718
+ dmPolicy: "open",
1719
+ },
1720
+ },
1721
+ } as ClawdbotConfig;
1722
+
1723
+ const event: FeishuMessageEvent = {
1724
+ sender: {
1725
+ sender_id: {
1726
+ open_id: "ou-image-dedup",
1727
+ },
1728
+ },
1729
+ message: {
1730
+ message_id: "msg-image-dedup",
1731
+ chat_id: "oc-dm",
1732
+ chat_type: "p2p",
1733
+ message_type: "image",
1734
+ content: JSON.stringify({
1735
+ image_key: "img_dedup_payload",
1736
+ }),
1737
+ },
1738
+ };
1739
+
1740
+ await Promise.all([dispatchMessage({ cfg, event }), dispatchMessage({ cfg, event })]);
1741
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
1742
+ });
1743
+ });
1744
+
1745
+ describe("toMessageResourceType", () => {
1746
+ it("maps image to image", () => {
1747
+ expect(toMessageResourceType("image")).toBe("image");
1748
+ });
1749
+
1750
+ it("maps audio to file", () => {
1751
+ expect(toMessageResourceType("audio")).toBe("file");
1752
+ });
1753
+
1754
+ it("maps video/file/sticker to file", () => {
1755
+ expect(toMessageResourceType("video")).toBe("file");
1756
+ expect(toMessageResourceType("file")).toBe("file");
1757
+ expect(toMessageResourceType("sticker")).toBe("file");
1758
+ });
1759
+ });
1760
+
1761
+ describe("resolveBroadcastAgents", () => {
1762
+ it("returns agent list when broadcast config has the peerId", () => {
1763
+ const cfg = { broadcast: { oc_group123: ["susan", "main"] } } as unknown as ClawdbotConfig;
1764
+ expect(resolveBroadcastAgents(cfg, "oc_group123")).toEqual(["susan", "main"]);
1765
+ });
1766
+
1767
+ it("returns null when no broadcast config", () => {
1768
+ const cfg = {} as ClawdbotConfig;
1769
+ expect(resolveBroadcastAgents(cfg, "oc_group123")).toBeNull();
1770
+ });
1771
+
1772
+ it("returns null when peerId not in broadcast", () => {
1773
+ const cfg = { broadcast: { oc_other: ["susan"] } } as unknown as ClawdbotConfig;
1774
+ expect(resolveBroadcastAgents(cfg, "oc_group123")).toBeNull();
1775
+ });
1776
+
1777
+ it("returns null when agent list is empty", () => {
1778
+ const cfg = { broadcast: { oc_group123: [] } } as unknown as ClawdbotConfig;
1779
+ expect(resolveBroadcastAgents(cfg, "oc_group123")).toBeNull();
1780
+ });
1781
+ });
1782
+
1783
+ describe("buildBroadcastSessionKey", () => {
1784
+ it("replaces agent ID prefix in session key", () => {
1785
+ expect(buildBroadcastSessionKey("agent:main:feishu:group:oc_group123", "main", "susan")).toBe(
1786
+ "agent:susan:feishu:group:oc_group123",
1787
+ );
1788
+ });
1789
+
1790
+ it("handles compound peer IDs", () => {
1791
+ expect(
1792
+ buildBroadcastSessionKey(
1793
+ "agent:main:feishu:group:oc_group123:sender:ou_user1",
1794
+ "main",
1795
+ "susan",
1796
+ ),
1797
+ ).toBe("agent:susan:feishu:group:oc_group123:sender:ou_user1");
1798
+ });
1799
+
1800
+ it("returns base key unchanged when prefix does not match", () => {
1801
+ expect(buildBroadcastSessionKey("custom:key:format", "main", "susan")).toBe(
1802
+ "custom:key:format",
1803
+ );
1804
+ });
1805
+ });
1806
+
1807
+ describe("broadcast dispatch", () => {
1808
+ const mockFinalizeInboundContext = vi.fn((ctx: unknown) => ctx);
1809
+ const mockDispatchReplyFromConfig = vi
1810
+ .fn()
1811
+ .mockResolvedValue({ queuedFinal: false, counts: { final: 1 } });
1812
+ const mockWithReplyDispatcher = vi.fn(
1813
+ async ({
1814
+ dispatcher,
1815
+ run,
1816
+ onSettled,
1817
+ }: Parameters<PluginRuntime["channel"]["reply"]["withReplyDispatcher"]>[0]) => {
1818
+ try {
1819
+ return await run();
1820
+ } finally {
1821
+ dispatcher.markComplete();
1822
+ try {
1823
+ await dispatcher.waitForIdle();
1824
+ } finally {
1825
+ await onSettled?.();
1826
+ }
1827
+ }
1828
+ },
1829
+ );
1830
+ const mockShouldComputeCommandAuthorized = vi.fn(() => false);
1831
+ const mockSaveMediaBuffer = vi.fn().mockResolvedValue({
1832
+ path: "/tmp/inbound-clip.mp4",
1833
+ contentType: "video/mp4",
1834
+ });
1835
+
1836
+ beforeEach(() => {
1837
+ vi.clearAllMocks();
1838
+ mockResolveAgentRoute.mockReturnValue({
1839
+ agentId: "main",
1840
+ channel: "feishu",
1841
+ accountId: "default",
1842
+ sessionKey: "agent:main:feishu:group:oc-broadcast-group",
1843
+ mainSessionKey: "agent:main:main",
1844
+ matchedBy: "default",
1845
+ });
1846
+ mockCreateFeishuClient.mockReturnValue({
1847
+ contact: {
1848
+ user: {
1849
+ get: vi.fn().mockResolvedValue({ data: { user: { name: "Sender" } } }),
1850
+ },
1851
+ },
1852
+ });
1853
+ setFeishuRuntime({
1854
+ system: {
1855
+ enqueueSystemEvent: vi.fn(),
1856
+ },
1857
+ channel: {
1858
+ routing: {
1859
+ resolveAgentRoute: mockResolveAgentRoute,
1860
+ },
1861
+ reply: {
1862
+ resolveEnvelopeFormatOptions: vi.fn(() => ({ template: "channel+name+time" })),
1863
+ formatAgentEnvelope: vi.fn((params: { body: string }) => params.body),
1864
+ finalizeInboundContext: mockFinalizeInboundContext,
1865
+ dispatchReplyFromConfig: mockDispatchReplyFromConfig,
1866
+ withReplyDispatcher: mockWithReplyDispatcher,
1867
+ },
1868
+ commands: {
1869
+ shouldComputeCommandAuthorized: mockShouldComputeCommandAuthorized,
1870
+ resolveCommandAuthorizedFromAuthorizers: vi.fn(() => false),
1871
+ },
1872
+ media: {
1873
+ saveMediaBuffer: mockSaveMediaBuffer,
1874
+ },
1875
+ pairing: {
1876
+ readAllowFromStore: vi.fn().mockResolvedValue([]),
1877
+ upsertPairingRequest: vi.fn().mockResolvedValue({ code: "ABCDEFGH", created: false }),
1878
+ buildPairingReply: vi.fn(() => "Pairing response"),
1879
+ },
1880
+ },
1881
+ media: {
1882
+ detectMime: vi.fn(async () => "application/octet-stream"),
1883
+ },
1884
+ } as unknown as PluginRuntime);
1885
+ });
1886
+
1887
+ it("dispatches to all broadcast agents when bot is mentioned", async () => {
1888
+ const cfg: ClawdbotConfig = {
1889
+ broadcast: { "oc-broadcast-group": ["susan", "main"] },
1890
+ agents: { list: [{ id: "main" }, { id: "susan" }] },
1891
+ channels: {
1892
+ feishu: {
1893
+ groups: {
1894
+ "oc-broadcast-group": {
1895
+ requireMention: true,
1896
+ },
1897
+ },
1898
+ },
1899
+ },
1900
+ } as unknown as ClawdbotConfig;
1901
+
1902
+ const event: FeishuMessageEvent = {
1903
+ sender: { sender_id: { open_id: "ou-sender" } },
1904
+ message: {
1905
+ message_id: "msg-broadcast-mentioned",
1906
+ chat_id: "oc-broadcast-group",
1907
+ chat_type: "group",
1908
+ message_type: "text",
1909
+ content: JSON.stringify({ text: "hello @bot" }),
1910
+ mentions: [
1911
+ { key: "@_user_1", id: { open_id: "bot-open-id" }, name: "Bot", tenant_key: "" },
1912
+ ],
1913
+ },
1914
+ };
1915
+
1916
+ await handleFeishuMessage({
1917
+ cfg,
1918
+ event,
1919
+ botOpenId: "bot-open-id",
1920
+ runtime: createRuntimeEnv(),
1921
+ });
1922
+
1923
+ // Both agents should get dispatched
1924
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(2);
1925
+
1926
+ // Verify session keys for both agents
1927
+ const sessionKeys = mockFinalizeInboundContext.mock.calls.map(
1928
+ (call: unknown[]) => (call[0] as { SessionKey: string }).SessionKey,
1929
+ );
1930
+ expect(sessionKeys).toContain("agent:susan:feishu:group:oc-broadcast-group");
1931
+ expect(sessionKeys).toContain("agent:main:feishu:group:oc-broadcast-group");
1932
+
1933
+ // Active agent (mentioned) gets the real Feishu reply dispatcher
1934
+ expect(mockCreateFeishuReplyDispatcher).toHaveBeenCalledTimes(1);
1935
+ expect(mockCreateFeishuReplyDispatcher).toHaveBeenCalledWith(
1936
+ expect.objectContaining({ agentId: "main" }),
1937
+ );
1938
+ });
1939
+
1940
+ it("skips broadcast dispatch when bot is NOT mentioned (requireMention=true)", async () => {
1941
+ const cfg: ClawdbotConfig = {
1942
+ broadcast: { "oc-broadcast-group": ["susan", "main"] },
1943
+ agents: { list: [{ id: "main" }, { id: "susan" }] },
1944
+ channels: {
1945
+ feishu: {
1946
+ groups: {
1947
+ "oc-broadcast-group": {
1948
+ requireMention: true,
1949
+ },
1950
+ },
1951
+ },
1952
+ },
1953
+ } as unknown as ClawdbotConfig;
1954
+
1955
+ const event: FeishuMessageEvent = {
1956
+ sender: { sender_id: { open_id: "ou-sender" } },
1957
+ message: {
1958
+ message_id: "msg-broadcast-not-mentioned",
1959
+ chat_id: "oc-broadcast-group",
1960
+ chat_type: "group",
1961
+ message_type: "text",
1962
+ content: JSON.stringify({ text: "hello everyone" }),
1963
+ },
1964
+ };
1965
+
1966
+ await handleFeishuMessage({
1967
+ cfg,
1968
+ event,
1969
+ runtime: createRuntimeEnv(),
1970
+ });
1971
+
1972
+ // No dispatch: requireMention=true and bot not mentioned → returns early.
1973
+ // The mentioned bot's handler (on another account or same account with
1974
+ // matching botOpenId) will handle broadcast dispatch for all agents.
1975
+ expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
1976
+ expect(mockCreateFeishuReplyDispatcher).not.toHaveBeenCalled();
1977
+ });
1978
+
1979
+ it("preserves single-agent dispatch when no broadcast config", async () => {
1980
+ const cfg: ClawdbotConfig = {
1981
+ channels: {
1982
+ feishu: {
1983
+ groups: {
1984
+ "oc-broadcast-group": {
1985
+ requireMention: false,
1986
+ },
1987
+ },
1988
+ },
1989
+ },
1990
+ } as ClawdbotConfig;
1991
+
1992
+ const event: FeishuMessageEvent = {
1993
+ sender: { sender_id: { open_id: "ou-sender" } },
1994
+ message: {
1995
+ message_id: "msg-no-broadcast",
1996
+ chat_id: "oc-broadcast-group",
1997
+ chat_type: "group",
1998
+ message_type: "text",
1999
+ content: JSON.stringify({ text: "hello" }),
2000
+ },
2001
+ };
2002
+
2003
+ await handleFeishuMessage({
2004
+ cfg,
2005
+ event,
2006
+ runtime: createRuntimeEnv(),
2007
+ });
2008
+
2009
+ // Single dispatch (no broadcast)
2010
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
2011
+ expect(mockCreateFeishuReplyDispatcher).toHaveBeenCalledTimes(1);
2012
+ expect(mockFinalizeInboundContext).toHaveBeenCalledWith(
2013
+ expect.objectContaining({
2014
+ SessionKey: "agent:main:feishu:group:oc-broadcast-group",
2015
+ }),
2016
+ );
2017
+ });
2018
+
2019
+ it("cross-account broadcast dedup: second account skips dispatch", async () => {
2020
+ const cfg: ClawdbotConfig = {
2021
+ broadcast: { "oc-broadcast-group": ["susan", "main"] },
2022
+ agents: { list: [{ id: "main" }, { id: "susan" }] },
2023
+ channels: {
2024
+ feishu: {
2025
+ groups: {
2026
+ "oc-broadcast-group": {
2027
+ requireMention: false,
2028
+ },
2029
+ },
2030
+ },
2031
+ },
2032
+ } as unknown as ClawdbotConfig;
2033
+
2034
+ const event: FeishuMessageEvent = {
2035
+ sender: { sender_id: { open_id: "ou-sender" } },
2036
+ message: {
2037
+ message_id: "msg-multi-account-dedup",
2038
+ chat_id: "oc-broadcast-group",
2039
+ chat_type: "group",
2040
+ message_type: "text",
2041
+ content: JSON.stringify({ text: "hello" }),
2042
+ },
2043
+ };
2044
+
2045
+ // First account handles broadcast normally
2046
+ await handleFeishuMessage({
2047
+ cfg,
2048
+ event,
2049
+ runtime: createRuntimeEnv(),
2050
+ accountId: "account-A",
2051
+ });
2052
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(2);
2053
+
2054
+ mockDispatchReplyFromConfig.mockClear();
2055
+ mockFinalizeInboundContext.mockClear();
2056
+
2057
+ // Second account: same message ID, different account.
2058
+ // Per-account dedup passes (different namespace), but cross-account
2059
+ // broadcast dedup blocks dispatch.
2060
+ await handleFeishuMessage({
2061
+ cfg,
2062
+ event,
2063
+ runtime: createRuntimeEnv(),
2064
+ accountId: "account-B",
2065
+ });
2066
+ expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
2067
+ });
2068
+
2069
+ it("skips unknown agents not in agents.list", async () => {
2070
+ const cfg: ClawdbotConfig = {
2071
+ broadcast: { "oc-broadcast-group": ["susan", "unknown-agent"] },
2072
+ agents: { list: [{ id: "main" }, { id: "susan" }] },
2073
+ channels: {
2074
+ feishu: {
2075
+ groups: {
2076
+ "oc-broadcast-group": {
2077
+ requireMention: false,
2078
+ },
2079
+ },
2080
+ },
2081
+ },
2082
+ } as unknown as ClawdbotConfig;
2083
+
2084
+ const event: FeishuMessageEvent = {
2085
+ sender: { sender_id: { open_id: "ou-sender" } },
2086
+ message: {
2087
+ message_id: "msg-broadcast-unknown-agent",
2088
+ chat_id: "oc-broadcast-group",
2089
+ chat_type: "group",
2090
+ message_type: "text",
2091
+ content: JSON.stringify({ text: "hello" }),
2092
+ },
2093
+ };
2094
+
2095
+ await handleFeishuMessage({
2096
+ cfg,
2097
+ event,
2098
+ runtime: createRuntimeEnv(),
2099
+ });
2100
+
2101
+ // Only susan should get dispatched (unknown-agent skipped)
2102
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
2103
+ const sessionKey = (mockFinalizeInboundContext.mock.calls[0]?.[0] as { SessionKey: string })
2104
+ .SessionKey;
2105
+ expect(sessionKey).toBe("agent:susan:feishu:group:oc-broadcast-group");
2106
+ });
2107
+ });