@kodelyth/feishu 2026.5.42 → 2026.6.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 (192) hide show
  1. package/klaw.plugin.json +1712 -47
  2. package/package.json +19 -6
  3. package/api.ts +0 -32
  4. package/channel-entry.ts +0 -20
  5. package/channel-plugin-api.ts +0 -1
  6. package/contract-api.ts +0 -16
  7. package/index.ts +0 -82
  8. package/runtime-api.ts +0 -52
  9. package/secret-contract-api.ts +0 -5
  10. package/security-contract-api.ts +0 -1
  11. package/session-key-api.ts +0 -1
  12. package/setup-api.ts +0 -3
  13. package/setup-entry.test.ts +0 -19
  14. package/setup-entry.ts +0 -13
  15. package/src/accounts.test.ts +0 -480
  16. package/src/accounts.ts +0 -333
  17. package/src/agent-config.ts +0 -21
  18. package/src/app-registration.ts +0 -331
  19. package/src/approval-auth.test.ts +0 -24
  20. package/src/approval-auth.ts +0 -25
  21. package/src/async.test.ts +0 -35
  22. package/src/async.ts +0 -104
  23. package/src/audio-preflight.runtime.ts +0 -9
  24. package/src/bitable.test.ts +0 -136
  25. package/src/bitable.ts +0 -762
  26. package/src/bot-content.ts +0 -485
  27. package/src/bot-group-name.test.ts +0 -116
  28. package/src/bot-runtime-api.ts +0 -12
  29. package/src/bot-sender-name.ts +0 -125
  30. package/src/bot.broadcast.test.ts +0 -523
  31. package/src/bot.card-action.test.ts +0 -552
  32. package/src/bot.checkBotMentioned.test.ts +0 -265
  33. package/src/bot.helpers.test.ts +0 -135
  34. package/src/bot.stripBotMention.test.ts +0 -126
  35. package/src/bot.test.ts +0 -3671
  36. package/src/bot.ts +0 -1703
  37. package/src/card-action.ts +0 -447
  38. package/src/card-interaction.test.ts +0 -131
  39. package/src/card-interaction.ts +0 -159
  40. package/src/card-test-helpers.ts +0 -54
  41. package/src/card-ux-approval.ts +0 -65
  42. package/src/card-ux-launcher.test.ts +0 -106
  43. package/src/card-ux-launcher.ts +0 -121
  44. package/src/card-ux-shared.ts +0 -33
  45. package/src/channel-runtime-api.ts +0 -16
  46. package/src/channel.runtime.ts +0 -47
  47. package/src/channel.test.ts +0 -1151
  48. package/src/channel.ts +0 -1423
  49. package/src/chat-schema.ts +0 -25
  50. package/src/chat.test.ts +0 -240
  51. package/src/chat.ts +0 -188
  52. package/src/client-timeout.ts +0 -42
  53. package/src/client.test.ts +0 -447
  54. package/src/client.ts +0 -262
  55. package/src/comment-dispatcher-runtime-api.ts +0 -6
  56. package/src/comment-dispatcher.test.ts +0 -185
  57. package/src/comment-dispatcher.ts +0 -107
  58. package/src/comment-handler-runtime-api.ts +0 -3
  59. package/src/comment-handler.test.ts +0 -592
  60. package/src/comment-handler.ts +0 -303
  61. package/src/comment-reaction.test.ts +0 -138
  62. package/src/comment-reaction.ts +0 -259
  63. package/src/comment-shared.test.ts +0 -183
  64. package/src/comment-shared.ts +0 -406
  65. package/src/comment-target.ts +0 -44
  66. package/src/config-schema.test.ts +0 -326
  67. package/src/config-schema.ts +0 -335
  68. package/src/conversation-id.test.ts +0 -18
  69. package/src/conversation-id.ts +0 -199
  70. package/src/dedup-runtime-api.ts +0 -1
  71. package/src/dedup.ts +0 -141
  72. package/src/dedupe-key.ts +0 -72
  73. package/src/directory.static.ts +0 -61
  74. package/src/directory.test.ts +0 -141
  75. package/src/directory.ts +0 -124
  76. package/src/doc-schema.ts +0 -182
  77. package/src/docx-batch-insert.test.ts +0 -116
  78. package/src/docx-batch-insert.ts +0 -223
  79. package/src/docx-color-text.ts +0 -154
  80. package/src/docx-table-ops.test.ts +0 -53
  81. package/src/docx-table-ops.ts +0 -316
  82. package/src/docx-types.ts +0 -38
  83. package/src/docx.account-selection.test.ts +0 -95
  84. package/src/docx.test.ts +0 -701
  85. package/src/docx.ts +0 -1596
  86. package/src/drive-schema.ts +0 -92
  87. package/src/drive.test.ts +0 -1237
  88. package/src/drive.ts +0 -829
  89. package/src/dynamic-agent.test.ts +0 -155
  90. package/src/dynamic-agent.ts +0 -143
  91. package/src/event-types.ts +0 -45
  92. package/src/external-keys.test.ts +0 -20
  93. package/src/external-keys.ts +0 -19
  94. package/src/lifecycle.test-support.ts +0 -220
  95. package/src/media.test.ts +0 -955
  96. package/src/media.ts +0 -1105
  97. package/src/mention-target.types.ts +0 -5
  98. package/src/mention.ts +0 -114
  99. package/src/message-action-contract.ts +0 -13
  100. package/src/monitor-state-runtime-api.ts +0 -7
  101. package/src/monitor-transport-runtime-api.ts +0 -10
  102. package/src/monitor.account.ts +0 -492
  103. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +0 -219
  104. package/src/monitor.bot-identity.ts +0 -86
  105. package/src/monitor.bot-menu-handler.ts +0 -165
  106. package/src/monitor.bot-menu.lifecycle.test-support.ts +0 -224
  107. package/src/monitor.bot-menu.test.ts +0 -188
  108. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +0 -264
  109. package/src/monitor.card-action.lifecycle.test-support.ts +0 -421
  110. package/src/monitor.cleanup.test.ts +0 -383
  111. package/src/monitor.comment-notice-handler.ts +0 -105
  112. package/src/monitor.comment.test.ts +0 -967
  113. package/src/monitor.comment.ts +0 -1386
  114. package/src/monitor.lifecycle.test.ts +0 -4
  115. package/src/monitor.message-handler.ts +0 -350
  116. package/src/monitor.reaction.lifecycle.test-support.ts +0 -68
  117. package/src/monitor.reaction.test.ts +0 -739
  118. package/src/monitor.startup.test.ts +0 -213
  119. package/src/monitor.startup.ts +0 -74
  120. package/src/monitor.state.defaults.test.ts +0 -46
  121. package/src/monitor.state.ts +0 -170
  122. package/src/monitor.synthetic-error.ts +0 -18
  123. package/src/monitor.test-mocks.ts +0 -46
  124. package/src/monitor.transport.ts +0 -451
  125. package/src/monitor.ts +0 -100
  126. package/src/monitor.webhook-e2e.test.ts +0 -279
  127. package/src/monitor.webhook-security.test.ts +0 -389
  128. package/src/monitor.webhook.test-helpers.ts +0 -116
  129. package/src/outbound-runtime-api.ts +0 -1
  130. package/src/outbound.test.ts +0 -1118
  131. package/src/outbound.ts +0 -785
  132. package/src/perm-schema.ts +0 -52
  133. package/src/perm.ts +0 -170
  134. package/src/pins.ts +0 -108
  135. package/src/policy.test.ts +0 -223
  136. package/src/policy.ts +0 -318
  137. package/src/post.test.ts +0 -105
  138. package/src/post.ts +0 -275
  139. package/src/probe.test.ts +0 -283
  140. package/src/probe.ts +0 -166
  141. package/src/processing-claims.ts +0 -59
  142. package/src/qr-terminal.ts +0 -1
  143. package/src/reactions.ts +0 -123
  144. package/src/reasoning-preview.test.ts +0 -113
  145. package/src/reasoning-preview.ts +0 -28
  146. package/src/reply-dispatcher-runtime-api.ts +0 -7
  147. package/src/reply-dispatcher.test.ts +0 -1513
  148. package/src/reply-dispatcher.ts +0 -748
  149. package/src/runtime.ts +0 -9
  150. package/src/secret-contract.ts +0 -145
  151. package/src/secret-input.ts +0 -1
  152. package/src/security-audit-shared.ts +0 -69
  153. package/src/security-audit.test.ts +0 -59
  154. package/src/security-audit.ts +0 -1
  155. package/src/send-result.ts +0 -80
  156. package/src/send-target.test.ts +0 -86
  157. package/src/send-target.ts +0 -35
  158. package/src/send.reply-fallback.test.ts +0 -417
  159. package/src/send.test.ts +0 -621
  160. package/src/send.ts +0 -861
  161. package/src/sequential-key.test.ts +0 -72
  162. package/src/sequential-key.ts +0 -25
  163. package/src/sequential-queue.test.ts +0 -165
  164. package/src/sequential-queue.ts +0 -86
  165. package/src/session-conversation.ts +0 -42
  166. package/src/session-route.ts +0 -48
  167. package/src/setup-core.ts +0 -51
  168. package/src/setup-surface.test.ts +0 -484
  169. package/src/setup-surface.ts +0 -618
  170. package/src/streaming-card.test.ts +0 -397
  171. package/src/streaming-card.ts +0 -571
  172. package/src/subagent-hooks.test.ts +0 -627
  173. package/src/subagent-hooks.ts +0 -413
  174. package/src/targets.ts +0 -97
  175. package/src/test-support/lifecycle-test-support.ts +0 -454
  176. package/src/thread-bindings.test.ts +0 -180
  177. package/src/thread-bindings.ts +0 -331
  178. package/src/tool-account-routing.test.ts +0 -250
  179. package/src/tool-account.test.ts +0 -44
  180. package/src/tool-account.ts +0 -93
  181. package/src/tool-factory-test-harness.ts +0 -79
  182. package/src/tool-result.test.ts +0 -32
  183. package/src/tool-result.ts +0 -16
  184. package/src/tools-config.test.ts +0 -21
  185. package/src/tools-config.ts +0 -22
  186. package/src/types.ts +0 -106
  187. package/src/typing.test.ts +0 -144
  188. package/src/typing.ts +0 -214
  189. package/src/wiki-schema.ts +0 -69
  190. package/src/wiki.ts +0 -270
  191. package/subagent-hooks-api.ts +0 -31
  192. package/tsconfig.json +0 -16
