@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
@@ -1,739 +0,0 @@
1
- import {
2
- createInboundDebouncer,
3
- resolveInboundDebounceMs,
4
- } from "klaw/plugin-sdk/channel-inbound-debounce";
5
- import { hasControlCommand } from "klaw/plugin-sdk/command-detection";
6
- import { createNonExitingRuntimeEnv } from "klaw/plugin-sdk/plugin-test-runtime";
7
- import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
8
- import type { ClawdbotConfig, PluginRuntime } from "../runtime-api.js";
9
- import { parseFeishuMessageEvent, type FeishuMessageEvent } from "./bot.js";
10
- import * as dedup from "./dedup.js";
11
- import {
12
- monitorSingleAccount,
13
- resolveReactionSyntheticEvent,
14
- type FeishuReactionCreatedEvent,
15
- } from "./monitor.account.js";
16
- import { setFeishuRuntime } from "./runtime.js";
17
- import type { ResolvedFeishuAccount } from "./types.js";
18
-
19
- const handleFeishuMessageMock = vi.hoisted(() => vi.fn(async (_params: { event?: unknown }) => {}));
20
- const createEventDispatcherMock = vi.hoisted(() => vi.fn());
21
- const monitorWebSocketMock = vi.hoisted(() => vi.fn(async () => {}));
22
- const monitorWebhookMock = vi.hoisted(() => vi.fn(async () => {}));
23
- const createFeishuThreadBindingManagerMock = vi.hoisted(() => vi.fn(() => ({ stop: vi.fn() })));
24
-
25
- let handlers: Record<string, (data: unknown) => Promise<void>> = {};
26
-
27
- vi.mock("./client.js", () => ({
28
- createEventDispatcher: createEventDispatcherMock,
29
- }));
30
-
31
- vi.mock("./bot.js", async () => {
32
- const actual = await vi.importActual<typeof import("./bot.js")>("./bot.js");
33
- return {
34
- ...actual,
35
- handleFeishuMessage: handleFeishuMessageMock,
36
- };
37
- });
38
-
39
- vi.mock("./monitor.transport.js", () => ({
40
- monitorWebSocket: monitorWebSocketMock,
41
- monitorWebhook: monitorWebhookMock,
42
- }));
43
-
44
- vi.mock("./thread-bindings.js", () => ({
45
- createFeishuThreadBindingManager: createFeishuThreadBindingManagerMock,
46
- }));
47
-
48
- afterAll(() => {
49
- vi.doUnmock("./client.js");
50
- vi.doUnmock("./bot.js");
51
- vi.doUnmock("./monitor.transport.js");
52
- vi.doUnmock("./thread-bindings.js");
53
- vi.resetModules();
54
- });
55
-
56
- const cfg = {} as ClawdbotConfig;
57
-
58
- function makeReactionEvent(
59
- overrides: Partial<FeishuReactionCreatedEvent> = {},
60
- ): FeishuReactionCreatedEvent {
61
- return {
62
- message_id: "om_msg1",
63
- reaction_type: { emoji_type: "THUMBSUP" },
64
- operator_type: "user",
65
- user_id: { open_id: "ou_user1" },
66
- ...overrides,
67
- };
68
- }
69
-
70
- function createFetchedReactionMessage(chatId: string, chatType?: "p2p" | "group" | "private") {
71
- return {
72
- messageId: "om_msg1",
73
- chatId,
74
- chatType,
75
- senderOpenId: "ou_bot",
76
- content: "hello",
77
- contentType: "text",
78
- };
79
- }
80
-
81
- async function resolveReactionWithLookup(params: {
82
- event?: FeishuReactionCreatedEvent;
83
- lookupChatId: string;
84
- lookupChatType?: "p2p" | "group" | "private";
85
- }) {
86
- return await resolveReactionSyntheticEvent({
87
- cfg,
88
- accountId: "default",
89
- event: params.event ?? makeReactionEvent(),
90
- botOpenId: "ou_bot",
91
- fetchMessage: async () =>
92
- createFetchedReactionMessage(params.lookupChatId, params.lookupChatType),
93
- uuid: () => "fixed-uuid",
94
- });
95
- }
96
-
97
- async function resolveNonBotReaction(params?: { cfg?: ClawdbotConfig; uuid?: () => string }) {
98
- return await resolveReactionSyntheticEvent({
99
- cfg: params?.cfg ?? cfg,
100
- accountId: "default",
101
- event: makeReactionEvent(),
102
- botOpenId: "ou_bot",
103
- fetchMessage: async () => ({
104
- messageId: "om_msg1",
105
- chatId: "oc_group",
106
- chatType: "group",
107
- senderOpenId: "ou_other",
108
- senderType: "user",
109
- content: "hello",
110
- contentType: "text",
111
- }),
112
- ...(params?.uuid ? { uuid: params.uuid } : {}),
113
- });
114
- }
115
-
116
- type FeishuMention = NonNullable<FeishuMessageEvent["message"]["mentions"]>[number];
117
-
118
- function buildDebounceConfig(): ClawdbotConfig {
119
- return {
120
- messages: {
121
- inbound: {
122
- debounceMs: 0,
123
- byChannel: {
124
- feishu: 20,
125
- },
126
- },
127
- },
128
- channels: {
129
- feishu: {
130
- enabled: true,
131
- },
132
- },
133
- } as ClawdbotConfig;
134
- }
135
-
136
- function buildDebounceAccount(): ResolvedFeishuAccount {
137
- return {
138
- accountId: "default",
139
- enabled: true,
140
- configured: true,
141
- appId: "cli_test",
142
- appSecret: "secret_test", // pragma: allowlist secret
143
- domain: "feishu",
144
- config: {
145
- enabled: true,
146
- connectionMode: "websocket",
147
- },
148
- } as ResolvedFeishuAccount;
149
- }
150
-
151
- function createTextEvent(params: {
152
- messageId: string;
153
- text: string;
154
- senderId?: string;
155
- mentions?: FeishuMention[];
156
- }): FeishuMessageEvent {
157
- const senderId = params.senderId ?? "ou_sender";
158
- return {
159
- sender: {
160
- sender_id: { open_id: senderId },
161
- sender_type: "user",
162
- },
163
- message: {
164
- message_id: params.messageId,
165
- chat_id: "oc_group_1",
166
- chat_type: "group",
167
- message_type: "text",
168
- content: JSON.stringify({ text: params.text }),
169
- mentions: params.mentions,
170
- },
171
- };
172
- }
173
-
174
- async function setupDebounceMonitor(params?: {
175
- botOpenId?: string;
176
- botName?: string;
177
- }): Promise<(data: unknown) => Promise<void>> {
178
- const register = vi.fn((registered: Record<string, (data: unknown) => Promise<void>>) => {
179
- handlers = registered;
180
- });
181
- createEventDispatcherMock.mockReturnValue({ register });
182
-
183
- await monitorSingleAccount({
184
- cfg: buildDebounceConfig(),
185
- account: buildDebounceAccount(),
186
- runtime: createNonExitingRuntimeEnv(),
187
- botOpenIdSource: {
188
- kind: "prefetched",
189
- botOpenId: params?.botOpenId ?? "ou_bot",
190
- botName: params?.botName,
191
- },
192
- });
193
-
194
- const onMessage = handlers["im.message.receive_v1"];
195
- if (!onMessage) {
196
- throw new Error("missing im.message.receive_v1 handler");
197
- }
198
- return onMessage;
199
- }
200
-
201
- function mockCallAt(
202
- mock: { mock: { calls: Array<readonly unknown[]> } },
203
- index: number,
204
- label: string,
205
- ): readonly unknown[] {
206
- const call = mock.mock.calls[index];
207
- if (!call) {
208
- throw new Error(`expected ${label} call`);
209
- }
210
- return call;
211
- }
212
-
213
- function getFirstDispatchedEvent(): FeishuMessageEvent {
214
- const firstCall = mockCallAt(handleFeishuMessageMock, 0, "Feishu message dispatch");
215
- const firstParams = firstCall[0] as { event?: FeishuMessageEvent } | undefined;
216
- if (!firstParams?.event) {
217
- throw new Error("missing dispatched event payload");
218
- }
219
- return firstParams.event;
220
- }
221
-
222
- function expectSingleDispatchedEvent(): FeishuMessageEvent {
223
- expect(handleFeishuMessageMock).toHaveBeenCalledTimes(1);
224
- return getFirstDispatchedEvent();
225
- }
226
-
227
- function expectParsedFirstDispatchedEvent(botOpenId = "ou_bot") {
228
- const dispatched = expectSingleDispatchedEvent();
229
- return {
230
- dispatched,
231
- parsed: parseFeishuMessageEvent(dispatched, botOpenId),
232
- };
233
- }
234
-
235
- function setDedupPassThroughMocks(): void {
236
- vi.spyOn(dedup, "tryBeginFeishuMessageProcessing").mockReturnValue(true);
237
- vi.spyOn(dedup, "recordProcessedFeishuMessage").mockResolvedValue(true);
238
- vi.spyOn(dedup, "hasProcessedFeishuMessage").mockResolvedValue(false);
239
- }
240
-
241
- function createMention(params: { openId: string; name: string; key?: string }): FeishuMention {
242
- return {
243
- key: params.key ?? "@_user_1",
244
- id: { open_id: params.openId },
245
- name: params.name,
246
- };
247
- }
248
-
249
- function mentionOpenIds(event: FeishuMessageEvent): string[] {
250
- return (event.message.mentions ?? []).flatMap((mention) =>
251
- mention.id.open_id ? [mention.id.open_id] : [],
252
- );
253
- }
254
-
255
- function createFeishuMonitorRuntime(params?: {
256
- createInboundDebouncer?: PluginRuntime["channel"]["debounce"]["createInboundDebouncer"];
257
- resolveInboundDebounceMs?: PluginRuntime["channel"]["debounce"]["resolveInboundDebounceMs"];
258
- hasControlCommand?: PluginRuntime["channel"]["text"]["hasControlCommand"];
259
- }): PluginRuntime {
260
- return {
261
- channel: {
262
- debounce: {
263
- createInboundDebouncer: params?.createInboundDebouncer ?? createInboundDebouncer,
264
- resolveInboundDebounceMs: params?.resolveInboundDebounceMs ?? resolveInboundDebounceMs,
265
- },
266
- text: {
267
- hasControlCommand: params?.hasControlCommand ?? hasControlCommand,
268
- },
269
- },
270
- } as unknown as PluginRuntime;
271
- }
272
-
273
- async function enqueueDebouncedMessage(
274
- onMessage: (data: unknown) => Promise<void>,
275
- event: FeishuMessageEvent,
276
- ): Promise<void> {
277
- await onMessage(event);
278
- await Promise.resolve();
279
- await Promise.resolve();
280
- }
281
-
282
- function setStaleRetryMocks(messageId = "om_old") {
283
- vi.spyOn(dedup, "hasProcessedFeishuMessage").mockImplementation(
284
- async (currentMessageId) => currentMessageId === messageId,
285
- );
286
- }
287
-
288
- describe("resolveReactionSyntheticEvent", () => {
289
- it("filters app self-reactions", async () => {
290
- const event = makeReactionEvent({ operator_type: "app" });
291
- const result = await resolveReactionSyntheticEvent({
292
- cfg,
293
- accountId: "default",
294
- event,
295
- botOpenId: "ou_bot",
296
- });
297
- expect(result).toBeNull();
298
- });
299
-
300
- it("filters Typing reactions", async () => {
301
- const event = makeReactionEvent({ reaction_type: { emoji_type: "Typing" } });
302
- const result = await resolveReactionSyntheticEvent({
303
- cfg,
304
- accountId: "default",
305
- event,
306
- botOpenId: "ou_bot",
307
- });
308
- expect(result).toBeNull();
309
- });
310
-
311
- it("fails closed when bot open_id is unavailable", async () => {
312
- const event = makeReactionEvent();
313
- const result = await resolveReactionSyntheticEvent({
314
- cfg,
315
- accountId: "default",
316
- event,
317
- });
318
- expect(result).toBeNull();
319
- });
320
-
321
- it("drops reactions when reactionNotifications is off", async () => {
322
- const event = makeReactionEvent();
323
- const result = await resolveReactionSyntheticEvent({
324
- cfg: {
325
- channels: {
326
- feishu: {
327
- reactionNotifications: "off",
328
- },
329
- },
330
- } as ClawdbotConfig,
331
- accountId: "default",
332
- event,
333
- botOpenId: "ou_bot",
334
- fetchMessage: async () => ({
335
- messageId: "om_msg1",
336
- chatId: "oc_group",
337
- senderOpenId: "ou_bot",
338
- senderType: "app",
339
- content: "hello",
340
- contentType: "text",
341
- }),
342
- });
343
- expect(result).toBeNull();
344
- });
345
-
346
- it("filters reactions on non-bot messages", async () => {
347
- const result = await resolveNonBotReaction();
348
- expect(result).toBeNull();
349
- });
350
-
351
- it("allows non-bot reactions when reactionNotifications is all", async () => {
352
- const result = await resolveNonBotReaction({
353
- cfg: {
354
- channels: {
355
- feishu: {
356
- reactionNotifications: "all",
357
- },
358
- },
359
- } as ClawdbotConfig,
360
- uuid: () => "fixed-uuid",
361
- });
362
- expect(result?.message.message_id).toBe("om_msg1:reaction:THUMBSUP:fixed-uuid");
363
- });
364
-
365
- it("drops unverified reactions when sender verification times out", async () => {
366
- const event = makeReactionEvent();
367
- const result = await resolveReactionSyntheticEvent({
368
- cfg,
369
- accountId: "default",
370
- event,
371
- botOpenId: "ou_bot",
372
- verificationTimeoutMs: 1,
373
- fetchMessage: async () =>
374
- await new Promise<never>(() => {
375
- // Never resolves
376
- }),
377
- });
378
- expect(result).toBeNull();
379
- });
380
-
381
- it("uses event chat context when provided", async () => {
382
- const result = await resolveReactionWithLookup({
383
- event: makeReactionEvent({
384
- chat_id: "oc_group_from_event",
385
- chat_type: "group",
386
- }),
387
- lookupChatId: "oc_group_from_lookup",
388
- });
389
-
390
- expect(result).toEqual({
391
- sender: {
392
- sender_id: { open_id: "ou_user1" },
393
- sender_type: "user",
394
- },
395
- message: {
396
- message_id: "om_msg1:reaction:THUMBSUP:fixed-uuid",
397
- chat_id: "oc_group_from_event",
398
- chat_type: "group",
399
- message_type: "text",
400
- content: JSON.stringify({
401
- text: "[reacted with THUMBSUP to message om_msg1]",
402
- }),
403
- },
404
- });
405
- });
406
-
407
- it("falls back to reacted message chat_id when event chat_id is absent", async () => {
408
- const result = await resolveReactionWithLookup({
409
- lookupChatId: "oc_group_from_lookup",
410
- lookupChatType: "group",
411
- });
412
-
413
- expect(result?.message.chat_id).toBe("oc_group_from_lookup");
414
- expect(result?.message.chat_type).toBe("group");
415
- });
416
-
417
- it("falls back to sender p2p chat when lookup returns empty chat_id", async () => {
418
- const result = await resolveReactionWithLookup({
419
- lookupChatId: "",
420
- lookupChatType: "p2p",
421
- });
422
-
423
- expect(result?.message.chat_id).toBe("p2p:ou_user1");
424
- expect(result?.message.chat_type).toBe("p2p");
425
- });
426
-
427
- it("drops reactions without chat context when lookup does not provide chat_type", async () => {
428
- const result = await resolveReactionWithLookup({
429
- lookupChatId: "oc_group_from_lookup",
430
- });
431
-
432
- expect(result).toBeNull();
433
- });
434
-
435
- it("drops reactions when event chat_type is invalid and lookup cannot recover it", async () => {
436
- const result = await resolveReactionWithLookup({
437
- event: makeReactionEvent({
438
- chat_id: "oc_group_from_event",
439
- chat_type: "bogus" as "group",
440
- }),
441
- lookupChatId: "oc_group_from_lookup",
442
- });
443
-
444
- expect(result).toBeNull();
445
- });
446
-
447
- it("logs and drops reactions when lookup throws", async () => {
448
- const log = vi.fn();
449
- const event = makeReactionEvent();
450
- const result = await resolveReactionSyntheticEvent({
451
- cfg,
452
- accountId: "acct1",
453
- event,
454
- botOpenId: "ou_bot",
455
- fetchMessage: async () => {
456
- throw new Error("boom");
457
- },
458
- logger: log,
459
- });
460
- expect(result).toBeNull();
461
- expect(log).toHaveBeenCalledWith(
462
- "feishu[acct1]: ignoring reaction on non-bot/unverified message om_msg1 (sender: unknown)",
463
- );
464
- });
465
- });
466
-
467
- describe("monitorSingleAccount lifecycle", () => {
468
- beforeEach(() => {
469
- createFeishuThreadBindingManagerMock.mockReset().mockImplementation(() => ({
470
- stop: vi.fn(),
471
- }));
472
- createEventDispatcherMock.mockReset().mockReturnValue({
473
- register: vi.fn(),
474
- });
475
- });
476
-
477
- it("stops the Feishu thread binding manager when the monitor exits", async () => {
478
- setFeishuRuntime(createFeishuMonitorRuntime());
479
-
480
- await monitorSingleAccount({
481
- cfg: buildDebounceConfig(),
482
- account: buildDebounceAccount(),
483
- runtime: createNonExitingRuntimeEnv(),
484
- botOpenIdSource: {
485
- kind: "prefetched",
486
- botOpenId: "ou_bot",
487
- },
488
- });
489
-
490
- const manager = createFeishuThreadBindingManagerMock.mock.results[0]?.value as
491
- | { stop: ReturnType<typeof vi.fn> }
492
- | undefined;
493
- expect(manager?.stop).toHaveBeenCalledTimes(1);
494
- });
495
-
496
- it("stops the Feishu thread binding manager when setup fails before transport starts", async () => {
497
- setFeishuRuntime(createFeishuMonitorRuntime());
498
- createEventDispatcherMock.mockReturnValue({
499
- get register() {
500
- throw new Error("register failed");
501
- },
502
- });
503
-
504
- await expect(
505
- monitorSingleAccount({
506
- cfg: buildDebounceConfig(),
507
- account: buildDebounceAccount(),
508
- runtime: createNonExitingRuntimeEnv(),
509
- botOpenIdSource: {
510
- kind: "prefetched",
511
- botOpenId: "ou_bot",
512
- },
513
- }),
514
- ).rejects.toThrow("register failed");
515
-
516
- const manager = createFeishuThreadBindingManagerMock.mock.results[0]?.value as
517
- | { stop: ReturnType<typeof vi.fn> }
518
- | undefined;
519
- expect(manager?.stop).toHaveBeenCalledTimes(1);
520
- });
521
- });
522
-
523
- describe("Feishu inbound debounce regressions", () => {
524
- beforeEach(() => {
525
- vi.useFakeTimers();
526
- handlers = {};
527
- handleFeishuMessageMock.mockClear();
528
- setFeishuRuntime(createFeishuMonitorRuntime());
529
- });
530
-
531
- afterEach(() => {
532
- vi.useRealTimers();
533
- vi.restoreAllMocks();
534
- });
535
-
536
- it("keeps bot mention when per-message mention keys collide across non-forward messages", async () => {
537
- setDedupPassThroughMocks();
538
- const onMessage = await setupDebounceMonitor();
539
-
540
- await enqueueDebouncedMessage(
541
- onMessage,
542
- createTextEvent({
543
- messageId: "om_1",
544
- text: "first",
545
- mentions: [createMention({ openId: "ou_user_a", name: "user-a" })],
546
- }),
547
- );
548
- await enqueueDebouncedMessage(
549
- onMessage,
550
- createTextEvent({
551
- messageId: "om_2",
552
- text: "@bot second",
553
- mentions: [createMention({ openId: "ou_bot", name: "bot" })],
554
- }),
555
- );
556
- await vi.advanceTimersByTimeAsync(25);
557
-
558
- const dispatched = expectSingleDispatchedEvent();
559
- const mergedOpenIds = mentionOpenIds(dispatched);
560
- expect(mergedOpenIds).toContain("ou_bot");
561
- expect(mergedOpenIds).not.toContain("ou_user_a");
562
- });
563
-
564
- it("passes prefetched botName through to handleFeishuMessage", async () => {
565
- vi.spyOn(dedup, "tryBeginFeishuMessageProcessing").mockReturnValue(true);
566
- vi.spyOn(dedup, "recordProcessedFeishuMessage").mockResolvedValue(true);
567
- vi.spyOn(dedup, "hasProcessedFeishuMessage").mockResolvedValue(false);
568
- const onMessage = await setupDebounceMonitor({ botName: "Klaw Bot" });
569
-
570
- await onMessage(
571
- createTextEvent({
572
- messageId: "om_name_passthrough",
573
- text: "@bot hello",
574
- mentions: [
575
- {
576
- key: "@_user_1",
577
- id: { open_id: "ou_bot" },
578
- name: "Klaw Bot",
579
- },
580
- ],
581
- }),
582
- );
583
- await Promise.resolve();
584
- await Promise.resolve();
585
- await vi.advanceTimersByTimeAsync(25);
586
-
587
- expect(handleFeishuMessageMock).toHaveBeenCalledTimes(1);
588
- const firstParams = mockCallAt(handleFeishuMessageMock, 0, "Feishu message dispatch")[0] as
589
- | { botName?: string }
590
- | undefined;
591
- expect(firstParams?.botName).toBe("Klaw Bot");
592
- });
593
-
594
- it("does not synthesize mention-forward intent across separate messages", async () => {
595
- setDedupPassThroughMocks();
596
- const onMessage = await setupDebounceMonitor();
597
-
598
- await enqueueDebouncedMessage(
599
- onMessage,
600
- createTextEvent({
601
- messageId: "om_user_mention",
602
- text: "@alice first",
603
- mentions: [createMention({ openId: "ou_alice", name: "alice" })],
604
- }),
605
- );
606
- await enqueueDebouncedMessage(
607
- onMessage,
608
- createTextEvent({
609
- messageId: "om_bot_mention",
610
- text: "@bot second",
611
- mentions: [createMention({ openId: "ou_bot", name: "bot" })],
612
- }),
613
- );
614
- await vi.advanceTimersByTimeAsync(25);
615
-
616
- const { dispatched, parsed } = expectParsedFirstDispatchedEvent();
617
- expect(parsed.mentionedBot).toBe(true);
618
- expect(parsed.mentionTargets).toBeUndefined();
619
- expect(mentionOpenIds(dispatched)).toEqual(["ou_bot"]);
620
- });
621
-
622
- it("preserves bot mention signal when the latest merged message has no mentions", async () => {
623
- setDedupPassThroughMocks();
624
- const onMessage = await setupDebounceMonitor();
625
-
626
- await enqueueDebouncedMessage(
627
- onMessage,
628
- createTextEvent({
629
- messageId: "om_bot_first",
630
- text: "@bot first",
631
- mentions: [createMention({ openId: "ou_bot", name: "bot" })],
632
- }),
633
- );
634
- await enqueueDebouncedMessage(
635
- onMessage,
636
- createTextEvent({
637
- messageId: "om_plain_second",
638
- text: "plain follow-up",
639
- }),
640
- );
641
- await vi.advanceTimersByTimeAsync(25);
642
-
643
- const { parsed } = expectParsedFirstDispatchedEvent();
644
- expect(parsed.mentionedBot).toBe(true);
645
- });
646
-
647
- it("excludes previously processed retries from combined debounce text", async () => {
648
- vi.spyOn(dedup, "tryBeginFeishuMessageProcessing").mockReturnValue(true);
649
- vi.spyOn(dedup, "recordProcessedFeishuMessage").mockResolvedValue(true);
650
- setStaleRetryMocks();
651
- const onMessage = await setupDebounceMonitor();
652
-
653
- await onMessage(createTextEvent({ messageId: "om_old", text: "stale" }));
654
- await Promise.resolve();
655
- await Promise.resolve();
656
- await onMessage(createTextEvent({ messageId: "om_new_1", text: "first" }));
657
- await Promise.resolve();
658
- await Promise.resolve();
659
- await onMessage(createTextEvent({ messageId: "om_old", text: "stale" }));
660
- await Promise.resolve();
661
- await Promise.resolve();
662
- await onMessage(createTextEvent({ messageId: "om_new_2", text: "second" }));
663
- await Promise.resolve();
664
- await Promise.resolve();
665
- await vi.advanceTimersByTimeAsync(25);
666
-
667
- const dispatched = expectSingleDispatchedEvent();
668
- expect(dispatched.message.message_id).toBe("om_new_2");
669
- const combined = JSON.parse(dispatched.message.content) as { text?: string };
670
- expect(combined.text).toBe("first\nsecond");
671
- });
672
-
673
- it("uses latest fresh message id when debounce batch ends with stale retry", async () => {
674
- vi.spyOn(dedup, "tryBeginFeishuMessageProcessing").mockReturnValue(true);
675
- const recordSpy = vi.spyOn(dedup, "recordProcessedFeishuMessage").mockResolvedValue(true);
676
- setStaleRetryMocks("om_old_latest_fresh");
677
- const onMessage = await setupDebounceMonitor();
678
-
679
- await onMessage(createTextEvent({ messageId: "om_new_latest_fresh", text: "fresh" }));
680
- await Promise.resolve();
681
- await Promise.resolve();
682
- await onMessage(createTextEvent({ messageId: "om_old_latest_fresh", text: "stale" }));
683
- await Promise.resolve();
684
- await Promise.resolve();
685
- await vi.advanceTimersByTimeAsync(25);
686
-
687
- const dispatched = expectSingleDispatchedEvent();
688
- expect(dispatched.message.message_id).toBe("om_new_latest_fresh");
689
- const combined = JSON.parse(dispatched.message.content) as { text?: string };
690
- expect(combined.text).toBe("fresh");
691
- expect(recordSpy).toHaveBeenCalledTimes(1);
692
- const [recordedMessageId, recordedNamespace, recordedLogger] = mockCallAt(
693
- recordSpy,
694
- 0,
695
- "Feishu processed-message record",
696
- );
697
- expect(recordedMessageId).toBe("om_old_latest_fresh");
698
- expect(recordedNamespace).toBe("default");
699
- expect(typeof recordedLogger).toBe("function");
700
- });
701
-
702
- it("releases early event dedupe when debounced dispatch fails", async () => {
703
- setDedupPassThroughMocks();
704
- const enqueueMock = vi.fn();
705
- setFeishuRuntime(
706
- createFeishuMonitorRuntime({
707
- createInboundDebouncer: <T>(params: { onError?: (err: unknown, items: T[]) => void }) => ({
708
- enqueue: async (item: T) => {
709
- enqueueMock(item);
710
- params.onError?.(new Error("dispatch failed"), [item]);
711
- },
712
- flushKey: async () => {},
713
- cancelKey: () => false,
714
- }),
715
- }),
716
- );
717
- const onMessage = await setupDebounceMonitor();
718
- const event = createTextEvent({ messageId: "om_retryable", text: "hello" });
719
-
720
- await enqueueDebouncedMessage(onMessage, event);
721
- expect(enqueueMock).toHaveBeenCalledTimes(1);
722
-
723
- await enqueueDebouncedMessage(onMessage, event);
724
- expect(enqueueMock).toHaveBeenCalledTimes(2);
725
- expect(handleFeishuMessageMock).not.toHaveBeenCalled();
726
- });
727
-
728
- it("drops duplicate inbound events before they re-enter the debounce pipeline", async () => {
729
- const onMessage = await setupDebounceMonitor();
730
- const event = createTextEvent({ messageId: "om_duplicate", text: "hello" });
731
-
732
- await enqueueDebouncedMessage(onMessage, event);
733
- await vi.advanceTimersByTimeAsync(25);
734
- await enqueueDebouncedMessage(onMessage, event);
735
- await vi.advanceTimersByTimeAsync(25);
736
-
737
- expect(handleFeishuMessageMock).toHaveBeenCalledTimes(1);
738
- });
739
- });