package/src/bot.test.ts DELETED
@@ -1,3671 +0,0 @@
1
- import type * as ConversationRuntime from "klaw/plugin-sdk/conversation-runtime";
2
- import { createRuntimeEnv } from "klaw/plugin-sdk/plugin-test-runtime";
3
- import type { ResolvedAgentRoute } from "klaw/plugin-sdk/routing";
4
- import { resolveGroupSessionKey } from "klaw/plugin-sdk/session-store-runtime";
5
- import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
6
- import type { ClawdbotConfig, PluginRuntime } from "../runtime-api.js";
7
- import type { FeishuMessageEvent } from "./bot.js";
8
- import { handleFeishuMessage } from "./bot.js";
9
- import { createFeishuMessageReceiveHandler } from "./monitor.message-handler.js";
10
- import { setFeishuRuntime } from "./runtime.js";
11
-
12
- type ConfiguredBindingRoute = ReturnType<typeof ConversationRuntime.resolveConfiguredBindingRoute>;
13
- type BoundConversation = ReturnType<
14
- ReturnType<typeof ConversationRuntime.getSessionBindingService>["resolveByConversation"]
15
- >;
16
- type BindingReadiness = Awaited<
17
- ReturnType<typeof ConversationRuntime.ensureConfiguredBindingRouteReady>
18
- >;
19
- type ReplyDispatcher = Parameters<
20
- PluginRuntime["channel"]["reply"]["withReplyDispatcher"]
21
- >[0]["dispatcher"];
22
- type DeepPartial<T> = {
23
- [K in keyof T]?: T[K] extends (...args: never[]) => unknown
24
- ? T[K]
25
- : T[K] extends ReadonlyArray<unknown>
26
- ? T[K]
27
- : T[K] extends object
28
- ? DeepPartial<T[K]>
29
- : T[K];
30
- };
31
-
32
- function createReplyDispatcher(): ReplyDispatcher {
33
- return {
34
- sendToolResult: vi.fn(),
35
- sendBlockReply: vi.fn(),
36
- sendFinalReply: vi.fn(),
37
- waitForIdle: vi.fn(),
38
- getQueuedCounts: vi.fn(() => ({ tool: 0, block: 0, final: 0 })),
39
- getFailedCounts: vi.fn(() => ({ tool: 0, block: 0, final: 0 })),
40
- markComplete: vi.fn(),
41
- };
42
- }
43
-
44
- function createConfiguredFeishuRoute(): NonNullable<ConfiguredBindingRoute> {
45
- return {
46
- bindingResolution: {
47
- conversation: {
48
- channel: "feishu",
49
- accountId: "default",
50
- conversationId: "ou_sender_1",
51
- },
52
- compiledBinding: {
53
- channel: "feishu",
54
- accountPattern: "default",
55
- binding: {
56
- type: "acp",
57
- agentId: "codex",
58
- match: {
59
- channel: "feishu",
60
- accountId: "default",
61
- peer: { kind: "direct", id: "ou_sender_1" },
62
- },
63
- },
64
- bindingConversationId: "ou_sender_1",
65
- target: {
66
- conversationId: "ou_sender_1",
67
- },
68
- agentId: "codex",
69
- provider: {
70
- compileConfiguredBinding: () => ({ conversationId: "ou_sender_1" }),
71
- matchInboundConversation: () => ({ conversationId: "ou_sender_1" }),
72
- },
73
- targetFactory: {
74
- driverId: "acp",
75
- materialize: () => ({
76
- record: {
77
- bindingId: "config:acp:feishu:default:ou_sender_1",
78
- targetSessionKey: "agent:codex:acp:binding:feishu:default:abc123",
79
- targetKind: "session",
80
- conversation: {
81
- channel: "feishu",
82
- accountId: "default",
83
- conversationId: "ou_sender_1",
84
- },
85
- status: "active",
86
- boundAt: 0,
87
- metadata: { source: "config" },
88
- },
89
- statefulTarget: {
90
- kind: "stateful",
91
- driverId: "acp",
92
- sessionKey: "agent:codex:acp:binding:feishu:default:abc123",
93
- agentId: "codex",
94
- },
95
- }),
96
- },
97
- },
98
- match: {
99
- conversationId: "ou_sender_1",
100
- },
101
- record: {
102
- bindingId: "config:acp:feishu:default:ou_sender_1",
103
- targetSessionKey: "agent:codex:acp:binding:feishu:default:abc123",
104
- targetKind: "session",
105
- conversation: {
106
- channel: "feishu",
107
- accountId: "default",
108
- conversationId: "ou_sender_1",
109
- },
110
- status: "active",
111
- boundAt: 0,
112
- metadata: { source: "config" },
113
- },
114
- statefulTarget: {
115
- kind: "stateful",
116
- driverId: "acp",
117
- sessionKey: "agent:codex:acp:binding:feishu:default:abc123",
118
- agentId: "codex",
119
- },
120
- },
121
- route: {
122
- agentId: "codex",
123
- channel: "feishu",
124
- accountId: "default",
125
- sessionKey: "agent:codex:acp:binding:feishu:default:abc123",
126
- mainSessionKey: "agent:codex:main",
127
- lastRoutePolicy: "session",
128
- matchedBy: "binding.channel",
129
- } as ResolvedAgentRoute,
130
- };
131
- }
132
-
133
- function createConfiguredBindingReadiness(ok: boolean, error?: string): BindingReadiness {
134
- return (ok ? { ok: true } : { ok: false, error: error ?? "unknown error" }) as BindingReadiness;
135
- }
136
-
137
- function createBoundConversation(): NonNullable<BoundConversation> {
138
- return {
139
- bindingId: "default:oc_group_chat:topic:om_topic_root",
140
- targetSessionKey: "agent:codex:acp:binding:feishu:default:feedface",
141
- targetKind: "session",
142
- conversation: {
143
- channel: "feishu",
144
- accountId: "default",
145
- conversationId: "oc_group_chat:topic:om_topic_root",
146
- parentConversationId: "oc_group_chat",
147
- },
148
- status: "active",
149
- boundAt: 0,
150
- };
151
- }
152
-
153
- function buildDefaultResolveRoute(): ResolvedAgentRoute {
154
- return {
155
- agentId: "main",
156
- channel: "feishu",
157
- accountId: "default",
158
- sessionKey: "agent:main:feishu:dm:ou-attacker",
159
- mainSessionKey: "agent:main:main",
160
- lastRoutePolicy: "session",
161
- matchedBy: "default",
162
- };
163
- }
164
-
165
- function createUnboundConfiguredRoute(
166
- route: NonNullable<ConfiguredBindingRoute>["route"],
167
- ): ConfiguredBindingRoute {
168
- return { bindingResolution: null, route };
169
- }
170
-
171
- function createFeishuBotRuntime(overrides: DeepPartial<PluginRuntime> = {}): PluginRuntime {
172
- return {
173
- channel: {
174
- routing: {
175
- resolveAgentRoute: resolveAgentRouteMock,
176
- },
177
- session: {
178
- readSessionUpdatedAt: readSessionUpdatedAtMock,
179
- resolveStorePath: resolveStorePathMock,
180
- recordInboundSession: vi.fn(async () => undefined),
181
- },
182
- reply: {
183
- resolveEnvelopeFormatOptions:
184
- resolveEnvelopeFormatOptionsMock as unknown as PluginRuntime["channel"]["reply"]["resolveEnvelopeFormatOptions"],
185
- formatAgentEnvelope: vi.fn((params: { body: string }) => params.body),
186
- finalizeInboundContext: finalizeInboundContextMock as never,
187
- dispatchReplyFromConfig: vi.fn().mockResolvedValue({
188
- queuedFinal: false,
189
- counts: { final: 1 },
190
- }),
191
- withReplyDispatcher: withReplyDispatcherMock as never,
192
- },
193
- commands: {
194
- shouldComputeCommandAuthorized: vi.fn(() => false),
195
- resolveCommandAuthorizedFromAuthorizers: vi.fn(() => false),
196
- },
197
- pairing: {
198
- readAllowFromStore: vi.fn().mockResolvedValue(["ou_sender_1"]),
199
- upsertPairingRequest: vi.fn(),
200
- buildPairingReply: vi.fn(),
201
- },
202
- turn: {
203
- run: vi.fn(async (params) => {
204
- const input = await params.adapter.ingest(params.raw);
205
- const turn = await params.adapter.resolveTurn(input, {
206
- kind: "message",
207
- canStartAgentTurn: true,
208
- });
209
- await turn.recordInboundSession({
210
- storePath: turn.storePath,
211
- sessionKey: turn.ctxPayload.SessionKey ?? turn.routeSessionKey,
212
- ctx: turn.ctxPayload,
213
- groupResolution: turn.record?.groupResolution,
214
- createIfMissing: turn.record?.createIfMissing,
215
- updateLastRoute: turn.record?.updateLastRoute,
216
- onRecordError: turn.record?.onRecordError ?? (() => undefined),
217
- });
218
- return {
219
- dispatchResult: await turn.runDispatch(),
220
- };
221
- }),
222
- runPrepared: vi.fn(async (params) => ({
223
- dispatchResult: await params.runDispatch(),
224
- })),
225
- },
226
- ...overrides.channel,
227
- },
228
- ...(overrides.system ? { system: overrides.system as PluginRuntime["system"] } : {}),
229
- ...(overrides.media ? { media: overrides.media as PluginRuntime["media"] } : {}),
230
- } as unknown as PluginRuntime;
231
- }
232
-
233
- const resolveAgentRouteMock: PluginRuntime["channel"]["routing"]["resolveAgentRoute"] = (params) =>
234
- mockResolveAgentRoute(params);
235
- const readSessionUpdatedAtMock: PluginRuntime["channel"]["session"]["readSessionUpdatedAt"] = (
236
- params,
237
- ) => mockReadSessionUpdatedAt(params);
238
- const resolveStorePathMock: PluginRuntime["channel"]["session"]["resolveStorePath"] = (params) =>
239
- mockResolveStorePath(params);
240
- const resolveEnvelopeFormatOptionsMock = () => ({});
241
- const finalizeInboundContextMock = (ctx: Record<string, unknown>) => ctx;
242
- const withReplyDispatcherMock = async ({
243
- run,
244
- }: Parameters<PluginRuntime["channel"]["reply"]["withReplyDispatcher"]>[0]) => await run();
245
-
246
- function mockCallArg<T>(
247
- mock: { mock: { calls: unknown[][] } },
248
- callIndex: number,
249
- argIndex: number,
250
- _type?: (value: unknown) => value is T,
251
- ): T {
252
- const call = mock.mock.calls[callIndex];
253
- if (!call) {
254
- throw new Error(`Expected mock call at index ${callIndex}`);
255
- }
256
- return call[argIndex] as T;
257
- }
258
-
259
- function lastMockCallArg<T>(
260
- mock: { mock: { calls: unknown[][] } },
261
- argIndex = 0,
262
- _type?: (value: unknown) => value is T,
263
- ): T | undefined {
264
- return mock.mock.calls.at(-1)?.[argIndex] as T | undefined;
265
- }
266
-
267
- type FeishuRoutePeer = { id: string; kind: "direct" | "group" };
268
-
269
- function expectResolvedRouteCall(
270
- callIndex: number,
271
- peer: FeishuRoutePeer,
272
- parentPeer?: FeishuRoutePeer | null,
273
- ): void {
274
- const routeRequest = mockCallArg<{
275
- parentPeer?: FeishuRoutePeer | null;
276
- peer?: FeishuRoutePeer;
277
- }>(mockResolveAgentRoute, callIndex, 0);
278
- expect(routeRequest.peer).toEqual(peer);
279
- if (arguments.length >= 3) {
280
- expect(routeRequest.parentPeer).toEqual(parentPeer);
281
- }
282
- }
283
-
284
- const {
285
- mockCreateFeishuReplyDispatcher,
286
- mockSendMessageFeishu,
287
- mockGetMessageFeishu,
288
- mockListFeishuThreadMessages,
289
- mockDownloadMessageResourceFeishu,
290
- mockCreateFeishuClient,
291
- mockResolveAgentRoute,
292
- mockReadSessionUpdatedAt,
293
- mockResolveStorePath,
294
- mockResolveConfiguredBindingRoute,
295
- mockEnsureConfiguredBindingRouteReady,
296
- mockResolveBoundConversation,
297
- mockTouchBinding,
298
- mockResolveFeishuReasoningPreviewEnabled,
299
- mockTranscribeFirstAudio,
300
- mockMaybeCreateDynamicAgent,
301
- } = vi.hoisted(() => ({
302
- mockCreateFeishuReplyDispatcher: vi.fn(() => ({
303
- dispatcher: createReplyDispatcher(),
304
- replyOptions: {},
305
- markDispatchIdle: vi.fn(),
306
- })),
307
- mockSendMessageFeishu: vi.fn().mockResolvedValue({ messageId: "pairing-msg", chatId: "oc-dm" }),
308
- mockGetMessageFeishu: vi.fn().mockResolvedValue(null),
309
- mockListFeishuThreadMessages: vi.fn().mockResolvedValue([]),
310
- mockDownloadMessageResourceFeishu: vi.fn().mockResolvedValue({
311
- buffer: Buffer.from("video"),
312
- contentType: "video/mp4",
313
- fileName: "clip.mp4",
314
- }),
315
- mockCreateFeishuClient: vi.fn(),
316
- mockResolveAgentRoute: vi.fn((_params?: unknown) => buildDefaultResolveRoute()),
317
- mockReadSessionUpdatedAt: vi.fn((_params?: unknown): number | undefined => undefined),
318
- mockResolveStorePath: vi.fn((_params?: unknown) => "/tmp/feishu-sessions.json"),
319
- mockResolveConfiguredBindingRoute: vi.fn(
320
- ({
321
- route,
322
- }: {
323
- route: NonNullable<ConfiguredBindingRoute>["route"];
324
- }): ConfiguredBindingRoute => ({
325
- bindingResolution: null,
326
- route,
327
- }),
328
- ),
329
- mockEnsureConfiguredBindingRouteReady: vi.fn(
330
- async (_params?: unknown): Promise<BindingReadiness> => ({ ok: true }),
331
- ),
332
- mockResolveBoundConversation: vi.fn((_ref?: unknown) => null as BoundConversation),
333
- mockTouchBinding: vi.fn(),
334
- mockResolveFeishuReasoningPreviewEnabled: vi.fn(() => false),
335
- mockTranscribeFirstAudio: vi.fn(),
336
- mockMaybeCreateDynamicAgent: vi.fn(),
337
- }));
338
-
339
- vi.mock("./reply-dispatcher.js", () => ({
340
- createFeishuReplyDispatcher: mockCreateFeishuReplyDispatcher,
341
- }));
342
-
343
- vi.mock("./reasoning-preview.js", () => ({
344
- resolveFeishuReasoningPreviewEnabled: mockResolveFeishuReasoningPreviewEnabled,
345
- }));
346
-
347
- vi.mock("./send.js", () => ({
348
- sendMessageFeishu: mockSendMessageFeishu,
349
- getMessageFeishu: mockGetMessageFeishu,
350
- listFeishuThreadMessages: mockListFeishuThreadMessages,
351
- }));
352
-
353
- vi.mock("./media.js", () => ({
354
- downloadMessageResourceFeishu: mockDownloadMessageResourceFeishu,
355
- saveMessageResourceFeishu: mockDownloadMessageResourceFeishu,
356
- }));
357
-
358
- vi.mock("./audio-preflight.runtime.js", () => ({
359
- transcribeFirstAudio: mockTranscribeFirstAudio,
360
- }));
361
-
362
- vi.mock("./client.js", () => ({
363
- createFeishuClient: mockCreateFeishuClient,
364
- }));
365
-
366
- vi.mock("./dynamic-agent.js", () => ({
367
- maybeCreateDynamicAgent: mockMaybeCreateDynamicAgent,
368
- }));
369
-
370
- vi.mock("klaw/plugin-sdk/conversation-runtime", async () => {
371
- const actual = await vi.importActual<typeof import("klaw/plugin-sdk/conversation-runtime")>(
372
- "klaw/plugin-sdk/conversation-runtime",
373
- );
374
- return {
375
- ...actual,
376
- resolveConfiguredBindingRoute: (params: unknown) =>
377
- mockResolveConfiguredBindingRoute(params as { route: ResolvedAgentRoute }),
378
- resolveRuntimeConversationBindingRoute: (params: {
379
- route: ResolvedAgentRoute;
380
- conversation: Parameters<
381
- ReturnType<typeof actual.getSessionBindingService>["resolveByConversation"]
382
- >[0];
383
- }) => {
384
- const bindingRecord = mockResolveBoundConversation(params.conversation);
385
- const boundSessionKey = bindingRecord?.targetSessionKey?.trim();
386
- if (!bindingRecord || !boundSessionKey) {
387
- return { bindingRecord: null, route: params.route };
388
- }
389
- mockTouchBinding(bindingRecord.bindingId);
390
- return {
391
- bindingRecord,
392
- boundSessionKey,
393
- boundAgentId: params.route.agentId,
394
- route: {
395
- ...params.route,
396
- sessionKey: boundSessionKey,
397
- lastRoutePolicy: boundSessionKey === params.route.mainSessionKey ? "main" : "session",
398
- matchedBy: "binding.channel",
399
- },
400
- };
401
- },
402
- ensureConfiguredBindingRouteReady: (params: unknown) =>
403
- mockEnsureConfiguredBindingRouteReady(params),
404
- getSessionBindingService: () => ({
405
- resolveByConversation: mockResolveBoundConversation,
406
- touch: mockTouchBinding,
407
- }),
408
- };
409
- });
410
-
411
- afterAll(() => {
412
- vi.doUnmock("./reply-dispatcher.js");
413
- vi.doUnmock("./reasoning-preview.js");
414
- vi.doUnmock("./send.js");
415
- vi.doUnmock("./media.js");
416
- vi.doUnmock("./audio-preflight.runtime.js");
417
- vi.doUnmock("./client.js");
418
- vi.doUnmock("klaw/plugin-sdk/conversation-runtime");
419
- vi.resetModules();
420
- });
421
-
422
- async function dispatchMessage(params: { cfg: ClawdbotConfig; event: FeishuMessageEvent }) {
423
- const runtime = createRuntimeEnv();
424
- const feishuConfig = params.cfg.channels?.feishu;
425
- const cfg =
426
- feishuConfig?.dmPolicy === "open" && feishuConfig.allowFrom === undefined
427
- ? ({
428
- ...params.cfg,
429
- channels: {
430
- ...params.cfg.channels,
431
- feishu: {
432
- ...feishuConfig,
433
- allowFrom: ["*"],
434
- },
435
- },
436
- } as ClawdbotConfig)
437
- : params.cfg;
438
- await handleFeishuMessage({
439
- cfg,
440
- event: params.event,
441
- runtime,
442
- });
443
- return runtime;
444
- }
445
-
446
- describe("handleFeishuMessage ACP routing", () => {
447
- beforeEach(() => {
448
- vi.clearAllMocks();
449
- mockResolveConfiguredBindingRoute.mockReset().mockImplementation(
450
- ({
451
- route,
452
- }: {
453
- route: NonNullable<ConfiguredBindingRoute>["route"];
454
- }): ConfiguredBindingRoute => ({
455
- bindingResolution: null,
456
- route,
457
- }),
458
- );
459
- mockEnsureConfiguredBindingRouteReady.mockReset().mockResolvedValue({ ok: true });
460
- mockResolveBoundConversation.mockReset().mockReturnValue(null);
461
- mockTouchBinding.mockReset();
462
- mockResolveFeishuReasoningPreviewEnabled.mockReset().mockReturnValue(false);
463
- mockTranscribeFirstAudio.mockReset().mockResolvedValue(undefined);
464
- mockMaybeCreateDynamicAgent.mockReset().mockResolvedValue({ created: false });
465
- mockResolveAgentRoute.mockReset().mockReturnValue({
466
- ...buildDefaultResolveRoute(),
467
- sessionKey: "agent:main:feishu:direct:ou_sender_1",
468
- });
469
- mockSendMessageFeishu
470
- .mockReset()
471
- .mockResolvedValue({ messageId: "reply-msg", chatId: "oc_dm" });
472
- mockCreateFeishuReplyDispatcher.mockReset().mockReturnValue({
473
- dispatcher: createReplyDispatcher(),
474
- replyOptions: {},
475
- markDispatchIdle: vi.fn(),
476
- });
477
-
478
- setFeishuRuntime(createFeishuBotRuntime());
479
- });
480
-
481
- it("ensures configured ACP routes for Feishu DMs", async () => {
482
- mockResolveConfiguredBindingRoute.mockReturnValue(createConfiguredFeishuRoute());
483
-
484
- await dispatchMessage({
485
- cfg: {
486
- session: { mainKey: "main", scope: "per-sender" },
487
- channels: { feishu: { enabled: true, allowFrom: ["ou_sender_1"], dmPolicy: "open" } },
488
- },
489
- event: {
490
- sender: { sender_id: { open_id: "ou_sender_1" } },
491
- message: {
492
- message_id: "msg-1",
493
- chat_id: "oc_dm",
494
- chat_type: "p2p",
495
- message_type: "text",
496
- content: JSON.stringify({ text: "hello" }),
497
- },
498
- },
499
- });
500
-
501
- expect(mockResolveConfiguredBindingRoute).toHaveBeenCalledTimes(1);
502
- expect(mockEnsureConfiguredBindingRouteReady).toHaveBeenCalledTimes(1);
503
- });
504
-
505
- it("surfaces configured ACP initialization failures to the Feishu conversation", async () => {
506
- mockResolveConfiguredBindingRoute.mockReturnValue(createConfiguredFeishuRoute());
507
- mockEnsureConfiguredBindingRouteReady.mockResolvedValue(
508
- createConfiguredBindingReadiness(false, "runtime unavailable"),
509
- );
510
-
511
- await dispatchMessage({
512
- cfg: {
513
- session: { mainKey: "main", scope: "per-sender" },
514
- channels: { feishu: { enabled: true, allowFrom: ["ou_sender_1"], dmPolicy: "open" } },
515
- },
516
- event: {
517
- sender: { sender_id: { open_id: "ou_sender_1" } },
518
- message: {
519
- message_id: "msg-2",
520
- chat_id: "oc_dm",
521
- chat_type: "p2p",
522
- message_type: "text",
523
- content: JSON.stringify({ text: "hello" }),
524
- },
525
- },
526
- });
527
-
528
- const message = mockCallArg<{ text?: string; to?: string }>(mockSendMessageFeishu, 0, 0);
529
- expect(message.to).toBe("chat:oc_dm");
530
- expect(message.text).toContain("runtime unavailable");
531
- });
532
-
533
- it("routes Feishu topic messages through active bound conversations", async () => {
534
- mockResolveBoundConversation.mockReturnValue(createBoundConversation());
535
-
536
- await dispatchMessage({
537
- cfg: {
538
- session: { mainKey: "main", scope: "per-sender" },
539
- channels: {
540
- feishu: {
541
- enabled: true,
542
- allowFrom: ["ou_sender_1"],
543
- groups: {
544
- oc_group_chat: {
545
- allow: true,
546
- requireMention: false,
547
- groupSessionScope: "group_topic",
548
- },
549
- },
550
- },
551
- },
552
- },
553
- event: {
554
- sender: { sender_id: { open_id: "ou_sender_1" } },
555
- message: {
556
- message_id: "msg-3",
557
- chat_id: "oc_group_chat",
558
- chat_type: "group",
559
- message_type: "text",
560
- root_id: "om_topic_root",
561
- content: JSON.stringify({ text: "hello topic" }),
562
- },
563
- },
564
- });
565
-
566
- const conversationRef = mockCallArg<{ channel?: string; conversationId?: string }>(
567
- mockResolveBoundConversation,
568
- 0,
569
- 0,
570
- );
571
- expect(conversationRef.channel).toBe("feishu");
572
- expect(conversationRef.conversationId).toBe("oc_group_chat:topic:om_topic_root");
573
- expect(mockTouchBinding).toHaveBeenCalledWith("default:oc_group_chat:topic:om_topic_root");
574
- });
575
-
576
- it("records Feishu DM last-route updates on the resolved session", async () => {
577
- const runtime = createFeishuBotRuntime();
578
- const recordInboundSession = vi.fn(async () => undefined);
579
- runtime.channel.session.recordInboundSession = recordInboundSession;
580
- mockResolveAgentRoute.mockReturnValue({
581
- agentId: "main",
582
- channel: "feishu",
583
- accountId: "default",
584
- sessionKey: "agent:main:main",
585
- mainSessionKey: "agent:main:main",
586
- lastRoutePolicy: "main",
587
- matchedBy: "default",
588
- });
589
- setFeishuRuntime(runtime);
590
-
591
- await dispatchMessage({
592
- cfg: {
593
- session: { mainKey: "main", scope: "per-sender" },
594
- channels: { feishu: { enabled: true, allowFrom: ["ou_sender_1"], dmPolicy: "open" } },
595
- },
596
- event: {
597
- sender: { sender_id: { open_id: "ou_sender_1" } },
598
- message: {
599
- message_id: "msg-dm-last-route",
600
- chat_id: "oc_dm",
601
- chat_type: "p2p",
602
- message_type: "text",
603
- content: JSON.stringify({ text: "hello" }),
604
- },
605
- },
606
- });
607
-
608
- const recordParams = lastMockCallArg<{
609
- sessionKey?: string;
610
- updateLastRoute?: {
611
- accountId?: string;
612
- channel?: string;
613
- sessionKey?: string;
614
- to?: string;
615
- };
616
- }>(recordInboundSession);
617
- expect(recordParams?.sessionKey).toBe("agent:main:main");
618
- expect(recordParams?.updateLastRoute).toMatchObject({
619
- sessionKey: "agent:main:main",
620
- channel: "feishu",
621
- to: "user:ou_sender_1",
622
- accountId: "default",
623
- });
624
- });
625
-
626
- it("pins shared Feishu DM last-route updates to the configured owner", async () => {
627
- const runtime = createFeishuBotRuntime();
628
- const recordInboundSession = vi.fn(async () => undefined);
629
- runtime.channel.session.recordInboundSession = recordInboundSession;
630
- runtime.channel.pairing.readAllowFromStore = vi.fn().mockResolvedValue(["ou_sender_2"]);
631
- mockResolveAgentRoute.mockReturnValue({
632
- agentId: "main",
633
- channel: "feishu",
634
- accountId: "default",
635
- sessionKey: "agent:main:main",
636
- mainSessionKey: "agent:main:main",
637
- lastRoutePolicy: "main",
638
- matchedBy: "default",
639
- });
640
- setFeishuRuntime(runtime);
641
-
642
- await dispatchMessage({
643
- cfg: {
644
- session: { mainKey: "main", scope: "per-sender" },
645
- channels: { feishu: { enabled: true, allowFrom: ["ou_owner"], dmPolicy: "pairing" } },
646
- },
647
- event: {
648
- sender: { sender_id: { open_id: "ou_sender_2" } },
649
- message: {
650
- message_id: "msg-dm-last-route-secondary",
651
- chat_id: "oc_dm",
652
- chat_type: "p2p",
653
- message_type: "text",
654
- content: JSON.stringify({ text: "hello" }),
655
- },
656
- },
657
- });
658
-
659
- const recordParams = lastMockCallArg<{
660
- updateLastRoute?: {
661
- mainDmOwnerPin?: {
662
- ownerRecipient?: string;
663
- senderRecipient?: string;
664
- onSkip?: unknown;
665
- };
666
- };
667
- }>(recordInboundSession);
668
- expect(recordParams?.updateLastRoute?.mainDmOwnerPin).toMatchObject({
669
- ownerRecipient: "user:ou_owner",
670
- senderRecipient: "user:ou_sender_2",
671
- });
672
- expect(typeof recordParams?.updateLastRoute?.mainDmOwnerPin?.onSkip).toBe("function");
673
- });
674
-
675
- it("matches Feishu DM owner pins against user_id allowlist entries", async () => {
676
- const runtime = createFeishuBotRuntime();
677
- const recordInboundSession = vi.fn(async () => undefined);
678
- runtime.channel.session.recordInboundSession = recordInboundSession;
679
- mockResolveAgentRoute.mockReturnValue({
680
- agentId: "main",
681
- channel: "feishu",
682
- accountId: "default",
683
- sessionKey: "agent:main:main",
684
- mainSessionKey: "agent:main:main",
685
- lastRoutePolicy: "main",
686
- matchedBy: "default",
687
- });
688
- setFeishuRuntime(runtime);
689
-
690
- await dispatchMessage({
691
- cfg: {
692
- session: { mainKey: "main", scope: "per-sender" },
693
- channels: { feishu: { enabled: true, allowFrom: ["user_123"], dmPolicy: "allowlist" } },
694
- },
695
- event: {
696
- sender: { sender_id: { open_id: "ou_owner", user_id: "user_123" } },
697
- message: {
698
- message_id: "msg-dm-last-route-user-id-owner",
699
- chat_id: "oc_dm",
700
- chat_type: "p2p",
701
- message_type: "text",
702
- content: JSON.stringify({ text: "hello" }),
703
- },
704
- },
705
- });
706
-
707
- const recordParams = lastMockCallArg<{
708
- updateLastRoute?: {
709
- mainDmOwnerPin?: {
710
- ownerRecipient?: string;
711
- senderRecipient?: string;
712
- };
713
- };
714
- }>(recordInboundSession);
715
- expect(recordParams?.updateLastRoute?.mainDmOwnerPin).toMatchObject({
716
- ownerRecipient: "user:user_123",
717
- senderRecipient: "user:user_123",
718
- });
719
- });
720
-
721
- it("records Feishu group last-route updates on the resolved session", async () => {
722
- const runtime = createFeishuBotRuntime();
723
- const recordInboundSession = vi.fn(async () => undefined);
724
- runtime.channel.session.recordInboundSession = recordInboundSession;
725
- mockResolveAgentRoute.mockReturnValue({
726
- agentId: "agent-B",
727
- channel: "feishu",
728
- accountId: "default",
729
- sessionKey: "agent:agent-B:feishu:group:oc_group_chat",
730
- mainSessionKey: "agent:agent-B:main",
731
- lastRoutePolicy: "session",
732
- matchedBy: "default",
733
- });
734
- setFeishuRuntime(runtime);
735
-
736
- await dispatchMessage({
737
- cfg: {
738
- session: { mainKey: "main", scope: "per-sender" },
739
- channels: {
740
- feishu: {
741
- enabled: true,
742
- allowFrom: ["ou_sender_1"],
743
- groups: {
744
- oc_group_chat: {
745
- allow: true,
746
- requireMention: false,
747
- },
748
- },
749
- },
750
- },
751
- },
752
- event: {
753
- sender: { sender_id: { open_id: "ou_sender_1" } },
754
- message: {
755
- message_id: "msg-group-last-route",
756
- chat_id: "oc_group_chat",
757
- chat_type: "group",
758
- message_type: "text",
759
- content: JSON.stringify({ text: "hello group" }),
760
- },
761
- },
762
- });
763
-
764
- const recordParams = lastMockCallArg<{
765
- sessionKey?: string;
766
- updateLastRoute?: {
767
- accountId?: string;
768
- channel?: string;
769
- sessionKey?: string;
770
- to?: string;
771
- };
772
- }>(recordInboundSession);
773
- expect(recordParams?.sessionKey).toBe("agent:agent-B:feishu:group:oc_group_chat");
774
- expect(recordParams?.updateLastRoute).toMatchObject({
775
- sessionKey: "agent:agent-B:feishu:group:oc_group_chat",
776
- channel: "feishu",
777
- to: "chat:oc_group_chat",
778
- accountId: "default",
779
- });
780
- });
781
-
782
- it("records configured Feishu thread replies with the dispatcher fallback target", async () => {
783
- const runtime = createFeishuBotRuntime();
784
- const recordInboundSession = vi.fn(async () => undefined);
785
- runtime.channel.session.recordInboundSession = recordInboundSession;
786
- mockResolveAgentRoute.mockReturnValue({
787
- agentId: "agent-B",
788
- channel: "feishu",
789
- accountId: "default",
790
- sessionKey: "agent:agent-B:feishu:group:oc_group_chat",
791
- mainSessionKey: "agent:agent-B:main",
792
- lastRoutePolicy: "session",
793
- matchedBy: "default",
794
- });
795
- setFeishuRuntime(runtime);
796
-
797
- await dispatchMessage({
798
- cfg: {
799
- session: { mainKey: "main", scope: "per-sender" },
800
- channels: {
801
- feishu: {
802
- enabled: true,
803
- allowFrom: ["ou_sender_1"],
804
- groups: {
805
- oc_group_chat: {
806
- allow: true,
807
- requireMention: false,
808
- replyInThread: "enabled",
809
- },
810
- },
811
- },
812
- },
813
- },
814
- event: {
815
- sender: { sender_id: { open_id: "ou_sender_1" } },
816
- message: {
817
- message_id: "msg-group-thread-fallback",
818
- chat_id: "oc_group_chat",
819
- chat_type: "group",
820
- message_type: "text",
821
- content: JSON.stringify({ text: "start a thread" }),
822
- },
823
- },
824
- });
825
-
826
- const recordParams = lastMockCallArg<{
827
- updateLastRoute?: {
828
- threadId?: string;
829
- to?: string;
830
- };
831
- }>(recordInboundSession);
832
- expect(recordParams?.updateLastRoute).toMatchObject({
833
- to: "chat:oc_group_chat",
834
- threadId: "msg-group-thread-fallback",
835
- });
836
- });
837
-
838
- it("records auto-threaded Feishu group replies with the dispatcher target", async () => {
839
- const runtime = createFeishuBotRuntime();
840
- const recordInboundSession = vi.fn(async () => undefined);
841
- runtime.channel.session.recordInboundSession = recordInboundSession;
842
- mockResolveAgentRoute.mockReturnValue({
843
- agentId: "agent-B",
844
- channel: "feishu",
845
- accountId: "default",
846
- sessionKey: "agent:agent-B:feishu:group:oc_group_chat",
847
- mainSessionKey: "agent:agent-B:main",
848
- lastRoutePolicy: "session",
849
- matchedBy: "default",
850
- });
851
- setFeishuRuntime(runtime);
852
-
853
- await dispatchMessage({
854
- cfg: {
855
- session: { mainKey: "main", scope: "per-sender" },
856
- channels: {
857
- feishu: {
858
- enabled: true,
859
- allowFrom: ["ou_sender_1"],
860
- groups: {
861
- oc_group_chat: {
862
- allow: true,
863
- requireMention: false,
864
- },
865
- },
866
- },
867
- },
868
- },
869
- event: {
870
- sender: { sender_id: { open_id: "ou_sender_1" } },
871
- message: {
872
- message_id: "msg-group-auto-thread",
873
- chat_id: "oc_group_chat",
874
- chat_type: "group",
875
- message_type: "text",
876
- root_id: "om_thread_root",
877
- content: JSON.stringify({ text: "continue the thread" }),
878
- },
879
- },
880
- });
881
-
882
- const recordParams = lastMockCallArg<{
883
- updateLastRoute?: {
884
- threadId?: string;
885
- to?: string;
886
- };
887
- }>(recordInboundSession);
888
- expect(recordParams?.updateLastRoute).toMatchObject({
889
- to: "chat:oc_group_chat",
890
- threadId: "msg-group-auto-thread",
891
- });
892
- });
893
-
894
- it("passes reasoning preview permission from session state into the dispatcher", async () => {
895
- mockResolveFeishuReasoningPreviewEnabled.mockReturnValue(true);
896
-
897
- await dispatchMessage({
898
- cfg: {
899
- session: { mainKey: "main", scope: "per-sender" },
900
- channels: { feishu: { enabled: true, allowFrom: ["ou_sender_1"], dmPolicy: "open" } },
901
- },
902
- event: {
903
- sender: { sender_id: { open_id: "ou_sender_1" } },
904
- message: {
905
- message_id: "msg-reasoning",
906
- chat_id: "oc_dm",
907
- chat_type: "p2p",
908
- message_type: "text",
909
- content: JSON.stringify({ text: "hello" }),
910
- },
911
- },
912
- });
913
-
914
- const dispatcherOptions = mockCallArg<{ allowReasoningPreview?: boolean }>(
915
- mockCreateFeishuReplyDispatcher,
916
- 0,
917
- 0,
918
- );
919
- expect(dispatcherOptions.allowReasoningPreview).toBe(true);
920
- });
921
- });
922
-
923
- describe("handleFeishuMessage command authorization", () => {
924
- const mockFinalizeInboundContext = vi.fn((ctx: Record<string, unknown>) => ({
925
- ...ctx,
926
- CommandAuthorized: typeof ctx.CommandAuthorized === "boolean" ? ctx.CommandAuthorized : false,
927
- }));
928
- const mockDispatchReplyFromConfig = vi
929
- .fn()
930
- .mockResolvedValue({ queuedFinal: false, counts: { final: 1 } });
931
- const mockWithReplyDispatcher = vi.fn(
932
- async ({
933
- dispatcher,
934
- run,
935
- onSettled,
936
- }: Parameters<PluginRuntime["channel"]["reply"]["withReplyDispatcher"]>[0]) => {
937
- try {
938
- return await run();
939
- } finally {
940
- dispatcher.markComplete();
941
- try {
942
- await dispatcher.waitForIdle();
943
- } finally {
944
- await onSettled?.();
945
- }
946
- }
947
- },
948
- );
949
- const mockResolveCommandAuthorizedFromAuthorizers = vi.fn(() => false);
950
- const mockShouldComputeCommandAuthorized = vi.fn(() => true);
951
- const mockReadAllowFromStore = vi.fn().mockResolvedValue([]);
952
- const mockUpsertPairingRequest = vi.fn().mockResolvedValue({ code: "ABCDEFGH", created: false });
953
- const mockBuildPairingReply = vi.fn(() => "Pairing response");
954
- const mockEnqueueSystemEvent = vi.fn();
955
- const mockSaveMediaBuffer = vi.fn().mockResolvedValue({
956
- id: "inbound-clip.mp4",
957
- path: "/tmp/inbound-clip.mp4",
958
- size: Buffer.byteLength("video"),
959
- contentType: "video/mp4",
960
- });
961
-
962
- beforeEach(() => {
963
- vi.clearAllMocks();
964
- mockShouldComputeCommandAuthorized.mockReset().mockReturnValue(true);
965
- mockGetMessageFeishu.mockReset().mockResolvedValue(null);
966
- mockListFeishuThreadMessages.mockReset().mockResolvedValue([]);
967
- mockReadSessionUpdatedAt.mockReturnValue(undefined);
968
- mockResolveStorePath.mockReturnValue("/tmp/feishu-sessions.json");
969
- mockResolveConfiguredBindingRoute.mockReset().mockImplementation(
970
- ({
971
- route,
972
- }: {
973
- route: NonNullable<ConfiguredBindingRoute>["route"];
974
- }): ConfiguredBindingRoute => ({
975
- bindingResolution: null,
976
- route,
977
- }),
978
- );
979
- mockEnsureConfiguredBindingRouteReady.mockReset().mockResolvedValue({ ok: true });
980
- mockResolveBoundConversation.mockReset().mockReturnValue(null);
981
- mockTouchBinding.mockReset();
982
- mockTranscribeFirstAudio.mockReset().mockResolvedValue(undefined);
983
- mockMaybeCreateDynamicAgent.mockReset().mockResolvedValue({ created: false });
984
- mockResolveAgentRoute.mockReturnValue(buildDefaultResolveRoute());
985
- mockCreateFeishuClient.mockReturnValue({
986
- contact: {
987
- user: {
988
- get: vi.fn().mockResolvedValue({ data: { user: { name: "Sender" } } }),
989
- },
990
- },
991
- });
992
- mockEnqueueSystemEvent.mockReset();
993
- setFeishuRuntime(
994
- createFeishuBotRuntime({
995
- system: {
996
- enqueueSystemEvent: mockEnqueueSystemEvent,
997
- },
998
- channel: {
999
- reply: {
1000
- resolveEnvelopeFormatOptions:
1001
- resolveEnvelopeFormatOptionsMock as unknown as PluginRuntime["channel"]["reply"]["resolveEnvelopeFormatOptions"],
1002
- formatAgentEnvelope: vi.fn((params: { body: string }) => params.body),
1003
- finalizeInboundContext: mockFinalizeInboundContext as never,
1004
- dispatchReplyFromConfig: mockDispatchReplyFromConfig,
1005
- withReplyDispatcher: mockWithReplyDispatcher as never,
1006
- },
1007
- commands: {
1008
- shouldComputeCommandAuthorized: mockShouldComputeCommandAuthorized,
1009
- resolveCommandAuthorizedFromAuthorizers: mockResolveCommandAuthorizedFromAuthorizers,
1010
- },
1011
- pairing: {
1012
- readAllowFromStore: mockReadAllowFromStore,
1013
- upsertPairingRequest: mockUpsertPairingRequest,
1014
- buildPairingReply: mockBuildPairingReply,
1015
- },
1016
- media: {
1017
- saveMediaBuffer: mockSaveMediaBuffer,
1018
- },
1019
- },
1020
- media: {
1021
- detectMime: vi.fn(async () => "application/octet-stream"),
1022
- },
1023
- }),
1024
- );
1025
- });
1026
-
1027
- it("does not enqueue inbound preview text as system events", async () => {
1028
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1029
-
1030
- const cfg: ClawdbotConfig = {
1031
- channels: {
1032
- feishu: {
1033
- dmPolicy: "open",
1034
- },
1035
- },
1036
- } as ClawdbotConfig;
1037
-
1038
- const event: FeishuMessageEvent = {
1039
- sender: {
1040
- sender_id: {
1041
- open_id: "ou-attacker",
1042
- },
1043
- },
1044
- message: {
1045
- message_id: "msg-no-system-preview",
1046
- chat_id: "oc-dm",
1047
- chat_type: "p2p",
1048
- message_type: "text",
1049
- content: JSON.stringify({ text: "hi there" }),
1050
- },
1051
- };
1052
-
1053
- await dispatchMessage({ cfg, event });
1054
-
1055
- expect(mockEnqueueSystemEvent).not.toHaveBeenCalled();
1056
- });
1057
-
1058
- it("passes disabled config-write policy to dynamic agent creation", async () => {
1059
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1060
-
1061
- const cfg: ClawdbotConfig = {
1062
- channels: {
1063
- feishu: {
1064
- dmPolicy: "open",
1065
- allowFrom: ["*"],
1066
- configWrites: false,
1067
- dynamicAgentCreation: {
1068
- enabled: true,
1069
- },
1070
- },
1071
- },
1072
- } as ClawdbotConfig;
1073
-
1074
- const event: FeishuMessageEvent = {
1075
- sender: {
1076
- sender_id: {
1077
- open_id: "ou-attacker",
1078
- },
1079
- },
1080
- message: {
1081
- message_id: "msg-dynamic-config-writes-disabled",
1082
- chat_id: "oc-dm",
1083
- chat_type: "p2p",
1084
- message_type: "text",
1085
- content: JSON.stringify({ text: "hello" }),
1086
- },
1087
- };
1088
-
1089
- await dispatchMessage({ cfg, event });
1090
-
1091
- const dynamicAgentRequest = mockCallArg<{
1092
- configWritesAllowed?: boolean;
1093
- senderOpenId?: string;
1094
- }>(mockMaybeCreateDynamicAgent, 0, 0);
1095
- expect(dynamicAgentRequest.senderOpenId).toBe("ou-attacker");
1096
- expect(dynamicAgentRequest.configWritesAllowed).toBe(false);
1097
- expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
1098
- });
1099
-
1100
- it("blocks open DMs when a restrictive allowlist does not match", async () => {
1101
- const cfg: ClawdbotConfig = {
1102
- commands: { useAccessGroups: true },
1103
- channels: {
1104
- feishu: {
1105
- dmPolicy: "open",
1106
- allowFrom: ["ou-admin"],
1107
- },
1108
- },
1109
- } as ClawdbotConfig;
1110
-
1111
- const event: FeishuMessageEvent = {
1112
- sender: {
1113
- sender_id: {
1114
- open_id: "ou-attacker",
1115
- },
1116
- },
1117
- message: {
1118
- message_id: "msg-auth-bypass-regression",
1119
- chat_id: "oc-dm",
1120
- chat_type: "p2p",
1121
- message_type: "text",
1122
- content: JSON.stringify({ text: "/status" }),
1123
- },
1124
- };
1125
-
1126
- await dispatchMessage({ cfg, event });
1127
-
1128
- expect(mockResolveCommandAuthorizedFromAuthorizers).not.toHaveBeenCalled();
1129
- expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
1130
- });
1131
-
1132
- it("reads pairing allow store for non-command DMs when dmPolicy is pairing", async () => {
1133
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1134
- mockReadAllowFromStore.mockResolvedValue(["ou-attacker"]);
1135
-
1136
- const cfg: ClawdbotConfig = {
1137
- commands: { useAccessGroups: true },
1138
- channels: {
1139
- feishu: {
1140
- dmPolicy: "pairing",
1141
- allowFrom: [],
1142
- },
1143
- },
1144
- } as ClawdbotConfig;
1145
-
1146
- const event: FeishuMessageEvent = {
1147
- sender: {
1148
- sender_id: {
1149
- open_id: "ou-attacker",
1150
- },
1151
- },
1152
- message: {
1153
- message_id: "msg-read-store-non-command",
1154
- chat_id: "oc-dm",
1155
- chat_type: "p2p",
1156
- message_type: "text",
1157
- content: JSON.stringify({ text: "hello there" }),
1158
- },
1159
- };
1160
-
1161
- await dispatchMessage({ cfg, event });
1162
-
1163
- expect(mockReadAllowFromStore).toHaveBeenCalledWith({
1164
- channel: "feishu",
1165
- accountId: "default",
1166
- });
1167
- expect(mockResolveCommandAuthorizedFromAuthorizers).not.toHaveBeenCalled();
1168
- expect(mockFinalizeInboundContext).toHaveBeenCalledTimes(1);
1169
- expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
1170
- });
1171
-
1172
- it("skips sender-name lookup when resolveSenderNames is false", async () => {
1173
- const cfg: ClawdbotConfig = {
1174
- channels: {
1175
- feishu: {
1176
- dmPolicy: "open",
1177
- allowFrom: ["*"],
1178
- resolveSenderNames: false,
1179
- },
1180
- },
1181
- } as ClawdbotConfig;
1182
-
1183
- const event: FeishuMessageEvent = {
1184
- sender: {
1185
- sender_id: {
1186
- open_id: "ou-attacker",
1187
- },
1188
- },
1189
- message: {
1190
- message_id: "msg-skip-sender-lookup",
1191
- chat_id: "oc-dm",
1192
- chat_type: "p2p",
1193
- message_type: "text",
1194
- content: JSON.stringify({ text: "hello" }),
1195
- },
1196
- };
1197
-
1198
- await dispatchMessage({ cfg, event });
1199
-
1200
- expect(mockCreateFeishuClient).not.toHaveBeenCalled();
1201
- });
1202
-
1203
- it("propagates parent/root message ids into inbound context for reply reconstruction", async () => {
1204
- mockGetMessageFeishu.mockResolvedValueOnce({
1205
- messageId: "om_parent_001",
1206
- chatId: "oc-group",
1207
- content: "quoted content",
1208
- contentType: "text",
1209
- });
1210
-
1211
- const cfg: ClawdbotConfig = {
1212
- channels: {
1213
- feishu: {
1214
- enabled: true,
1215
- dmPolicy: "open",
1216
- },
1217
- },
1218
- } as ClawdbotConfig;
1219
-
1220
- const event: FeishuMessageEvent = {
1221
- sender: {
1222
- sender_id: {
1223
- open_id: "ou-replier",
1224
- },
1225
- },
1226
- message: {
1227
- message_id: "om_reply_001",
1228
- root_id: "om_root_001",
1229
- parent_id: "om_parent_001",
1230
- chat_id: "oc-dm",
1231
- chat_type: "p2p",
1232
- message_type: "text",
1233
- content: JSON.stringify({ text: "reply text" }),
1234
- },
1235
- };
1236
-
1237
- await dispatchMessage({ cfg, event });
1238
-
1239
- const context = mockCallArg<{
1240
- ReplyToBody?: string;
1241
- ReplyToId?: string;
1242
- RootMessageId?: string;
1243
- }>(mockFinalizeInboundContext, 0, 0);
1244
- expect(context.ReplyToId).toBe("om_parent_001");
1245
- expect(context.RootMessageId).toBe("om_root_001");
1246
- expect(context.ReplyToBody).toBe("quoted content");
1247
- });
1248
-
1249
- it("uses message create_time as Timestamp instead of Date.now()", async () => {
1250
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1251
-
1252
- const cfg: ClawdbotConfig = {
1253
- channels: {
1254
- feishu: {
1255
- dmPolicy: "open",
1256
- },
1257
- },
1258
- } as ClawdbotConfig;
1259
-
1260
- const event: FeishuMessageEvent = {
1261
- sender: {
1262
- sender_id: {
1263
- open_id: "ou-attacker",
1264
- },
1265
- },
1266
- message: {
1267
- message_id: "msg-create-time",
1268
- chat_id: "oc-dm",
1269
- chat_type: "p2p",
1270
- message_type: "text",
1271
- content: JSON.stringify({ text: "delete this" }),
1272
- create_time: "1700000000000",
1273
- },
1274
- };
1275
-
1276
- await dispatchMessage({ cfg, event });
1277
-
1278
- const context = mockCallArg<{ Timestamp?: number }>(mockFinalizeInboundContext, 0, 0);
1279
- expect(context.Timestamp).toBe(1700000000000);
1280
- });
1281
-
1282
- it("falls back to Date.now() when create_time is absent", async () => {
1283
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1284
-
1285
- const cfg: ClawdbotConfig = {
1286
- channels: {
1287
- feishu: {
1288
- dmPolicy: "open",
1289
- },
1290
- },
1291
- } as ClawdbotConfig;
1292
-
1293
- const event: FeishuMessageEvent = {
1294
- sender: {
1295
- sender_id: {
1296
- open_id: "ou-attacker",
1297
- },
1298
- },
1299
- message: {
1300
- message_id: "msg-no-create-time",
1301
- chat_id: "oc-dm",
1302
- chat_type: "p2p",
1303
- message_type: "text",
1304
- content: JSON.stringify({ text: "hello" }),
1305
- },
1306
- };
1307
-
1308
- const before = Date.now();
1309
- await dispatchMessage({ cfg, event });
1310
- const after = Date.now();
1311
-
1312
- const call = mockFinalizeInboundContext.mock.calls.at(0)?.[0] as { Timestamp: number };
1313
- expect(call.Timestamp).toBeGreaterThanOrEqual(before);
1314
- expect(call.Timestamp).toBeLessThanOrEqual(after);
1315
- });
1316
-
1317
- it("replies pairing challenge to DM chat_id instead of user:sender id", async () => {
1318
- const cfg: ClawdbotConfig = {
1319
- channels: {
1320
- feishu: {
1321
- dmPolicy: "pairing",
1322
- },
1323
- },
1324
- } as ClawdbotConfig;
1325
-
1326
- const event: FeishuMessageEvent = {
1327
- sender: {
1328
- sender_id: {
1329
- user_id: "u_mobile_only",
1330
- },
1331
- },
1332
- message: {
1333
- message_id: "msg-pairing-chat-reply",
1334
- chat_id: "oc_dm_chat_1",
1335
- chat_type: "p2p",
1336
- message_type: "text",
1337
- content: JSON.stringify({ text: "hello" }),
1338
- },
1339
- };
1340
-
1341
- mockReadAllowFromStore.mockResolvedValue([]);
1342
- mockUpsertPairingRequest.mockResolvedValue({ code: "ABCDEFGH", created: true });
1343
-
1344
- await dispatchMessage({ cfg, event });
1345
-
1346
- const message = mockCallArg<{ to?: string }>(mockSendMessageFeishu, 0, 0);
1347
- expect(message.to).toBe("chat:oc_dm_chat_1");
1348
- });
1349
- it("creates pairing request and drops unauthorized DMs in pairing mode", async () => {
1350
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1351
- mockReadAllowFromStore.mockResolvedValue([]);
1352
- mockUpsertPairingRequest.mockResolvedValue({ code: "ABCDEFGH", created: true });
1353
-
1354
- const cfg: ClawdbotConfig = {
1355
- channels: {
1356
- feishu: {
1357
- dmPolicy: "pairing",
1358
- allowFrom: [],
1359
- },
1360
- },
1361
- } as ClawdbotConfig;
1362
-
1363
- const event: FeishuMessageEvent = {
1364
- sender: {
1365
- sender_id: {
1366
- open_id: "ou-unapproved",
1367
- },
1368
- },
1369
- message: {
1370
- message_id: "msg-pairing-flow",
1371
- chat_id: "oc-dm",
1372
- chat_type: "p2p",
1373
- message_type: "text",
1374
- content: JSON.stringify({ text: "hello" }),
1375
- },
1376
- };
1377
-
1378
- await dispatchMessage({ cfg, event });
1379
-
1380
- expect(mockUpsertPairingRequest).toHaveBeenCalledWith({
1381
- channel: "feishu",
1382
- accountId: "default",
1383
- id: "ou-unapproved",
1384
- meta: { name: undefined },
1385
- });
1386
- expect(mockSendMessageFeishu).toHaveBeenCalledTimes(1);
1387
- const pairingMessage = mockCallArg<{ accountId?: string; text?: string; to?: string }>(
1388
- mockSendMessageFeishu,
1389
- 0,
1390
- 0,
1391
- );
1392
- expect(pairingMessage.to).toBe("chat:oc-dm");
1393
- expect(pairingMessage.text).toContain("Your Feishu user id: ou-unapproved");
1394
- expect(pairingMessage.text).toContain("Pairing code:");
1395
- expect(pairingMessage.text).toContain("ABCDEFGH");
1396
- expect(pairingMessage.accountId).toBe("default");
1397
- expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
1398
- expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
1399
- });
1400
-
1401
- it("computes group command authorization from group allowFrom", async () => {
1402
- mockShouldComputeCommandAuthorized.mockReturnValue(true);
1403
- mockResolveCommandAuthorizedFromAuthorizers.mockReturnValue(false);
1404
-
1405
- const cfg: ClawdbotConfig = {
1406
- commands: { useAccessGroups: true },
1407
- channels: {
1408
- feishu: {
1409
- groups: {
1410
- "oc-group": {
1411
- requireMention: false,
1412
- },
1413
- },
1414
- },
1415
- },
1416
- } as ClawdbotConfig;
1417
-
1418
- const event: FeishuMessageEvent = {
1419
- sender: {
1420
- sender_id: {
1421
- open_id: "ou-attacker",
1422
- },
1423
- },
1424
- message: {
1425
- message_id: "msg-group-command-auth",
1426
- chat_id: "oc-group",
1427
- chat_type: "group",
1428
- message_type: "text",
1429
- content: JSON.stringify({ text: "/status" }),
1430
- },
1431
- };
1432
-
1433
- await dispatchMessage({ cfg, event });
1434
-
1435
- expect(mockResolveCommandAuthorizedFromAuthorizers).not.toHaveBeenCalled();
1436
- const context = mockCallArg<{
1437
- ChatType?: string;
1438
- CommandAuthorized?: boolean;
1439
- SenderId?: string;
1440
- }>(mockFinalizeInboundContext, 0, 0);
1441
- expect(context.ChatType).toBe("group");
1442
- expect(context.CommandAuthorized).toBe(false);
1443
- expect(context.SenderId).toBe("ou-attacker");
1444
- });
1445
-
1446
- it("normalizes group mention-prefixed slash commands before command-auth probing", async () => {
1447
- mockShouldComputeCommandAuthorized.mockReturnValue(true);
1448
-
1449
- const cfg: ClawdbotConfig = {
1450
- channels: {
1451
- feishu: {
1452
- groups: {
1453
- "oc-group": {
1454
- requireMention: false,
1455
- },
1456
- },
1457
- },
1458
- },
1459
- } as ClawdbotConfig;
1460
-
1461
- const event: FeishuMessageEvent = {
1462
- sender: {
1463
- sender_id: {
1464
- open_id: "ou-attacker",
1465
- },
1466
- },
1467
- message: {
1468
- message_id: "msg-group-mention-command-probe",
1469
- chat_id: "oc-group",
1470
- chat_type: "group",
1471
- message_type: "text",
1472
- content: JSON.stringify({ text: "@_user_1/model" }),
1473
- mentions: [{ key: "@_user_1", id: { open_id: "ou-bot" }, name: "Bot", tenant_key: "" }],
1474
- },
1475
- };
1476
-
1477
- await dispatchMessage({ cfg, event });
1478
-
1479
- expect(mockShouldComputeCommandAuthorized).toHaveBeenCalledWith("/model", cfg);
1480
- });
1481
-
1482
- it("falls back to top-level allowFrom for group command authorization", async () => {
1483
- mockShouldComputeCommandAuthorized.mockReturnValue(true);
1484
- mockResolveCommandAuthorizedFromAuthorizers.mockReturnValue(true);
1485
-
1486
- const cfg: ClawdbotConfig = {
1487
- commands: { useAccessGroups: true },
1488
- channels: {
1489
- feishu: {
1490
- allowFrom: ["ou-admin"],
1491
- groups: {
1492
- "oc-group": {
1493
- requireMention: false,
1494
- },
1495
- },
1496
- },
1497
- },
1498
- } as ClawdbotConfig;
1499
-
1500
- const event: FeishuMessageEvent = {
1501
- sender: {
1502
- sender_id: {
1503
- open_id: "ou-admin",
1504
- },
1505
- },
1506
- message: {
1507
- message_id: "msg-group-command-fallback",
1508
- chat_id: "oc-group",
1509
- chat_type: "group",
1510
- message_type: "text",
1511
- content: JSON.stringify({ text: "/status" }),
1512
- },
1513
- };
1514
-
1515
- await dispatchMessage({ cfg, event });
1516
-
1517
- expect(mockResolveCommandAuthorizedFromAuthorizers).not.toHaveBeenCalled();
1518
- const context = mockCallArg<{
1519
- ChatType?: string;
1520
- CommandAuthorized?: boolean;
1521
- SenderId?: string;
1522
- }>(mockFinalizeInboundContext, 0, 0);
1523
- expect(context.ChatType).toBe("group");
1524
- expect(context.CommandAuthorized).toBe(true);
1525
- expect(context.SenderId).toBe("ou-admin");
1526
- });
1527
-
1528
- it("allows group sender when global groupSenderAllowFrom includes sender", async () => {
1529
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1530
-
1531
- const cfg: ClawdbotConfig = {
1532
- channels: {
1533
- feishu: {
1534
- groupPolicy: "open",
1535
- groupSenderAllowFrom: ["ou-allowed"],
1536
- groups: {
1537
- "oc-group": {
1538
- requireMention: false,
1539
- },
1540
- },
1541
- },
1542
- },
1543
- } as ClawdbotConfig;
1544
-
1545
- const event: FeishuMessageEvent = {
1546
- sender: {
1547
- sender_id: {
1548
- open_id: "ou-allowed",
1549
- },
1550
- },
1551
- message: {
1552
- message_id: "msg-global-group-sender-allow",
1553
- chat_id: "oc-group",
1554
- chat_type: "group",
1555
- message_type: "text",
1556
- content: JSON.stringify({ text: "hello" }),
1557
- },
1558
- };
1559
-
1560
- await dispatchMessage({ cfg, event });
1561
-
1562
- const context = mockCallArg<{ ChatType?: string; SenderId?: string }>(
1563
- mockFinalizeInboundContext,
1564
- 0,
1565
- 0,
1566
- );
1567
- expect(context.ChatType).toBe("group");
1568
- expect(context.SenderId).toBe("ou-allowed");
1569
- expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
1570
- });
1571
-
1572
- it("keeps Feishu group policy bound to the chat while preserving speaker identity", async () => {
1573
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1574
-
1575
- const cfg: ClawdbotConfig = {
1576
- channels: {
1577
- feishu: {
1578
- groupPolicy: "open",
1579
- groupSenderAllowFrom: ["ou-allowed"],
1580
- groups: {
1581
- "oc-group": {
1582
- requireMention: false,
1583
- },
1584
- },
1585
- },
1586
- },
1587
- } as ClawdbotConfig;
1588
-
1589
- const event: FeishuMessageEvent = {
1590
- sender: {
1591
- sender_id: {
1592
- open_id: "ou-allowed",
1593
- },
1594
- },
1595
- message: {
1596
- message_id: "msg-group-context-79457",
1597
- chat_id: "oc-group",
1598
- chat_type: "group",
1599
- message_type: "text",
1600
- content: JSON.stringify({ text: "hello" }),
1601
- },
1602
- };
1603
-
1604
- await dispatchMessage({ cfg, event });
1605
-
1606
- const finalized = mockCallArg<{
1607
- ChatType?: string;
1608
- From?: string;
1609
- OriginatingChannel?: string;
1610
- OriginatingTo?: string;
1611
- SenderId?: string;
1612
- To?: string;
1613
- }>(mockFinalizeInboundContext, 0, 0);
1614
- expect(finalized.ChatType).toBe("group");
1615
- expect(finalized.From).toBe("feishu:ou-allowed");
1616
- expect(finalized.To).toBe("chat:oc-group");
1617
- expect(finalized.OriginatingChannel).toBe("feishu");
1618
- expect(finalized.OriginatingTo).toBe("chat:oc-group");
1619
- expect(finalized.SenderId).toBe("ou-allowed");
1620
- const groupSessionKey = resolveGroupSessionKey(finalized as never);
1621
- if (!groupSessionKey) {
1622
- throw new Error("Expected group session key");
1623
- }
1624
- expect(groupSessionKey.channel).toBe("feishu");
1625
- expect(groupSessionKey.id).toBe("oc-group");
1626
- expect(groupSessionKey.key).toBe("feishu:group:oc-group");
1627
- expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
1628
- });
1629
-
1630
- it("blocks group sender when global groupSenderAllowFrom excludes sender", async () => {
1631
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1632
-
1633
- const cfg: ClawdbotConfig = {
1634
- channels: {
1635
- feishu: {
1636
- groupPolicy: "open",
1637
- groupSenderAllowFrom: ["ou-allowed"],
1638
- groups: {
1639
- "oc-group": {
1640
- requireMention: false,
1641
- },
1642
- },
1643
- },
1644
- },
1645
- } as ClawdbotConfig;
1646
-
1647
- const event: FeishuMessageEvent = {
1648
- sender: {
1649
- sender_id: {
1650
- open_id: "ou-blocked",
1651
- },
1652
- },
1653
- message: {
1654
- message_id: "msg-global-group-sender-block",
1655
- chat_id: "oc-group",
1656
- chat_type: "group",
1657
- message_type: "text",
1658
- content: JSON.stringify({ text: "hello" }),
1659
- },
1660
- };
1661
-
1662
- await dispatchMessage({ cfg, event });
1663
-
1664
- expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
1665
- expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
1666
- });
1667
-
1668
- it("prefers per-group allowFrom over global groupSenderAllowFrom", async () => {
1669
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1670
-
1671
- const cfg: ClawdbotConfig = {
1672
- channels: {
1673
- feishu: {
1674
- groupPolicy: "open",
1675
- groupSenderAllowFrom: ["ou-global"],
1676
- groups: {
1677
- "oc-group": {
1678
- allowFrom: ["ou-group-only"],
1679
- requireMention: false,
1680
- },
1681
- },
1682
- },
1683
- },
1684
- } as ClawdbotConfig;
1685
-
1686
- const event: FeishuMessageEvent = {
1687
- sender: {
1688
- sender_id: {
1689
- open_id: "ou-global",
1690
- },
1691
- },
1692
- message: {
1693
- message_id: "msg-per-group-precedence",
1694
- chat_id: "oc-group",
1695
- chat_type: "group",
1696
- message_type: "text",
1697
- content: JSON.stringify({ text: "hello" }),
1698
- },
1699
- };
1700
-
1701
- await dispatchMessage({ cfg, event });
1702
-
1703
- expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
1704
- expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
1705
- });
1706
-
1707
- it("drops quoted group context from senders outside the group sender allowlist in allowlist mode", async () => {
1708
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1709
- mockGetMessageFeishu.mockResolvedValueOnce({
1710
- messageId: "om_parent_blocked",
1711
- chatId: "oc-group",
1712
- senderId: "ou-blocked",
1713
- senderType: "user",
1714
- content: "blocked quoted content",
1715
- contentType: "text",
1716
- });
1717
-
1718
- const cfg: ClawdbotConfig = {
1719
- channels: {
1720
- feishu: {
1721
- groupPolicy: "open",
1722
- groupSenderAllowFrom: ["ou-allowed"],
1723
- contextVisibility: "allowlist",
1724
- groups: {
1725
- "oc-group": {
1726
- requireMention: false,
1727
- },
1728
- },
1729
- },
1730
- },
1731
- } as ClawdbotConfig;
1732
-
1733
- const event: FeishuMessageEvent = {
1734
- sender: {
1735
- sender_id: {
1736
- open_id: "ou-allowed",
1737
- },
1738
- },
1739
- message: {
1740
- message_id: "msg-group-quoted-filter",
1741
- parent_id: "om_parent_blocked",
1742
- chat_id: "oc-group",
1743
- chat_type: "group",
1744
- message_type: "text",
1745
- content: JSON.stringify({ text: "hello" }),
1746
- },
1747
- };
1748
-
1749
- await dispatchMessage({ cfg, event });
1750
-
1751
- const context = mockCallArg<{ ReplyToBody?: string; ReplyToId?: string }>(
1752
- mockFinalizeInboundContext,
1753
- 0,
1754
- 0,
1755
- );
1756
- expect(context.ReplyToId).toBe("om_parent_blocked");
1757
- expect(context.ReplyToBody).toBeUndefined();
1758
- });
1759
-
1760
- it("keeps quoted group context from non-allowlisted senders in default all mode", async () => {
1761
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1762
- mockGetMessageFeishu.mockResolvedValueOnce({
1763
- messageId: "om_parent_visible",
1764
- chatId: "oc-group",
1765
- senderId: "ou-blocked",
1766
- senderType: "user",
1767
- content: "visible quoted content",
1768
- contentType: "text",
1769
- });
1770
-
1771
- const cfg: ClawdbotConfig = {
1772
- channels: {
1773
- feishu: {
1774
- groupPolicy: "open",
1775
- groupSenderAllowFrom: ["ou-allowed"],
1776
- groups: {
1777
- "oc-group": {
1778
- requireMention: false,
1779
- },
1780
- },
1781
- },
1782
- },
1783
- } as ClawdbotConfig;
1784
-
1785
- const event: FeishuMessageEvent = {
1786
- sender: {
1787
- sender_id: {
1788
- open_id: "ou-allowed",
1789
- },
1790
- },
1791
- message: {
1792
- message_id: "msg-group-quoted-visible",
1793
- parent_id: "om_parent_visible",
1794
- chat_id: "oc-group",
1795
- chat_type: "group",
1796
- message_type: "text",
1797
- content: JSON.stringify({ text: "hello" }),
1798
- },
1799
- };
1800
-
1801
- await dispatchMessage({ cfg, event });
1802
-
1803
- const context = mockCallArg<{ ReplyToBody?: string; ReplyToId?: string }>(
1804
- mockFinalizeInboundContext,
1805
- 0,
1806
- 0,
1807
- );
1808
- expect(context.ReplyToId).toBe("om_parent_visible");
1809
- expect(context.ReplyToBody).toBe("visible quoted content");
1810
- });
1811
-
1812
- it("dispatches group image message when groupPolicy is open (requireMention defaults to false)", async () => {
1813
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1814
-
1815
- const cfg: ClawdbotConfig = {
1816
- channels: {
1817
- feishu: {
1818
- groupPolicy: "open",
1819
- // requireMention is NOT set — should default to false for open policy
1820
- },
1821
- },
1822
- } as ClawdbotConfig;
1823
-
1824
- const event: FeishuMessageEvent = {
1825
- sender: {
1826
- sender_id: { open_id: "ou-sender" },
1827
- },
1828
- message: {
1829
- message_id: "msg-group-image-open",
1830
- chat_id: "oc-group-open",
1831
- chat_type: "group",
1832
- message_type: "image",
1833
- content: JSON.stringify({ image_key: "img_v3_test" }),
1834
- },
1835
- };
1836
-
1837
- await dispatchMessage({ cfg, event });
1838
-
1839
- expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
1840
- });
1841
-
1842
- it("drops group image message when groupPolicy is open but requireMention is explicitly true", async () => {
1843
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1844
-
1845
- const cfg: ClawdbotConfig = {
1846
- channels: {
1847
- feishu: {
1848
- groupPolicy: "open",
1849
- requireMention: true, // explicit override — user opts into mention-required even for open
1850
- },
1851
- },
1852
- } as ClawdbotConfig;
1853
-
1854
- const event: FeishuMessageEvent = {
1855
- sender: {
1856
- sender_id: { open_id: "ou-sender" },
1857
- },
1858
- message: {
1859
- message_id: "msg-group-image-open-explicit-mention",
1860
- chat_id: "oc-group-open",
1861
- chat_type: "group",
1862
- message_type: "image",
1863
- content: JSON.stringify({ image_key: "img_v3_test" }),
1864
- },
1865
- };
1866
-
1867
- await dispatchMessage({ cfg, event });
1868
-
1869
- expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
1870
- expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
1871
- });
1872
-
1873
- it("drops group image message when groupPolicy is allowlist and requireMention is not set (defaults to true)", async () => {
1874
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1875
-
1876
- const cfg: ClawdbotConfig = {
1877
- channels: {
1878
- feishu: {
1879
- groupPolicy: "allowlist",
1880
- // requireMention not set — for non-open policy defaults to true
1881
- groups: {
1882
- "oc-allowlist-group": {
1883
- allow: true,
1884
- },
1885
- },
1886
- },
1887
- },
1888
- } as ClawdbotConfig;
1889
-
1890
- const event: FeishuMessageEvent = {
1891
- sender: {
1892
- sender_id: { open_id: "ou-sender" },
1893
- },
1894
- message: {
1895
- message_id: "msg-group-image-allowlist",
1896
- chat_id: "oc-allowlist-group",
1897
- chat_type: "group",
1898
- message_type: "image",
1899
- content: JSON.stringify({ image_key: "img_v3_test" }),
1900
- },
1901
- };
1902
-
1903
- await dispatchMessage({ cfg, event });
1904
-
1905
- expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
1906
- expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
1907
- });
1908
-
1909
- it("admits group when chat_id is explicitly configured under groups, even with empty groupAllowFrom (#67687)", async () => {
1910
- // Regression for #67687: a group that only sets `groups.<chat_id>.requireMention=false`
1911
- // (and leaves `groupAllowFrom` empty) should still be admitted under the schema-default
1912
- // `groupPolicy="allowlist"`. The group's explicit presence in `channels.feishu.groups`
1913
- // is the operator's allowlist signal, and the per-group `requireMention` override should
1914
- // then control mention gating for inbound text events.
1915
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
1916
-
1917
- const cfg: ClawdbotConfig = {
1918
- channels: {
1919
- feishu: {
1920
- groupPolicy: "allowlist",
1921
- // groupAllowFrom intentionally omitted -> empty []
1922
- groups: {
1923
- "oc-explicit-group": {
1924
- requireMention: false,
1925
- },
1926
- },
1927
- },
1928
- },
1929
- } as ClawdbotConfig;
1930
-
1931
- const event: FeishuMessageEvent = {
1932
- sender: {
1933
- sender_id: { open_id: "ou-sender" },
1934
- },
1935
- message: {
1936
- message_id: "msg-explicit-group-67687",
1937
- chat_id: "oc-explicit-group",
1938
- chat_type: "group",
1939
- message_type: "text",
1940
- content: JSON.stringify({ text: "hello bot" }),
1941
- },
1942
- };
1943
-
1944
- await dispatchMessage({ cfg, event });
1945
-
1946
- // Group must be admitted: the inbound finalize/dispatch path runs.
1947
- expect(mockFinalizeInboundContext).toHaveBeenCalled();
1948
- expect(mockDispatchReplyFromConfig).toHaveBeenCalled();
1949
- });
1950
-
1951
- it("does not let explicit group config override disabled group policy", async () => {
1952
- const cfg: ClawdbotConfig = {
1953
- channels: {
1954
- feishu: {
1955
- groupPolicy: "disabled",
1956
- groups: {
1957
- "oc-disabled-policy-group": {
1958
- requireMention: false,
1959
- },
1960
- },
1961
- },
1962
- },
1963
- } as ClawdbotConfig;
1964
-
1965
- const event: FeishuMessageEvent = {
1966
- sender: {
1967
- sender_id: { open_id: "ou-sender" },
1968
- },
1969
- message: {
1970
- message_id: "msg-disabled-policy-group",
1971
- chat_id: "oc-disabled-policy-group",
1972
- chat_type: "group",
1973
- message_type: "text",
1974
- content: JSON.stringify({ text: "hello bot" }),
1975
- },
1976
- };
1977
-
1978
- await dispatchMessage({ cfg, event });
1979
-
1980
- expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
1981
- expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
1982
- });
1983
-
1984
- it("does not treat wildcard group defaults as allowlist admission", async () => {
1985
- const cfg: ClawdbotConfig = {
1986
- channels: {
1987
- feishu: {
1988
- groupPolicy: "allowlist",
1989
- groups: {
1990
- "*": {
1991
- requireMention: false,
1992
- },
1993
- },
1994
- },
1995
- },
1996
- } as ClawdbotConfig;
1997
-
1998
- const event: FeishuMessageEvent = {
1999
- sender: {
2000
- sender_id: { open_id: "ou-sender" },
2001
- },
2002
- message: {
2003
- message_id: "msg-wildcard-group-default",
2004
- chat_id: "oc-wildcard-only",
2005
- chat_type: "group",
2006
- message_type: "text",
2007
- content: JSON.stringify({ text: "hello bot" }),
2008
- },
2009
- };
2010
-
2011
- await dispatchMessage({ cfg, event });
2012
-
2013
- expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
2014
- expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
2015
- });
2016
-
2017
- it("drops message when groupConfig.enabled is false", async () => {
2018
- const cfg: ClawdbotConfig = {
2019
- channels: {
2020
- feishu: {
2021
- groups: {
2022
- "oc-disabled-group": {
2023
- enabled: false,
2024
- },
2025
- },
2026
- },
2027
- },
2028
- } as ClawdbotConfig;
2029
-
2030
- const event: FeishuMessageEvent = {
2031
- sender: {
2032
- sender_id: { open_id: "ou-sender" },
2033
- },
2034
- message: {
2035
- message_id: "msg-disabled-group",
2036
- chat_id: "oc-disabled-group",
2037
- chat_type: "group",
2038
- message_type: "text",
2039
- content: JSON.stringify({ text: "hello" }),
2040
- },
2041
- };
2042
-
2043
- await dispatchMessage({ cfg, event });
2044
-
2045
- expect(mockFinalizeInboundContext).not.toHaveBeenCalled();
2046
- expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
2047
- });
2048
-
2049
- it("transcribes inbound audio before building the agent turn", async () => {
2050
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2051
- mockDownloadMessageResourceFeishu.mockResolvedValueOnce({
2052
- buffer: Buffer.from("voice"),
2053
- contentType: "audio/ogg",
2054
- fileName: "voice.ogg",
2055
- });
2056
- mockSaveMediaBuffer.mockResolvedValueOnce({
2057
- id: "inbound-voice.ogg",
2058
- path: "/tmp/inbound-voice.ogg",
2059
- size: Buffer.byteLength("voice"),
2060
- contentType: "audio/ogg",
2061
- });
2062
- mockTranscribeFirstAudio.mockResolvedValueOnce("voice transcript");
2063
-
2064
- const cfg: ClawdbotConfig = {
2065
- channels: {
2066
- feishu: {
2067
- dmPolicy: "open",
2068
- },
2069
- },
2070
- } as ClawdbotConfig;
2071
-
2072
- const event: FeishuMessageEvent = {
2073
- sender: {
2074
- sender_id: {
2075
- open_id: "ou-voice",
2076
- },
2077
- },
2078
- message: {
2079
- message_id: "msg-audio-inbound",
2080
- chat_id: "oc-dm",
2081
- chat_type: "p2p",
2082
- message_type: "audio",
2083
- content: JSON.stringify({
2084
- file_key: "file_audio_payload",
2085
- duration: 1200,
2086
- }),
2087
- },
2088
- };
2089
-
2090
- await dispatchMessage({ cfg, event });
2091
-
2092
- const downloadRequest = mockCallArg<{ fileKey?: string; messageId?: string; type?: string }>(
2093
- mockDownloadMessageResourceFeishu,
2094
- 0,
2095
- 0,
2096
- );
2097
- expect(downloadRequest.messageId).toBe("msg-audio-inbound");
2098
- expect(downloadRequest.fileKey).toBe("file_audio_payload");
2099
- expect(downloadRequest.type).toBe("file");
2100
- const transcribeRequest = mockCallArg<{
2101
- cfg?: { channels?: { feishu?: { dmPolicy?: string } } };
2102
- ctx?: { ChatType?: string; MediaPaths?: string[]; MediaTypes?: string[] };
2103
- }>(mockTranscribeFirstAudio, 0, 0);
2104
- expect(transcribeRequest.ctx?.MediaPaths).toEqual(["/tmp/inbound-voice.ogg"]);
2105
- expect(transcribeRequest.ctx?.MediaTypes).toEqual(["audio/ogg"]);
2106
- expect(transcribeRequest.ctx?.ChatType).toBe("direct");
2107
- expect(transcribeRequest.cfg?.channels?.feishu?.dmPolicy).toBe("open");
2108
- const finalized = mockCallArg<{
2109
- BodyForAgent?: string;
2110
- CommandBody?: string;
2111
- MediaPaths?: string[];
2112
- MediaTranscribedIndexes?: number[];
2113
- MediaTypes?: string[];
2114
- RawBody?: string;
2115
- Transcript?: string;
2116
- }>(mockFinalizeInboundContext, 0, 0);
2117
- expect(finalized.BodyForAgent).toBe(
2118
- "[message_id: msg-audio-inbound]\nou-voice: voice transcript",
2119
- );
2120
- expect(finalized.RawBody).toBe("voice transcript");
2121
- expect(finalized.CommandBody).toBe("voice transcript");
2122
- expect(finalized.Transcript).toBe("voice transcript");
2123
- expect(finalized.MediaPaths).toEqual(["/tmp/inbound-voice.ogg"]);
2124
- expect(finalized.MediaTypes).toEqual(["audio/ogg"]);
2125
- expect(finalized.MediaTranscribedIndexes).toEqual([0]);
2126
- expect(finalized.BodyForAgent).not.toContain("file_audio_payload");
2127
- });
2128
-
2129
- it("uses video file_key (not thumbnail image_key) for inbound video download", async () => {
2130
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2131
-
2132
- const cfg: ClawdbotConfig = {
2133
- channels: {
2134
- feishu: {
2135
- dmPolicy: "open",
2136
- },
2137
- },
2138
- } as ClawdbotConfig;
2139
-
2140
- const event: FeishuMessageEvent = {
2141
- sender: {
2142
- sender_id: {
2143
- open_id: "ou-sender",
2144
- },
2145
- },
2146
- message: {
2147
- message_id: "msg-video-inbound",
2148
- chat_id: "oc-dm",
2149
- chat_type: "p2p",
2150
- message_type: "video",
2151
- content: JSON.stringify({
2152
- file_key: "file_video_payload",
2153
- image_key: "img_thumb_payload",
2154
- file_name: "clip.mp4",
2155
- }),
2156
- },
2157
- };
2158
-
2159
- await dispatchMessage({ cfg, event });
2160
-
2161
- const videoDownloadRequest = mockCallArg<{
2162
- fileKey?: string;
2163
- messageId?: string;
2164
- type?: string;
2165
- }>(mockDownloadMessageResourceFeishu, 0, 0);
2166
- expect(videoDownloadRequest.messageId).toBe("msg-video-inbound");
2167
- expect(videoDownloadRequest.fileKey).toBe("file_video_payload");
2168
- expect(videoDownloadRequest.type).toBe("file");
2169
- const mediaBuffer = mockCallArg<Buffer>(mockSaveMediaBuffer, 0, 0);
2170
- expect(Buffer.isBuffer(mediaBuffer)).toBe(true);
2171
- expect(mediaBuffer.toString()).toBe("video");
2172
- expect(mockCallArg(mockSaveMediaBuffer, 0, 1)).toBe("video/mp4");
2173
- expect(mockCallArg(mockSaveMediaBuffer, 0, 2)).toBe("inbound");
2174
- expect(typeof mockCallArg(mockSaveMediaBuffer, 0, 3)).toBe("number");
2175
- expect(mockCallArg(mockSaveMediaBuffer, 0, 4)).toBe("clip.mp4");
2176
- });
2177
-
2178
- it("uses media message_type file_key (not thumbnail image_key) for inbound mobile video download", async () => {
2179
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2180
-
2181
- const cfg: ClawdbotConfig = {
2182
- channels: {
2183
- feishu: {
2184
- dmPolicy: "open",
2185
- },
2186
- },
2187
- } as ClawdbotConfig;
2188
-
2189
- const event: FeishuMessageEvent = {
2190
- sender: {
2191
- sender_id: {
2192
- open_id: "ou-sender",
2193
- },
2194
- },
2195
- message: {
2196
- message_id: "msg-media-inbound",
2197
- chat_id: "oc-dm",
2198
- chat_type: "p2p",
2199
- message_type: "media",
2200
- content: JSON.stringify({
2201
- file_key: "file_media_payload",
2202
- image_key: "img_media_thumb",
2203
- file_name: "mobile.mp4",
2204
- }),
2205
- },
2206
- };
2207
-
2208
- await dispatchMessage({ cfg, event });
2209
-
2210
- const mediaDownloadRequest = mockCallArg<{
2211
- fileKey?: string;
2212
- messageId?: string;
2213
- type?: string;
2214
- }>(mockDownloadMessageResourceFeishu, 0, 0);
2215
- expect(mediaDownloadRequest.messageId).toBe("msg-media-inbound");
2216
- expect(mediaDownloadRequest.fileKey).toBe("file_media_payload");
2217
- expect(mediaDownloadRequest.type).toBe("file");
2218
- const mediaBuffer = mockCallArg<Buffer>(mockSaveMediaBuffer, 0, 0);
2219
- expect(Buffer.isBuffer(mediaBuffer)).toBe(true);
2220
- expect(mediaBuffer.toString()).toBe("video");
2221
- expect(mockCallArg(mockSaveMediaBuffer, 0, 1)).toBe("video/mp4");
2222
- expect(mockCallArg(mockSaveMediaBuffer, 0, 2)).toBe("inbound");
2223
- expect(typeof mockCallArg(mockSaveMediaBuffer, 0, 3)).toBe("number");
2224
- expect(mockCallArg(mockSaveMediaBuffer, 0, 4)).toBe("clip.mp4");
2225
- });
2226
-
2227
- it("falls back to the message payload filename when download metadata omits it", async () => {
2228
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2229
- mockDownloadMessageResourceFeishu.mockResolvedValueOnce({
2230
- buffer: Buffer.from("video"),
2231
- contentType: "video/mp4",
2232
- });
2233
-
2234
- const cfg: ClawdbotConfig = {
2235
- channels: {
2236
- feishu: {
2237
- dmPolicy: "open",
2238
- },
2239
- },
2240
- } as ClawdbotConfig;
2241
-
2242
- const event: FeishuMessageEvent = {
2243
- sender: {
2244
- sender_id: {
2245
- open_id: "ou-sender",
2246
- },
2247
- },
2248
- message: {
2249
- message_id: "msg-media-payload-name",
2250
- chat_id: "oc-dm",
2251
- chat_type: "p2p",
2252
- message_type: "media",
2253
- content: JSON.stringify({
2254
- file_key: "file_media_payload",
2255
- image_key: "img_media_thumb",
2256
- file_name: "payload-name.mp4",
2257
- }),
2258
- },
2259
- };
2260
-
2261
- await dispatchMessage({ cfg, event });
2262
-
2263
- const mediaBuffer = mockCallArg<Buffer>(mockSaveMediaBuffer, 0, 0);
2264
- expect(Buffer.isBuffer(mediaBuffer)).toBe(true);
2265
- expect(mediaBuffer.toString()).toBe("video");
2266
- expect(mockCallArg(mockSaveMediaBuffer, 0, 1)).toBe("video/mp4");
2267
- expect(mockCallArg(mockSaveMediaBuffer, 0, 2)).toBe("inbound");
2268
- expect(typeof mockCallArg(mockSaveMediaBuffer, 0, 3)).toBe("number");
2269
- expect(mockCallArg(mockSaveMediaBuffer, 0, 4)).toBe("payload-name.mp4");
2270
- });
2271
-
2272
- it("downloads embedded media tags from post messages as files", async () => {
2273
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2274
-
2275
- const cfg: ClawdbotConfig = {
2276
- channels: {
2277
- feishu: {
2278
- dmPolicy: "open",
2279
- },
2280
- },
2281
- } as ClawdbotConfig;
2282
-
2283
- const event: FeishuMessageEvent = {
2284
- sender: {
2285
- sender_id: {
2286
- open_id: "ou-sender",
2287
- },
2288
- },
2289
- message: {
2290
- message_id: "msg-post-media",
2291
- chat_id: "oc-dm",
2292
- chat_type: "p2p",
2293
- message_type: "post",
2294
- content: JSON.stringify({
2295
- title: "Rich text",
2296
- content: [
2297
- [
2298
- {
2299
- tag: "media",
2300
- file_key: "file_post_media_payload",
2301
- file_name: "embedded.mov",
2302
- },
2303
- ],
2304
- ],
2305
- }),
2306
- },
2307
- };
2308
-
2309
- await dispatchMessage({ cfg, event });
2310
-
2311
- const downloadRequest = mockCallArg<{ fileKey?: string; messageId?: string; type?: string }>(
2312
- mockDownloadMessageResourceFeishu,
2313
- 0,
2314
- 0,
2315
- );
2316
- expect(downloadRequest.messageId).toBe("msg-post-media");
2317
- expect(downloadRequest.fileKey).toBe("file_post_media_payload");
2318
- expect(downloadRequest.type).toBe("file");
2319
- const postMediaBuffer = mockCallArg<Buffer>(mockSaveMediaBuffer, 0, 0);
2320
- expect(Buffer.isBuffer(postMediaBuffer)).toBe(true);
2321
- expect(postMediaBuffer.toString()).toBe("video");
2322
- expect(mockCallArg(mockSaveMediaBuffer, 0, 1)).toBe("video/mp4");
2323
- expect(mockCallArg(mockSaveMediaBuffer, 0, 2)).toBe("inbound");
2324
- expect(typeof mockCallArg(mockSaveMediaBuffer, 0, 3)).toBe("number");
2325
- });
2326
-
2327
- it("includes message_id in BodyForAgent on its own line", async () => {
2328
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2329
-
2330
- const cfg: ClawdbotConfig = {
2331
- channels: {
2332
- feishu: {
2333
- dmPolicy: "open",
2334
- },
2335
- },
2336
- } as ClawdbotConfig;
2337
-
2338
- const event: FeishuMessageEvent = {
2339
- sender: {
2340
- sender_id: {
2341
- open_id: "ou-msgid",
2342
- },
2343
- },
2344
- message: {
2345
- message_id: "msg-message-id-line",
2346
- chat_id: "oc-dm",
2347
- chat_type: "p2p",
2348
- message_type: "text",
2349
- content: JSON.stringify({ text: "hello" }),
2350
- },
2351
- };
2352
-
2353
- await dispatchMessage({ cfg, event });
2354
-
2355
- const context = mockCallArg<{ BodyForAgent?: string }>(mockFinalizeInboundContext, 0, 0);
2356
- expect(context.BodyForAgent).toBe("[message_id: msg-message-id-line]\nou-msgid: hello");
2357
- });
2358
-
2359
- it("expands merge_forward content from API sub-messages", async () => {
2360
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2361
- const mockGetMerged = vi.fn().mockResolvedValue({
2362
- code: 0,
2363
- data: {
2364
- items: [
2365
- {
2366
- message_id: "container",
2367
- msg_type: "merge_forward",
2368
- body: { content: JSON.stringify({ text: "Merged and Forwarded Message" }) },
2369
- },
2370
- {
2371
- message_id: "sub-2",
2372
- upper_message_id: "container",
2373
- msg_type: "file",
2374
- body: { content: JSON.stringify({ file_name: "report.pdf" }) },
2375
- create_time: "2000",
2376
- },
2377
- {
2378
- message_id: "sub-1",
2379
- upper_message_id: "container",
2380
- msg_type: "text",
2381
- body: { content: JSON.stringify({ text: "alpha" }) },
2382
- create_time: "1000",
2383
- },
2384
- ],
2385
- },
2386
- });
2387
- mockCreateFeishuClient.mockReturnValue({
2388
- contact: {
2389
- user: {
2390
- get: vi.fn().mockResolvedValue({ data: { user: { name: "Sender" } } }),
2391
- },
2392
- },
2393
- im: {
2394
- message: {
2395
- get: mockGetMerged,
2396
- },
2397
- },
2398
- } as unknown as PluginRuntime);
2399
-
2400
- const cfg: ClawdbotConfig = {
2401
- channels: {
2402
- feishu: {
2403
- dmPolicy: "open",
2404
- },
2405
- },
2406
- } as ClawdbotConfig;
2407
-
2408
- const event: FeishuMessageEvent = {
2409
- sender: {
2410
- sender_id: {
2411
- open_id: "ou-merge",
2412
- },
2413
- },
2414
- message: {
2415
- message_id: "msg-merge-forward",
2416
- chat_id: "oc-dm",
2417
- chat_type: "p2p",
2418
- message_type: "merge_forward",
2419
- content: JSON.stringify({ text: "Merged and Forwarded Message" }),
2420
- },
2421
- };
2422
-
2423
- await dispatchMessage({ cfg, event });
2424
-
2425
- expect(mockGetMerged).toHaveBeenCalledWith({
2426
- path: { message_id: "msg-merge-forward" },
2427
- });
2428
- const context = mockCallArg<{ BodyForAgent?: string }>(mockFinalizeInboundContext, 0, 0);
2429
- expect(context.BodyForAgent).toContain(
2430
- "[Merged and Forwarded Messages]\n- alpha\n- [File: report.pdf]",
2431
- );
2432
- });
2433
-
2434
- it("falls back when merge_forward API returns no sub-messages", async () => {
2435
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2436
- mockCreateFeishuClient.mockReturnValue({
2437
- contact: {
2438
- user: {
2439
- get: vi.fn().mockResolvedValue({ data: { user: { name: "Sender" } } }),
2440
- },
2441
- },
2442
- im: {
2443
- message: {
2444
- get: vi.fn().mockResolvedValue({ code: 0, data: { items: [] } }),
2445
- },
2446
- },
2447
- });
2448
-
2449
- const cfg: ClawdbotConfig = {
2450
- channels: {
2451
- feishu: {
2452
- dmPolicy: "open",
2453
- },
2454
- },
2455
- } as ClawdbotConfig;
2456
-
2457
- const event: FeishuMessageEvent = {
2458
- sender: {
2459
- sender_id: {
2460
- open_id: "ou-merge-empty",
2461
- },
2462
- },
2463
- message: {
2464
- message_id: "msg-merge-empty",
2465
- chat_id: "oc-dm",
2466
- chat_type: "p2p",
2467
- message_type: "merge_forward",
2468
- content: JSON.stringify({ text: "Merged and Forwarded Message" }),
2469
- },
2470
- };
2471
-
2472
- await dispatchMessage({ cfg, event });
2473
-
2474
- const context = mockCallArg<{ BodyForAgent?: string }>(mockFinalizeInboundContext, 0, 0);
2475
- expect(context.BodyForAgent).toContain("[Merged and Forwarded Message - could not fetch]");
2476
- });
2477
-
2478
- it("dispatches once and appends permission notice to the main agent body", async () => {
2479
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2480
- mockCreateFeishuClient.mockReturnValue({
2481
- contact: {
2482
- user: {
2483
- get: vi.fn().mockRejectedValue({
2484
- response: {
2485
- data: {
2486
- code: 99991672,
2487
- msg: "permission denied https://open.feishu.cn/app/cli_test",
2488
- },
2489
- },
2490
- }),
2491
- },
2492
- },
2493
- });
2494
-
2495
- const cfg: ClawdbotConfig = {
2496
- channels: {
2497
- feishu: {
2498
- appId: "cli_test",
2499
- appSecret: "sec_test", // pragma: allowlist secret
2500
- groups: {
2501
- "oc-group": {
2502
- requireMention: false,
2503
- },
2504
- },
2505
- },
2506
- },
2507
- } as ClawdbotConfig;
2508
-
2509
- const event: FeishuMessageEvent = {
2510
- sender: {
2511
- sender_id: {
2512
- open_id: "ou-perm",
2513
- },
2514
- },
2515
- message: {
2516
- message_id: "msg-perm-1",
2517
- chat_id: "oc-group",
2518
- chat_type: "group",
2519
- message_type: "text",
2520
- content: JSON.stringify({ text: "hello group" }),
2521
- },
2522
- };
2523
-
2524
- await dispatchMessage({ cfg, event });
2525
-
2526
- expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
2527
- const context = mockCallArg<{ BodyForAgent?: string }>(mockFinalizeInboundContext, 0, 0);
2528
- expect(context.BodyForAgent).toContain(
2529
- "Permission grant URL: https://open.feishu.cn/app/cli_test",
2530
- );
2531
- expect(context.BodyForAgent).toContain("ou-perm: hello group");
2532
- });
2533
-
2534
- it("ignores stale non-existent contact scope permission errors", async () => {
2535
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2536
- mockCreateFeishuClient.mockReturnValue({
2537
- contact: {
2538
- user: {
2539
- get: vi.fn().mockRejectedValue({
2540
- response: {
2541
- data: {
2542
- code: 99991672,
2543
- msg: "permission denied: contact:contact.base:readonly https://open.feishu.cn/app/cli_scope_bug",
2544
- },
2545
- },
2546
- }),
2547
- },
2548
- },
2549
- });
2550
-
2551
- const cfg: ClawdbotConfig = {
2552
- channels: {
2553
- feishu: {
2554
- appId: "cli_scope_bug",
2555
- appSecret: "sec_scope_bug", // pragma: allowlist secret
2556
- groups: {
2557
- "oc-group": {
2558
- requireMention: false,
2559
- },
2560
- },
2561
- },
2562
- },
2563
- } as ClawdbotConfig;
2564
-
2565
- const event: FeishuMessageEvent = {
2566
- sender: {
2567
- sender_id: {
2568
- open_id: "ou-perm-scope",
2569
- },
2570
- },
2571
- message: {
2572
- message_id: "msg-perm-scope-1",
2573
- chat_id: "oc-group",
2574
- chat_type: "group",
2575
- message_type: "text",
2576
- content: JSON.stringify({ text: "hello group" }),
2577
- },
2578
- };
2579
-
2580
- await dispatchMessage({ cfg, event });
2581
-
2582
- expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
2583
- const context = mockCallArg<{ BodyForAgent?: string }>(mockFinalizeInboundContext, 0, 0);
2584
- expect(context.BodyForAgent).not.toContain("Permission grant URL");
2585
- expect(context.BodyForAgent).toContain("ou-perm-scope: hello group");
2586
- });
2587
-
2588
- it("routes group sessions by sender when groupSessionScope=group_sender", async () => {
2589
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2590
-
2591
- const cfg: ClawdbotConfig = {
2592
- channels: {
2593
- feishu: {
2594
- groups: {
2595
- "oc-group": {
2596
- requireMention: false,
2597
- groupSessionScope: "group_sender",
2598
- },
2599
- },
2600
- },
2601
- },
2602
- } as ClawdbotConfig;
2603
-
2604
- const event: FeishuMessageEvent = {
2605
- sender: { sender_id: { open_id: "ou-scope-user" } },
2606
- message: {
2607
- message_id: "msg-scope-group-sender",
2608
- chat_id: "oc-group",
2609
- chat_type: "group",
2610
- message_type: "text",
2611
- content: JSON.stringify({ text: "group sender scope" }),
2612
- },
2613
- };
2614
-
2615
- await dispatchMessage({ cfg, event });
2616
-
2617
- const routeRequest = mockCallArg<{
2618
- parentPeer?: unknown;
2619
- peer?: { id?: string; kind?: string };
2620
- }>(mockResolveAgentRoute, 0, 0);
2621
- expect(routeRequest.peer).toEqual({ kind: "group", id: "oc-group:sender:ou-scope-user" });
2622
- expect(routeRequest.parentPeer).toBeNull();
2623
- });
2624
-
2625
- it("routes topic sessions and parentPeer when groupSessionScope=group_topic_sender", async () => {
2626
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2627
-
2628
- const cfg: ClawdbotConfig = {
2629
- channels: {
2630
- feishu: {
2631
- groups: {
2632
- "oc-group": {
2633
- requireMention: false,
2634
- groupSessionScope: "group_topic_sender",
2635
- },
2636
- },
2637
- },
2638
- },
2639
- } as ClawdbotConfig;
2640
-
2641
- const event: FeishuMessageEvent = {
2642
- sender: { sender_id: { open_id: "ou-topic-user" } },
2643
- message: {
2644
- message_id: "msg-scope-topic-sender",
2645
- chat_id: "oc-group",
2646
- chat_type: "group",
2647
- root_id: "om_root_topic",
2648
- message_type: "text",
2649
- content: JSON.stringify({ text: "topic sender scope" }),
2650
- },
2651
- };
2652
-
2653
- await dispatchMessage({ cfg, event });
2654
-
2655
- const routeRequest = mockCallArg<{
2656
- parentPeer?: { id?: string; kind?: string };
2657
- peer?: { id?: string; kind?: string };
2658
- }>(mockResolveAgentRoute, 0, 0);
2659
- expect(routeRequest.peer).toEqual({
2660
- kind: "group",
2661
- id: "oc-group:topic:om_root_topic:sender:ou-topic-user",
2662
- });
2663
- expect(routeRequest.parentPeer).toEqual({ kind: "group", id: "oc-group" });
2664
- });
2665
-
2666
- it("keeps root_id as topic key when root_id and thread_id both exist", async () => {
2667
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2668
-
2669
- const cfg: ClawdbotConfig = {
2670
- channels: {
2671
- feishu: {
2672
- groups: {
2673
- "oc-group": {
2674
- requireMention: false,
2675
- groupSessionScope: "group_topic_sender",
2676
- },
2677
- },
2678
- },
2679
- },
2680
- } as ClawdbotConfig;
2681
-
2682
- const event: FeishuMessageEvent = {
2683
- sender: { sender_id: { open_id: "ou-topic-user" } },
2684
- message: {
2685
- message_id: "msg-scope-topic-thread-id",
2686
- chat_id: "oc-group",
2687
- chat_type: "group",
2688
- root_id: "om_root_topic",
2689
- thread_id: "omt_topic_1",
2690
- message_type: "text",
2691
- content: JSON.stringify({ text: "topic sender scope" }),
2692
- },
2693
- };
2694
-
2695
- await dispatchMessage({ cfg, event });
2696
-
2697
- const routeRequest = mockCallArg<{
2698
- parentPeer?: { id?: string; kind?: string };
2699
- peer?: { id?: string; kind?: string };
2700
- }>(mockResolveAgentRoute, 0, 0);
2701
- expect(routeRequest.peer).toEqual({
2702
- kind: "group",
2703
- id: "oc-group:topic:om_root_topic:sender:ou-topic-user",
2704
- });
2705
- expect(routeRequest.parentPeer).toEqual({ kind: "group", id: "oc-group" });
2706
- });
2707
-
2708
- it("uses thread_id as the canonical topic key in Feishu topic groups", async () => {
2709
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2710
-
2711
- const cfg: ClawdbotConfig = {
2712
- channels: {
2713
- feishu: {
2714
- groups: {
2715
- "oc-group": {
2716
- requireMention: false,
2717
- groupSessionScope: "group_topic",
2718
- },
2719
- },
2720
- },
2721
- },
2722
- } as ClawdbotConfig;
2723
-
2724
- const topicStarter: FeishuMessageEvent = {
2725
- sender: { sender_id: { open_id: "ou-topic-user" } },
2726
- message: {
2727
- message_id: "om_topic_starter_message",
2728
- chat_id: "oc-group",
2729
- chat_type: "topic_group",
2730
- root_id: "omt_topic_1",
2731
- message_type: "text",
2732
- content: JSON.stringify({ text: "topic starter" }),
2733
- },
2734
- };
2735
- const topicReply: FeishuMessageEvent = {
2736
- sender: { sender_id: { open_id: "ou-topic-user" } },
2737
- message: {
2738
- message_id: "om_topic_reply_message",
2739
- chat_id: "oc-group",
2740
- chat_type: "topic_group",
2741
- root_id: "om_topic_starter_message",
2742
- thread_id: "omt_topic_1",
2743
- message_type: "text",
2744
- content: JSON.stringify({ text: "topic reply" }),
2745
- },
2746
- };
2747
-
2748
- await dispatchMessage({ cfg, event: topicStarter });
2749
- await dispatchMessage({ cfg, event: topicReply });
2750
-
2751
- const starterRouteRequest = mockCallArg<{
2752
- parentPeer?: { id?: string; kind?: string };
2753
- peer?: { id?: string; kind?: string };
2754
- }>(mockResolveAgentRoute, 0, 0);
2755
- expect(starterRouteRequest.peer).toEqual({ kind: "group", id: "oc-group:topic:omt_topic_1" });
2756
- expect(starterRouteRequest.parentPeer).toEqual({ kind: "group", id: "oc-group" });
2757
- const replyRouteRequest = mockCallArg<{
2758
- parentPeer?: { id?: string; kind?: string };
2759
- peer?: { id?: string; kind?: string };
2760
- }>(mockResolveAgentRoute, 1, 0);
2761
- expect(replyRouteRequest.peer).toEqual({ kind: "group", id: "oc-group:topic:omt_topic_1" });
2762
- expect(replyRouteRequest.parentPeer).toEqual({ kind: "group", id: "oc-group" });
2763
- });
2764
-
2765
- it("uses thread_id as topic key when root_id is missing", async () => {
2766
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2767
-
2768
- const cfg: ClawdbotConfig = {
2769
- channels: {
2770
- feishu: {
2771
- groups: {
2772
- "oc-group": {
2773
- requireMention: false,
2774
- groupSessionScope: "group_topic_sender",
2775
- },
2776
- },
2777
- },
2778
- },
2779
- } as ClawdbotConfig;
2780
-
2781
- const event: FeishuMessageEvent = {
2782
- sender: { sender_id: { open_id: "ou-topic-user" } },
2783
- message: {
2784
- message_id: "msg-scope-topic-thread-only",
2785
- chat_id: "oc-group",
2786
- chat_type: "group",
2787
- thread_id: "omt_topic_1",
2788
- message_type: "text",
2789
- content: JSON.stringify({ text: "topic sender scope" }),
2790
- },
2791
- };
2792
-
2793
- await dispatchMessage({ cfg, event });
2794
-
2795
- expectResolvedRouteCall(
2796
- 0,
2797
- { kind: "group", id: "oc-group:topic:omt_topic_1:sender:ou-topic-user" },
2798
- { kind: "group", id: "oc-group" },
2799
- );
2800
- });
2801
-
2802
- it("maps legacy topicSessionMode=enabled to group_topic routing", async () => {
2803
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2804
-
2805
- const cfg: ClawdbotConfig = {
2806
- channels: {
2807
- feishu: {
2808
- topicSessionMode: "enabled",
2809
- groups: {
2810
- "oc-group": {
2811
- requireMention: false,
2812
- },
2813
- },
2814
- },
2815
- },
2816
- } as ClawdbotConfig;
2817
-
2818
- const event: FeishuMessageEvent = {
2819
- sender: { sender_id: { open_id: "ou-legacy" } },
2820
- message: {
2821
- message_id: "msg-legacy-topic-mode",
2822
- chat_id: "oc-group",
2823
- chat_type: "group",
2824
- root_id: "om_root_legacy",
2825
- message_type: "text",
2826
- content: JSON.stringify({ text: "legacy topic mode" }),
2827
- },
2828
- };
2829
-
2830
- await dispatchMessage({ cfg, event });
2831
-
2832
- expectResolvedRouteCall(
2833
- 0,
2834
- { kind: "group", id: "oc-group:topic:om_root_legacy" },
2835
- { kind: "group", id: "oc-group" },
2836
- );
2837
- });
2838
-
2839
- it("maps legacy topicSessionMode=enabled to root_id when both root_id and thread_id exist", async () => {
2840
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2841
-
2842
- const cfg: ClawdbotConfig = {
2843
- channels: {
2844
- feishu: {
2845
- topicSessionMode: "enabled",
2846
- groups: {
2847
- "oc-group": {
2848
- requireMention: false,
2849
- },
2850
- },
2851
- },
2852
- },
2853
- } as ClawdbotConfig;
2854
-
2855
- const event: FeishuMessageEvent = {
2856
- sender: { sender_id: { open_id: "ou-legacy-thread-id" } },
2857
- message: {
2858
- message_id: "msg-legacy-topic-thread-id",
2859
- chat_id: "oc-group",
2860
- chat_type: "group",
2861
- root_id: "om_root_legacy",
2862
- thread_id: "omt_topic_legacy",
2863
- message_type: "text",
2864
- content: JSON.stringify({ text: "legacy topic mode" }),
2865
- },
2866
- };
2867
-
2868
- await dispatchMessage({ cfg, event });
2869
-
2870
- expectResolvedRouteCall(
2871
- 0,
2872
- { kind: "group", id: "oc-group:topic:om_root_legacy" },
2873
- { kind: "group", id: "oc-group" },
2874
- );
2875
- });
2876
-
2877
- it("uses message_id as topic root when group_topic + replyInThread and no root_id", async () => {
2878
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2879
-
2880
- const cfg: ClawdbotConfig = {
2881
- channels: {
2882
- feishu: {
2883
- groups: {
2884
- "oc-group": {
2885
- requireMention: false,
2886
- groupSessionScope: "group_topic",
2887
- replyInThread: "enabled",
2888
- },
2889
- },
2890
- },
2891
- },
2892
- } as ClawdbotConfig;
2893
-
2894
- const event: FeishuMessageEvent = {
2895
- sender: { sender_id: { open_id: "ou-topic-init" } },
2896
- message: {
2897
- message_id: "msg-new-topic-root",
2898
- chat_id: "oc-group",
2899
- chat_type: "group",
2900
- message_type: "text",
2901
- content: JSON.stringify({ text: "create topic" }),
2902
- },
2903
- };
2904
-
2905
- await dispatchMessage({ cfg, event });
2906
-
2907
- expectResolvedRouteCall(
2908
- 0,
2909
- { kind: "group", id: "oc-group:topic:msg-new-topic-root" },
2910
- { kind: "group", id: "oc-group" },
2911
- );
2912
- });
2913
-
2914
- it("keeps topic session key stable after first turn creates a thread", async () => {
2915
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2916
-
2917
- const cfg: ClawdbotConfig = {
2918
- channels: {
2919
- feishu: {
2920
- groups: {
2921
- "oc-group": {
2922
- requireMention: false,
2923
- groupSessionScope: "group_topic",
2924
- replyInThread: "enabled",
2925
- },
2926
- },
2927
- },
2928
- },
2929
- } as ClawdbotConfig;
2930
-
2931
- const firstTurn: FeishuMessageEvent = {
2932
- sender: { sender_id: { open_id: "ou-topic-init" } },
2933
- message: {
2934
- message_id: "msg-topic-first",
2935
- chat_id: "oc-group",
2936
- chat_type: "group",
2937
- message_type: "text",
2938
- content: JSON.stringify({ text: "create topic" }),
2939
- },
2940
- };
2941
- const secondTurn: FeishuMessageEvent = {
2942
- sender: { sender_id: { open_id: "ou-topic-init" } },
2943
- message: {
2944
- message_id: "msg-topic-second",
2945
- chat_id: "oc-group",
2946
- chat_type: "group",
2947
- root_id: "msg-topic-first",
2948
- thread_id: "omt_topic_created",
2949
- message_type: "text",
2950
- content: JSON.stringify({ text: "follow up in same topic" }),
2951
- },
2952
- };
2953
-
2954
- await dispatchMessage({ cfg, event: firstTurn });
2955
- await dispatchMessage({ cfg, event: secondTurn });
2956
-
2957
- expectResolvedRouteCall(0, { kind: "group", id: "oc-group:topic:msg-topic-first" });
2958
- expectResolvedRouteCall(1, { kind: "group", id: "oc-group:topic:msg-topic-first" });
2959
- });
2960
-
2961
- it("hydrates missing native topic thread_id before routing starter events", async () => {
2962
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
2963
- mockGetMessageFeishu.mockResolvedValueOnce({
2964
- messageId: "msg-native-topic-first",
2965
- chatId: "oc-group",
2966
- chatType: "topic_group",
2967
- content: "topic starter",
2968
- contentType: "text",
2969
- threadId: "omt_native_topic",
2970
- });
2971
-
2972
- const cfg: ClawdbotConfig = {
2973
- channels: {
2974
- feishu: {
2975
- groups: {
2976
- "oc-group": {
2977
- requireMention: false,
2978
- groupSessionScope: "group_topic",
2979
- replyInThread: "enabled",
2980
- },
2981
- },
2982
- },
2983
- },
2984
- } as ClawdbotConfig;
2985
-
2986
- const firstTurn: FeishuMessageEvent = {
2987
- sender: { sender_id: { open_id: "ou-topic-init" } },
2988
- message: {
2989
- message_id: "msg-native-topic-first",
2990
- chat_id: "oc-group",
2991
- chat_type: "topic_group",
2992
- message_type: "text",
2993
- content: JSON.stringify({ text: "create native topic" }),
2994
- },
2995
- };
2996
- const secondTurn: FeishuMessageEvent = {
2997
- sender: { sender_id: { open_id: "ou-topic-init" } },
2998
- message: {
2999
- message_id: "msg-native-topic-second",
3000
- chat_id: "oc-group",
3001
- chat_type: "topic_group",
3002
- thread_id: "omt_native_topic",
3003
- message_type: "text",
3004
- content: JSON.stringify({ text: "follow up in same native topic" }),
3005
- },
3006
- };
3007
-
3008
- await dispatchMessage({ cfg, event: firstTurn });
3009
- await dispatchMessage({ cfg, event: secondTurn });
3010
-
3011
- const getMessageRequest = mockCallArg<{ messageId?: string }>(mockGetMessageFeishu, 0, 0);
3012
- expect(getMessageRequest.messageId).toBe("msg-native-topic-first");
3013
- expectResolvedRouteCall(0, { kind: "group", id: "oc-group:topic:omt_native_topic" });
3014
- expectResolvedRouteCall(1, { kind: "group", id: "oc-group:topic:omt_native_topic" });
3015
- });
3016
-
3017
- it("replies to the topic root when handling a message inside an existing topic", async () => {
3018
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3019
-
3020
- const cfg: ClawdbotConfig = {
3021
- channels: {
3022
- feishu: {
3023
- groups: {
3024
- "oc-group": {
3025
- requireMention: false,
3026
- replyInThread: "enabled",
3027
- },
3028
- },
3029
- },
3030
- },
3031
- } as ClawdbotConfig;
3032
-
3033
- const event: FeishuMessageEvent = {
3034
- sender: { sender_id: { open_id: "ou-topic-user" } },
3035
- message: {
3036
- message_id: "om_child_message",
3037
- root_id: "om_root_topic",
3038
- chat_id: "oc-group",
3039
- chat_type: "group",
3040
- message_type: "text",
3041
- content: JSON.stringify({ text: "reply inside topic" }),
3042
- },
3043
- };
3044
-
3045
- await dispatchMessage({ cfg, event });
3046
-
3047
- const dispatcherOptions = mockCallArg<{ replyToMessageId?: string; rootId?: string }>(
3048
- mockCreateFeishuReplyDispatcher,
3049
- 0,
3050
- 0,
3051
- );
3052
- expect(dispatcherOptions.replyToMessageId).toBe("om_root_topic");
3053
- expect(dispatcherOptions.rootId).toBe("om_root_topic");
3054
- });
3055
-
3056
- it("replies to triggering message in normal group even when root_id is present (#32980)", async () => {
3057
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3058
-
3059
- const cfg: ClawdbotConfig = {
3060
- channels: {
3061
- feishu: {
3062
- groups: {
3063
- "oc-group": {
3064
- requireMention: false,
3065
- groupSessionScope: "group",
3066
- },
3067
- },
3068
- },
3069
- },
3070
- } as ClawdbotConfig;
3071
-
3072
- const event: FeishuMessageEvent = {
3073
- sender: { sender_id: { open_id: "ou-normal-user" } },
3074
- message: {
3075
- message_id: "om_quote_reply",
3076
- root_id: "om_original_msg",
3077
- chat_id: "oc-group",
3078
- chat_type: "group",
3079
- message_type: "text",
3080
- content: JSON.stringify({ text: "hello in normal group" }),
3081
- },
3082
- };
3083
-
3084
- await dispatchMessage({ cfg, event });
3085
-
3086
- const dispatcherOptions = mockCallArg<{ replyToMessageId?: string; rootId?: string }>(
3087
- mockCreateFeishuReplyDispatcher,
3088
- 0,
3089
- 0,
3090
- );
3091
- expect(dispatcherOptions.replyToMessageId).toBe("om_quote_reply");
3092
- expect(dispatcherOptions.rootId).toBe("om_original_msg");
3093
- });
3094
-
3095
- it("replies to topic root in topic-mode group with root_id", async () => {
3096
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3097
-
3098
- const cfg: ClawdbotConfig = {
3099
- channels: {
3100
- feishu: {
3101
- groups: {
3102
- "oc-group": {
3103
- requireMention: false,
3104
- groupSessionScope: "group_topic",
3105
- },
3106
- },
3107
- },
3108
- },
3109
- } as ClawdbotConfig;
3110
-
3111
- const event: FeishuMessageEvent = {
3112
- sender: { sender_id: { open_id: "ou-topic-user" } },
3113
- message: {
3114
- message_id: "om_topic_reply",
3115
- root_id: "om_topic_root",
3116
- chat_id: "oc-group",
3117
- chat_type: "group",
3118
- message_type: "text",
3119
- content: JSON.stringify({ text: "hello in topic group" }),
3120
- },
3121
- };
3122
-
3123
- await dispatchMessage({ cfg, event });
3124
-
3125
- const dispatcherOptions = mockCallArg<{ replyToMessageId?: string; rootId?: string }>(
3126
- mockCreateFeishuReplyDispatcher,
3127
- 0,
3128
- 0,
3129
- );
3130
- expect(dispatcherOptions.replyToMessageId).toBe("om_topic_root");
3131
- expect(dispatcherOptions.rootId).toBe("om_topic_root");
3132
- });
3133
-
3134
- it("replies to topic root in topic-sender group with root_id", async () => {
3135
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3136
-
3137
- const cfg: ClawdbotConfig = {
3138
- channels: {
3139
- feishu: {
3140
- groups: {
3141
- "oc-group": {
3142
- requireMention: false,
3143
- groupSessionScope: "group_topic_sender",
3144
- },
3145
- },
3146
- },
3147
- },
3148
- } as ClawdbotConfig;
3149
-
3150
- const event: FeishuMessageEvent = {
3151
- sender: { sender_id: { open_id: "ou-topic-sender-user" } },
3152
- message: {
3153
- message_id: "om_topic_sender_reply",
3154
- root_id: "om_topic_sender_root",
3155
- chat_id: "oc-group",
3156
- chat_type: "group",
3157
- message_type: "text",
3158
- content: JSON.stringify({ text: "hello in topic sender group" }),
3159
- },
3160
- };
3161
-
3162
- await dispatchMessage({ cfg, event });
3163
-
3164
- const dispatcherOptions = mockCallArg<{ replyToMessageId?: string; rootId?: string }>(
3165
- mockCreateFeishuReplyDispatcher,
3166
- 0,
3167
- 0,
3168
- );
3169
- expect(dispatcherOptions.replyToMessageId).toBe("om_topic_sender_root");
3170
- expect(dispatcherOptions.rootId).toBe("om_topic_sender_root");
3171
- });
3172
-
3173
- it("forces thread replies when inbound message contains thread_id", async () => {
3174
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3175
-
3176
- const cfg: ClawdbotConfig = {
3177
- channels: {
3178
- feishu: {
3179
- groups: {
3180
- "oc-group": {
3181
- requireMention: false,
3182
- groupSessionScope: "group",
3183
- replyInThread: "disabled",
3184
- },
3185
- },
3186
- },
3187
- },
3188
- } as ClawdbotConfig;
3189
-
3190
- const event: FeishuMessageEvent = {
3191
- sender: { sender_id: { open_id: "ou-thread-reply" } },
3192
- message: {
3193
- message_id: "msg-thread-reply",
3194
- chat_id: "oc-group",
3195
- chat_type: "group",
3196
- thread_id: "omt_topic_thread_reply",
3197
- message_type: "text",
3198
- content: JSON.stringify({ text: "thread content" }),
3199
- },
3200
- };
3201
-
3202
- await dispatchMessage({ cfg, event });
3203
-
3204
- const dispatcherOptions = mockCallArg<{ replyInThread?: boolean; threadReply?: boolean }>(
3205
- mockCreateFeishuReplyDispatcher,
3206
- 0,
3207
- 0,
3208
- );
3209
- expect(dispatcherOptions.replyInThread).toBe(true);
3210
- expect(dispatcherOptions.threadReply).toBe(true);
3211
- });
3212
-
3213
- it("bootstraps topic thread context only for a new thread session", async () => {
3214
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3215
- mockGetMessageFeishu.mockResolvedValue({
3216
- messageId: "om_topic_root",
3217
- chatId: "oc-group",
3218
- content: "root starter",
3219
- contentType: "text",
3220
- threadId: "omt_topic_1",
3221
- });
3222
- mockListFeishuThreadMessages.mockResolvedValue([
3223
- {
3224
- messageId: "om_bot_reply",
3225
- senderId: "app_1",
3226
- senderType: "app",
3227
- content: "assistant reply",
3228
- contentType: "text",
3229
- createTime: 1710000000000,
3230
- },
3231
- {
3232
- messageId: "om_follow_up",
3233
- senderId: "ou-topic-user",
3234
- senderType: "user",
3235
- content: "follow-up question",
3236
- contentType: "text",
3237
- createTime: 1710000001000,
3238
- },
3239
- ]);
3240
-
3241
- const cfg: ClawdbotConfig = {
3242
- channels: {
3243
- feishu: {
3244
- groups: {
3245
- "oc-group": {
3246
- requireMention: false,
3247
- groupSessionScope: "group_topic",
3248
- },
3249
- },
3250
- },
3251
- },
3252
- } as ClawdbotConfig;
3253
-
3254
- const event: FeishuMessageEvent = {
3255
- sender: { sender_id: { open_id: "ou-topic-user" } },
3256
- message: {
3257
- message_id: "om_topic_followup_existing_session",
3258
- root_id: "om_topic_root",
3259
- chat_id: "oc-group",
3260
- chat_type: "group",
3261
- message_type: "text",
3262
- content: JSON.stringify({ text: "current turn" }),
3263
- },
3264
- };
3265
-
3266
- await dispatchMessage({ cfg, event });
3267
-
3268
- expect(mockReadSessionUpdatedAt).toHaveBeenCalledWith({
3269
- storePath: "/tmp/feishu-sessions.json",
3270
- sessionKey: "agent:main:feishu:dm:ou-attacker",
3271
- });
3272
- const listRequest = mockCallArg<{ rootMessageId?: string }>(mockListFeishuThreadMessages, 0, 0);
3273
- expect(listRequest.rootMessageId).toBe("om_topic_root");
3274
- const context = mockCallArg<{
3275
- MessageThreadId?: string;
3276
- ThreadHistoryBody?: string;
3277
- ThreadLabel?: string;
3278
- ThreadStarterBody?: string;
3279
- }>(mockFinalizeInboundContext, 0, 0);
3280
- expect(context.ThreadStarterBody).toBe("root starter");
3281
- expect(context.ThreadHistoryBody).toBe("assistant reply\n\nfollow-up question");
3282
- expect(context.ThreadLabel).toBe("Feishu thread in oc-group");
3283
- expect(context.MessageThreadId).toBe("om_topic_root");
3284
- });
3285
-
3286
- it("skips topic thread bootstrap when the thread session already exists", async () => {
3287
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3288
- mockReadSessionUpdatedAt.mockReturnValue(1710000000000);
3289
-
3290
- const cfg: ClawdbotConfig = {
3291
- channels: {
3292
- feishu: {
3293
- groups: {
3294
- "oc-group": {
3295
- requireMention: false,
3296
- groupSessionScope: "group_topic",
3297
- },
3298
- },
3299
- },
3300
- },
3301
- } as ClawdbotConfig;
3302
-
3303
- const event: FeishuMessageEvent = {
3304
- sender: { sender_id: { open_id: "ou-topic-user" } },
3305
- message: {
3306
- message_id: "om_topic_followup",
3307
- root_id: "om_topic_root",
3308
- chat_id: "oc-group",
3309
- chat_type: "group",
3310
- message_type: "text",
3311
- content: JSON.stringify({ text: "current turn" }),
3312
- },
3313
- };
3314
-
3315
- await dispatchMessage({ cfg, event });
3316
-
3317
- expect(mockGetMessageFeishu).not.toHaveBeenCalled();
3318
- expect(mockListFeishuThreadMessages).not.toHaveBeenCalled();
3319
- const context = mockCallArg<{
3320
- MessageThreadId?: string;
3321
- ThreadHistoryBody?: string;
3322
- ThreadLabel?: string;
3323
- ThreadStarterBody?: string;
3324
- }>(mockFinalizeInboundContext, 0, 0);
3325
- expect(context.ThreadStarterBody).toBeUndefined();
3326
- expect(context.ThreadHistoryBody).toBeUndefined();
3327
- expect(context.ThreadLabel).toBe("Feishu thread in oc-group");
3328
- expect(context.MessageThreadId).toBe("om_topic_root");
3329
- });
3330
-
3331
- it("keeps sender-scoped thread history when the inbound event and thread history use different sender ids", async () => {
3332
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3333
- mockGetMessageFeishu.mockResolvedValue({
3334
- messageId: "om_topic_root",
3335
- chatId: "oc-group",
3336
- content: "root starter",
3337
- contentType: "text",
3338
- threadId: "omt_topic_1",
3339
- });
3340
- mockListFeishuThreadMessages.mockResolvedValue([
3341
- {
3342
- messageId: "om_bot_reply",
3343
- senderId: "app_1",
3344
- senderType: "app",
3345
- content: "assistant reply",
3346
- contentType: "text",
3347
- createTime: 1710000000000,
3348
- },
3349
- {
3350
- messageId: "om_follow_up",
3351
- senderId: "user_topic_1",
3352
- senderType: "user",
3353
- content: "follow-up question",
3354
- contentType: "text",
3355
- createTime: 1710000001000,
3356
- },
3357
- ]);
3358
-
3359
- const cfg: ClawdbotConfig = {
3360
- channels: {
3361
- feishu: {
3362
- groups: {
3363
- "oc-group": {
3364
- requireMention: false,
3365
- groupSessionScope: "group_topic_sender",
3366
- },
3367
- },
3368
- },
3369
- },
3370
- } as ClawdbotConfig;
3371
-
3372
- const event: FeishuMessageEvent = {
3373
- sender: {
3374
- sender_id: {
3375
- open_id: "ou-topic-user",
3376
- user_id: "user_topic_1",
3377
- },
3378
- },
3379
- message: {
3380
- message_id: "om_topic_followup_mixed_ids",
3381
- root_id: "om_topic_root",
3382
- chat_id: "oc-group",
3383
- chat_type: "group",
3384
- message_type: "text",
3385
- content: JSON.stringify({ text: "current turn" }),
3386
- },
3387
- };
3388
-
3389
- await dispatchMessage({ cfg, event });
3390
-
3391
- const context = mockCallArg<{
3392
- MessageThreadId?: string;
3393
- ThreadHistoryBody?: string;
3394
- ThreadLabel?: string;
3395
- ThreadStarterBody?: string;
3396
- }>(mockFinalizeInboundContext, 0, 0);
3397
- expect(context.ThreadStarterBody).toBe("root starter");
3398
- expect(context.ThreadHistoryBody).toBe("assistant reply\n\nfollow-up question");
3399
- expect(context.ThreadLabel).toBe("Feishu thread in oc-group");
3400
- expect(context.MessageThreadId).toBe("om_topic_root");
3401
- });
3402
-
3403
- it("filters topic bootstrap context to allowlisted group senders", async () => {
3404
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3405
- mockGetMessageFeishu.mockResolvedValue({
3406
- messageId: "om_topic_root",
3407
- chatId: "oc-group",
3408
- senderId: "ou-blocked",
3409
- senderType: "user",
3410
- content: "blocked root starter",
3411
- contentType: "text",
3412
- threadId: "omt_topic_1",
3413
- });
3414
- mockListFeishuThreadMessages.mockResolvedValue([
3415
- {
3416
- messageId: "om_blocked_reply",
3417
- senderId: "ou-blocked",
3418
- senderType: "user",
3419
- content: "blocked follow-up",
3420
- contentType: "text",
3421
- createTime: 1710000000000,
3422
- },
3423
- {
3424
- messageId: "om_bot_reply",
3425
- senderId: "app_1",
3426
- senderType: "app",
3427
- content: "assistant reply",
3428
- contentType: "text",
3429
- createTime: 1710000001000,
3430
- },
3431
- {
3432
- messageId: "om_allowed_reply",
3433
- senderId: "ou-allowed",
3434
- senderType: "user",
3435
- content: "allowed follow-up",
3436
- contentType: "text",
3437
- createTime: 1710000002000,
3438
- },
3439
- ]);
3440
-
3441
- const cfg: ClawdbotConfig = {
3442
- channels: {
3443
- feishu: {
3444
- groupPolicy: "open",
3445
- groupSenderAllowFrom: ["ou-allowed"],
3446
- contextVisibility: "allowlist",
3447
- groups: {
3448
- "oc-group": {
3449
- requireMention: false,
3450
- groupSessionScope: "group_topic",
3451
- },
3452
- },
3453
- },
3454
- },
3455
- } as ClawdbotConfig;
3456
-
3457
- const event: FeishuMessageEvent = {
3458
- sender: { sender_id: { open_id: "ou-allowed" } },
3459
- message: {
3460
- message_id: "om_topic_followup_allowlisted",
3461
- root_id: "om_topic_root",
3462
- thread_id: "omt_topic_1",
3463
- chat_id: "oc-group",
3464
- chat_type: "group",
3465
- message_type: "text",
3466
- content: JSON.stringify({ text: "current turn" }),
3467
- },
3468
- };
3469
-
3470
- await dispatchMessage({ cfg, event });
3471
-
3472
- const context = mockCallArg<{
3473
- ThreadHistoryBody?: string;
3474
- ThreadStarterBody?: string;
3475
- }>(mockFinalizeInboundContext, 0, 0);
3476
- expect(context.ThreadStarterBody).toBe("assistant reply");
3477
- expect(context.ThreadHistoryBody).toBe("assistant reply\n\nallowed follow-up");
3478
- });
3479
-
3480
- it("does not dispatch twice for the same image message_id (concurrent dedupe)", async () => {
3481
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3482
-
3483
- const cfg: ClawdbotConfig = {
3484
- channels: {
3485
- feishu: {
3486
- dmPolicy: "open",
3487
- },
3488
- },
3489
- } as ClawdbotConfig;
3490
-
3491
- const event: FeishuMessageEvent = {
3492
- sender: {
3493
- sender_id: {
3494
- open_id: "ou-image-dedup",
3495
- },
3496
- },
3497
- message: {
3498
- message_id: "msg-image-dedup",
3499
- chat_id: "oc-dm",
3500
- chat_type: "p2p",
3501
- message_type: "image",
3502
- content: JSON.stringify({
3503
- image_key: "img_dedup_payload",
3504
- }),
3505
- },
3506
- };
3507
-
3508
- await Promise.all([dispatchMessage({ cfg, event }), dispatchMessage({ cfg, event })]);
3509
- expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
3510
- });
3511
-
3512
- it("dedupes Feishu media by message_id plus file_key", async () => {
3513
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3514
-
3515
- const cfg: ClawdbotConfig = {
3516
- channels: {
3517
- feishu: {
3518
- dmPolicy: "open",
3519
- },
3520
- },
3521
- } as ClawdbotConfig;
3522
- const createAudioEvent = (fileKey: string): FeishuMessageEvent => ({
3523
- sender: {
3524
- sender_id: {
3525
- open_id: "ou-audio-dedup",
3526
- },
3527
- },
3528
- message: {
3529
- message_id: "msg-audio-reused-id",
3530
- chat_id: "oc-dm",
3531
- chat_type: "p2p",
3532
- message_type: "audio",
3533
- content: JSON.stringify({
3534
- file_key: fileKey,
3535
- duration: 1200,
3536
- }),
3537
- },
3538
- });
3539
-
3540
- await dispatchMessage({ cfg, event: createAudioEvent("file_audio_first") });
3541
- await dispatchMessage({ cfg, event: createAudioEvent("file_audio_second") });
3542
- await dispatchMessage({ cfg, event: createAudioEvent("file_audio_first") });
3543
-
3544
- expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(2);
3545
- expect(mockDownloadMessageResourceFeishu).toHaveBeenCalledTimes(2);
3546
- const firstDownloadRequest = mockCallArg<{
3547
- fileKey?: string;
3548
- messageId?: string;
3549
- type?: string;
3550
- }>(mockDownloadMessageResourceFeishu, 0, 0);
3551
- expect(firstDownloadRequest.messageId).toBe("msg-audio-reused-id");
3552
- expect(firstDownloadRequest.fileKey).toBe("file_audio_first");
3553
- expect(firstDownloadRequest.type).toBe("file");
3554
- const secondDownloadRequest = mockCallArg<{
3555
- fileKey?: string;
3556
- messageId?: string;
3557
- type?: string;
3558
- }>(mockDownloadMessageResourceFeishu, 1, 0);
3559
- expect(secondDownloadRequest.messageId).toBe("msg-audio-reused-id");
3560
- expect(secondDownloadRequest.fileKey).toBe("file_audio_second");
3561
- expect(secondDownloadRequest.type).toBe("file");
3562
- });
3563
-
3564
- it("skips empty-text messages with no media to prevent blank user turns in session (#74634)", async () => {
3565
- // Feishu can deliver { "text": "" } events (empty-text or media-stripped
3566
- // messages). Writing blank user content to the session causes downstream
3567
- // LLM providers such as MiniMax to reject requests with "messages must not
3568
- // be empty". The handler should drop such events before queuing a reply.
3569
- mockShouldComputeCommandAuthorized.mockReturnValue(false);
3570
-
3571
- const cfg: ClawdbotConfig = {
3572
- channels: {
3573
- feishu: {
3574
- dmPolicy: "open",
3575
- allowFrom: ["*"],
3576
- },
3577
- },
3578
- } as ClawdbotConfig;
3579
-
3580
- const event: FeishuMessageEvent = {
3581
- sender: {
3582
- sender_id: {
3583
- open_id: "ou-empty-text-sender",
3584
- },
3585
- },
3586
- message: {
3587
- message_id: "msg-empty-text-74634",
3588
- chat_id: "oc-dm",
3589
- chat_type: "p2p",
3590
- message_type: "text",
3591
- // Feishu encodes empty text as {"text":""}
3592
- content: JSON.stringify({ text: "" }),
3593
- },
3594
- };
3595
-
3596
- await dispatchMessage({ cfg, event });
3597
-
3598
- // No reply should be dispatched: empty message is silently skipped
3599
- expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
3600
- });
3601
- });
3602
-
3603
- describe("createFeishuMessageReceiveHandler media dedupe", () => {
3604
- it("keeps same-id media variants distinct at receive time", async () => {
3605
- const handleMessage = vi.fn(async () => undefined);
3606
- const core = {
3607
- channel: {
3608
- debounce: {
3609
- resolveInboundDebounceMs: vi.fn(() => 0),
3610
- createInboundDebouncer: vi.fn(
3611
- (options: { onFlush: (entries: FeishuMessageEvent[]) => Promise<void> | void }) => ({
3612
- enqueue: async (event: FeishuMessageEvent) => {
3613
- await options.onFlush([event]);
3614
- },
3615
- }),
3616
- ),
3617
- },
3618
- text: {
3619
- hasControlCommand: vi.fn(() => false),
3620
- },
3621
- },
3622
- } as unknown as PluginRuntime;
3623
- const createAudioEvent = (fileKey: string): FeishuMessageEvent => ({
3624
- sender: {
3625
- sender_id: {
3626
- open_id: "ou-audio-receive-dedup",
3627
- },
3628
- },
3629
- message: {
3630
- message_id: "msg-audio-receive-reused-id",
3631
- chat_id: "oc-dm",
3632
- chat_type: "p2p",
3633
- message_type: "audio",
3634
- content: JSON.stringify({
3635
- file_key: fileKey,
3636
- duration: 1200,
3637
- }),
3638
- },
3639
- });
3640
- const handler = createFeishuMessageReceiveHandler({
3641
- cfg: { channels: { feishu: { dmPolicy: "open" } } } as ClawdbotConfig,
3642
- core,
3643
- accountId: "receive-media-dedupe",
3644
- chatHistories: new Map(),
3645
- handleMessage,
3646
- resolveDebounceText: () => "",
3647
- hasProcessedMessage: vi.fn(async () => false),
3648
- recordProcessedMessage: vi.fn(async () => true),
3649
- });
3650
-
3651
- const firstEvent = createAudioEvent("file_audio_receive_first");
3652
- const secondEvent = createAudioEvent("file_audio_receive_second");
3653
- await handler(firstEvent);
3654
- await handler(secondEvent);
3655
- await handler(createAudioEvent("file_audio_receive_first"));
3656
-
3657
- expect(handleMessage).toHaveBeenCalledTimes(2);
3658
- const firstCall = mockCallArg<{
3659
- event?: FeishuMessageEvent;
3660
- processingClaimHeld?: boolean;
3661
- }>(handleMessage, 0, 0);
3662
- expect(firstCall.event).toEqual(firstEvent);
3663
- expect(firstCall.processingClaimHeld).toBe(true);
3664
- const secondCall = mockCallArg<{
3665
- event?: FeishuMessageEvent;
3666
- processingClaimHeld?: boolean;
3667
- }>(handleMessage, 1, 0);
3668
- expect(secondCall.event).toEqual(secondEvent);
3669
- expect(secondCall.processingClaimHeld).toBe(true);
3670
- });
3671
- });