@kodelyth/msteams 2026.5.42 → 2026.6.1

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 (177) hide show
  1. package/klaw.plugin.json +726 -2
  2. package/package.json +16 -4
  3. package/api.ts +0 -3
  4. package/channel-config-api.ts +0 -1
  5. package/channel-plugin-api.ts +0 -2
  6. package/config-api.ts +0 -4
  7. package/contract-api.ts +0 -4
  8. package/index.ts +0 -20
  9. package/runtime-api.ts +0 -66
  10. package/secret-contract-api.ts +0 -5
  11. package/setup-entry.ts +0 -13
  12. package/setup-plugin-api.ts +0 -3
  13. package/src/ai-entity.ts +0 -7
  14. package/src/approval-auth.ts +0 -44
  15. package/src/attachments/bot-framework.test.ts +0 -506
  16. package/src/attachments/bot-framework.ts +0 -348
  17. package/src/attachments/download.ts +0 -328
  18. package/src/attachments/graph.test.ts +0 -441
  19. package/src/attachments/graph.ts +0 -489
  20. package/src/attachments/html.ts +0 -122
  21. package/src/attachments/payload.ts +0 -14
  22. package/src/attachments/remote-media.test.ts +0 -187
  23. package/src/attachments/remote-media.ts +0 -86
  24. package/src/attachments/shared.test.ts +0 -547
  25. package/src/attachments/shared.ts +0 -655
  26. package/src/attachments/types.ts +0 -47
  27. package/src/attachments.graph.test.ts +0 -414
  28. package/src/attachments.helpers.test.ts +0 -245
  29. package/src/attachments.test-helpers.ts +0 -17
  30. package/src/attachments.test.ts +0 -754
  31. package/src/attachments.ts +0 -18
  32. package/src/block-streaming-config.test.ts +0 -61
  33. package/src/channel-api.ts +0 -1
  34. package/src/channel.actions.test.ts +0 -797
  35. package/src/channel.directory.test.ts +0 -176
  36. package/src/channel.message-adapter.test.ts +0 -227
  37. package/src/channel.runtime.ts +0 -56
  38. package/src/channel.setup.ts +0 -77
  39. package/src/channel.test.ts +0 -136
  40. package/src/channel.ts +0 -1176
  41. package/src/config-schema.ts +0 -6
  42. package/src/config-ui-hints.ts +0 -40
  43. package/src/conversation-store-fs.test.ts +0 -81
  44. package/src/conversation-store-fs.ts +0 -149
  45. package/src/conversation-store-helpers.test.ts +0 -202
  46. package/src/conversation-store-helpers.ts +0 -105
  47. package/src/conversation-store-memory.ts +0 -51
  48. package/src/conversation-store.shared.test.ts +0 -260
  49. package/src/conversation-store.ts +0 -71
  50. package/src/directory-live.test.ts +0 -156
  51. package/src/directory-live.ts +0 -111
  52. package/src/doctor.ts +0 -27
  53. package/src/errors.test.ts +0 -154
  54. package/src/errors.ts +0 -270
  55. package/src/feedback-reflection-prompt.ts +0 -117
  56. package/src/feedback-reflection-store.ts +0 -113
  57. package/src/feedback-reflection.test.ts +0 -237
  58. package/src/feedback-reflection.ts +0 -268
  59. package/src/file-consent-helpers.test.ts +0 -328
  60. package/src/file-consent-helpers.ts +0 -115
  61. package/src/file-consent-invoke.ts +0 -150
  62. package/src/file-consent.test.ts +0 -378
  63. package/src/file-consent.ts +0 -223
  64. package/src/graph-chat.ts +0 -36
  65. package/src/graph-group-management.test.ts +0 -332
  66. package/src/graph-group-management.ts +0 -168
  67. package/src/graph-members.test.ts +0 -89
  68. package/src/graph-members.ts +0 -48
  69. package/src/graph-messages.actions.test.ts +0 -253
  70. package/src/graph-messages.read.test.ts +0 -391
  71. package/src/graph-messages.search.test.ts +0 -227
  72. package/src/graph-messages.test-helpers.ts +0 -50
  73. package/src/graph-messages.ts +0 -534
  74. package/src/graph-teams.test.ts +0 -222
  75. package/src/graph-teams.ts +0 -114
  76. package/src/graph-thread.test.ts +0 -252
  77. package/src/graph-thread.ts +0 -146
  78. package/src/graph-upload.test.ts +0 -253
  79. package/src/graph-upload.ts +0 -531
  80. package/src/graph-users.ts +0 -29
  81. package/src/graph.test.ts +0 -540
  82. package/src/graph.ts +0 -308
  83. package/src/inbound.test.ts +0 -221
  84. package/src/inbound.ts +0 -148
  85. package/src/index.ts +0 -4
  86. package/src/media-helpers.test.ts +0 -220
  87. package/src/media-helpers.ts +0 -105
  88. package/src/mentions.test.ts +0 -254
  89. package/src/mentions.ts +0 -114
  90. package/src/messenger.test.ts +0 -961
  91. package/src/messenger.ts +0 -608
  92. package/src/monitor-handler/access.ts +0 -136
  93. package/src/monitor-handler/inbound-media.test.ts +0 -314
  94. package/src/monitor-handler/inbound-media.ts +0 -180
  95. package/src/monitor-handler/message-handler-mock-support.test-support.ts +0 -28
  96. package/src/monitor-handler/message-handler.authz.test.ts +0 -739
  97. package/src/monitor-handler/message-handler.dm-media.test.ts +0 -54
  98. package/src/monitor-handler/message-handler.test-support.ts +0 -99
  99. package/src/monitor-handler/message-handler.thread-parent.test.ts +0 -225
  100. package/src/monitor-handler/message-handler.thread-session.test.ts +0 -132
  101. package/src/monitor-handler/message-handler.ts +0 -1003
  102. package/src/monitor-handler/reaction-handler.test.ts +0 -325
  103. package/src/monitor-handler/reaction-handler.ts +0 -122
  104. package/src/monitor-handler/thread-session.ts +0 -30
  105. package/src/monitor-handler.adaptive-card.test.ts +0 -158
  106. package/src/monitor-handler.feedback-authz.test.ts +0 -357
  107. package/src/monitor-handler.file-consent.test.ts +0 -443
  108. package/src/monitor-handler.sso.test.ts +0 -576
  109. package/src/monitor-handler.test-helpers.ts +0 -181
  110. package/src/monitor-handler.ts +0 -538
  111. package/src/monitor-handler.types.ts +0 -27
  112. package/src/monitor-types.ts +0 -6
  113. package/src/monitor.lifecycle.test.ts +0 -457
  114. package/src/monitor.test.ts +0 -119
  115. package/src/monitor.ts +0 -476
  116. package/src/oauth.flow.ts +0 -77
  117. package/src/oauth.shared.ts +0 -37
  118. package/src/oauth.test.ts +0 -350
  119. package/src/oauth.token.ts +0 -162
  120. package/src/oauth.ts +0 -130
  121. package/src/outbound.test.ts +0 -400
  122. package/src/outbound.ts +0 -198
  123. package/src/pending-uploads-fs.test.ts +0 -261
  124. package/src/pending-uploads-fs.ts +0 -235
  125. package/src/pending-uploads.test.ts +0 -186
  126. package/src/pending-uploads.ts +0 -121
  127. package/src/policy.test.ts +0 -156
  128. package/src/policy.ts +0 -245
  129. package/src/polls-store-memory.ts +0 -32
  130. package/src/polls.test.ts +0 -169
  131. package/src/polls.ts +0 -312
  132. package/src/presentation.ts +0 -93
  133. package/src/probe.test.ts +0 -79
  134. package/src/probe.ts +0 -132
  135. package/src/reply-dispatcher.test.ts +0 -543
  136. package/src/reply-dispatcher.ts +0 -523
  137. package/src/reply-stream-controller.test.ts +0 -424
  138. package/src/reply-stream-controller.ts +0 -334
  139. package/src/resolve-allowlist.test.ts +0 -253
  140. package/src/resolve-allowlist.ts +0 -309
  141. package/src/revoked-context.ts +0 -17
  142. package/src/runtime.ts +0 -12
  143. package/src/sdk-types.ts +0 -59
  144. package/src/sdk.test.ts +0 -727
  145. package/src/sdk.ts +0 -916
  146. package/src/secret-contract.ts +0 -49
  147. package/src/secret-input.ts +0 -7
  148. package/src/send-context.test.ts +0 -93
  149. package/src/send-context.ts +0 -269
  150. package/src/send.test.ts +0 -588
  151. package/src/send.ts +0 -697
  152. package/src/sent-message-cache.test.ts +0 -106
  153. package/src/sent-message-cache.ts +0 -174
  154. package/src/session-route.ts +0 -40
  155. package/src/setup-core.ts +0 -162
  156. package/src/setup-surface.test.ts +0 -175
  157. package/src/setup-surface.ts +0 -319
  158. package/src/sso-token-store.test.ts +0 -74
  159. package/src/sso-token-store.ts +0 -166
  160. package/src/sso.ts +0 -300
  161. package/src/storage.ts +0 -25
  162. package/src/store-fs.ts +0 -42
  163. package/src/streaming-message.test.ts +0 -323
  164. package/src/streaming-message.ts +0 -327
  165. package/src/test-runtime.ts +0 -16
  166. package/src/thread-parent-context.test.ts +0 -224
  167. package/src/thread-parent-context.ts +0 -159
  168. package/src/token-response.ts +0 -11
  169. package/src/token.test.ts +0 -268
  170. package/src/token.ts +0 -194
  171. package/src/user-agent.test.ts +0 -121
  172. package/src/user-agent.ts +0 -53
  173. package/src/webhook-timeouts.ts +0 -27
  174. package/src/welcome-card.test.ts +0 -104
  175. package/src/welcome-card.ts +0 -57
  176. package/test-api.ts +0 -1
  177. package/tsconfig.json +0 -16
@@ -1,961 +0,0 @@
1
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
- import path from "node:path";
3
- import { SILENT_REPLY_TOKEN } from "klaw/plugin-sdk/reply-chunking";
4
- import type { PluginRuntime } from "klaw/plugin-sdk/runtime-store";
5
- import { resolvePreferredKlawTmpDir } from "klaw/plugin-sdk/temp-path";
6
- import { beforeEach, describe, expect, it, vi } from "vitest";
7
- import type { StoredConversationReference } from "./conversation-store.js";
8
- const graphUploadMockState = vi.hoisted(() => ({
9
- uploadAndShareOneDrive: vi.fn(),
10
- uploadAndShareSharePoint: vi.fn(),
11
- getDriveItemProperties: vi.fn(),
12
- }));
13
-
14
- vi.mock("./graph-upload.js", () => {
15
- return {
16
- uploadAndShareOneDrive: graphUploadMockState.uploadAndShareOneDrive,
17
- uploadAndShareSharePoint: graphUploadMockState.uploadAndShareSharePoint,
18
- getDriveItemProperties: graphUploadMockState.getDriveItemProperties,
19
- };
20
- });
21
-
22
- import {
23
- buildActivity,
24
- buildConversationReference,
25
- renderReplyPayloadsToMessages,
26
- sendMSTeamsMessages,
27
- type MSTeamsAdapter,
28
- } from "./messenger.js";
29
- import { setMSTeamsRuntime } from "./runtime.js";
30
-
31
- const chunkMarkdownText = (text: string, limit: number) => {
32
- if (!text) {
33
- return [];
34
- }
35
- if (limit <= 0 || text.length <= limit) {
36
- return [text];
37
- }
38
- const chunks: string[] = [];
39
- for (let index = 0; index < text.length; index += limit) {
40
- chunks.push(text.slice(index, index + limit));
41
- }
42
- return chunks;
43
- };
44
-
45
- const runtimeStub = {
46
- config: {
47
- loadConfig: () => ({}),
48
- },
49
- channel: {
50
- text: {
51
- chunkMarkdownText,
52
- chunkMarkdownTextWithMode: chunkMarkdownText,
53
- resolveMarkdownTableMode: () => "code",
54
- convertMarkdownTables: (text: string) => text,
55
- },
56
- },
57
- } as unknown as PluginRuntime;
58
-
59
- const noopUpdateActivity = async () => {};
60
- const noopDeleteActivity = async () => {};
61
-
62
- const createNoopAdapter = (): MSTeamsAdapter => ({
63
- continueConversation: async () => {},
64
- process: async () => {},
65
- updateActivity: noopUpdateActivity,
66
- deleteActivity: noopDeleteActivity,
67
- });
68
-
69
- const createRecordedSendActivity = (
70
- sink: string[],
71
- failFirstWithStatusCode?: number,
72
- ): ((activity: unknown) => Promise<{ id: string }>) => {
73
- let attempts = 0;
74
- return async (activity: unknown) => {
75
- const { text } = activity as { text?: string };
76
- const content = text ?? "";
77
- sink.push(content);
78
- attempts += 1;
79
- if (failFirstWithStatusCode !== undefined && attempts === 1) {
80
- throw Object.assign(new Error("send failed"), { statusCode: failFirstWithStatusCode });
81
- }
82
- return { id: `id:${content}` };
83
- };
84
- };
85
-
86
- const REVOCATION_ERROR = "Cannot perform 'set' on a proxy that has been revoked";
87
-
88
- function requireConversationId(ref: { conversation?: { id?: string } }) {
89
- if (!ref.conversation?.id) {
90
- throw new Error("expected Teams top-level send to preserve conversation id");
91
- }
92
- return ref.conversation.id;
93
- }
94
-
95
- function requireSentMessage(sent: Array<{ text?: string; entities?: unknown[] }>) {
96
- const firstSent = sent[0];
97
- if (!firstSent?.text) {
98
- throw new Error("expected Teams message send to include rendered text");
99
- }
100
- return firstSent;
101
- }
102
-
103
- function findEntity(
104
- entities: unknown,
105
- predicate: (entity: Record<string, unknown>) => boolean,
106
- ): Record<string, unknown> | undefined {
107
- return (entities as Array<Record<string, unknown>> | undefined)?.find(predicate);
108
- }
109
-
110
- function requireAiGeneratedEntity(entities: unknown): Record<string, unknown> {
111
- const entity = findEntity(
112
- entities,
113
- (candidate) =>
114
- Array.isArray(candidate.additionalType) &&
115
- candidate.additionalType.includes("AIGeneratedContent"),
116
- );
117
- if (!entity) {
118
- throw new Error("expected Teams AI-generated entity");
119
- }
120
- return entity;
121
- }
122
-
123
- function requireMentionEntity(entities: unknown): Record<string, unknown> {
124
- const entity = findEntity(entities, (candidate) => candidate.type === "mention");
125
- if (!entity) {
126
- throw new Error("expected Teams mention entity");
127
- }
128
- return entity;
129
- }
130
-
131
- const createFallbackAdapter = (proactiveSent: string[]): MSTeamsAdapter => ({
132
- continueConversation: async (_appId, _reference, logic) => {
133
- await logic({
134
- sendActivity: createRecordedSendActivity(proactiveSent),
135
- updateActivity: noopUpdateActivity,
136
- deleteActivity: noopDeleteActivity,
137
- });
138
- },
139
- process: async () => {},
140
- updateActivity: noopUpdateActivity,
141
- deleteActivity: noopDeleteActivity,
142
- });
143
-
144
- describe("msteams messenger", () => {
145
- beforeEach(() => {
146
- setMSTeamsRuntime(runtimeStub);
147
- graphUploadMockState.uploadAndShareOneDrive.mockReset();
148
- graphUploadMockState.uploadAndShareSharePoint.mockReset();
149
- graphUploadMockState.getDriveItemProperties.mockReset();
150
- graphUploadMockState.uploadAndShareOneDrive.mockResolvedValue({
151
- itemId: "item123",
152
- webUrl: "https://onedrive.example.com/item123",
153
- shareUrl: "https://onedrive.example.com/share/item123",
154
- name: "upload.txt",
155
- });
156
- });
157
-
158
- describe("renderReplyPayloadsToMessages", () => {
159
- it("filters silent replies", () => {
160
- const messages = renderReplyPayloadsToMessages([{ text: SILENT_REPLY_TOKEN }], {
161
- textChunkLimit: 4000,
162
- tableMode: "code",
163
- });
164
- expect(messages).toStrictEqual([]);
165
- });
166
-
167
- it("does not filter non-exact silent reply prefixes", () => {
168
- const messages = renderReplyPayloadsToMessages(
169
- [{ text: `${SILENT_REPLY_TOKEN} -- ignored` }],
170
- { textChunkLimit: 4000, tableMode: "code" },
171
- );
172
- expect(messages).toEqual([{ text: `${SILENT_REPLY_TOKEN} -- ignored` }]);
173
- });
174
-
175
- it("splits media into separate messages by default", () => {
176
- const messages = renderReplyPayloadsToMessages(
177
- [{ text: "hi", mediaUrl: "https://example.com/a.png" }],
178
- { textChunkLimit: 4000, tableMode: "code" },
179
- );
180
- expect(messages).toEqual([{ text: "hi" }, { mediaUrl: "https://example.com/a.png" }]);
181
- });
182
-
183
- it("supports inline media mode", () => {
184
- const messages = renderReplyPayloadsToMessages(
185
- [{ text: "hi", mediaUrl: "https://example.com/a.png" }],
186
- { textChunkLimit: 4000, mediaMode: "inline", tableMode: "code" },
187
- );
188
- expect(messages).toEqual([{ text: "hi", mediaUrl: "https://example.com/a.png" }]);
189
- });
190
-
191
- it("chunks long text when enabled", () => {
192
- const long = "hello ".repeat(200);
193
- const messages = renderReplyPayloadsToMessages([{ text: long }], {
194
- textChunkLimit: 50,
195
- tableMode: "code",
196
- });
197
- expect(messages.length).toBeGreaterThan(1);
198
- });
199
- });
200
-
201
- describe("sendMSTeamsMessages", () => {
202
- function createRevokedThreadContext(params?: { failAfterAttempt?: number; sent?: string[] }) {
203
- let attempt = 0;
204
- return {
205
- sendActivity: async (activity: unknown) => {
206
- const { text } = activity as { text?: string };
207
- const content = text ?? "";
208
- attempt += 1;
209
- if (params?.failAfterAttempt && attempt < params.failAfterAttempt) {
210
- params.sent?.push(content);
211
- return { id: `id:${content}` };
212
- }
213
- throw new TypeError(REVOCATION_ERROR);
214
- },
215
- updateActivity: noopUpdateActivity,
216
- deleteActivity: noopDeleteActivity,
217
- };
218
- }
219
-
220
- const baseRef: StoredConversationReference = {
221
- activityId: "activity123",
222
- user: { id: "user123", name: "User" },
223
- agent: { id: "bot123", name: "Bot" },
224
- conversation: { id: "19:abc@thread.tacv2;messageid=deadbeef" },
225
- channelId: "msteams",
226
- serviceUrl: "https://service.example.com",
227
- };
228
-
229
- async function sendAndCaptureRevokeFallbackReference(params: {
230
- conversation: StoredConversationReference["conversation"];
231
- activityId?: string;
232
- threadId?: string;
233
- }) {
234
- const proactiveSent: string[] = [];
235
- let capturedReference: unknown;
236
- const conversationRef: StoredConversationReference = {
237
- activityId: params.activityId ?? "activity456",
238
- user: { id: "user123", name: "User" },
239
- agent: { id: "bot123", name: "Bot" },
240
- conversation: params.conversation,
241
- channelId: "msteams",
242
- serviceUrl: "https://service.example.com",
243
- ...(params.threadId ? { threadId: params.threadId } : {}),
244
- };
245
- const adapter: MSTeamsAdapter = {
246
- continueConversation: async (_appId, reference, logic) => {
247
- capturedReference = reference;
248
- await logic({
249
- sendActivity: createRecordedSendActivity(proactiveSent),
250
- updateActivity: noopUpdateActivity,
251
- deleteActivity: noopDeleteActivity,
252
- });
253
- },
254
- process: async () => {},
255
- updateActivity: noopUpdateActivity,
256
- deleteActivity: noopDeleteActivity,
257
- };
258
-
259
- await sendMSTeamsMessages({
260
- replyStyle: "thread",
261
- adapter,
262
- appId: "app123",
263
- conversationRef,
264
- context: createRevokedThreadContext(),
265
- messages: [{ text: "hello" }],
266
- });
267
-
268
- return {
269
- proactiveSent,
270
- reference: capturedReference as { conversation?: { id?: string }; activityId?: string },
271
- };
272
- }
273
-
274
- it("sends thread messages via the provided context", async () => {
275
- const sent: string[] = [];
276
- const ctx = {
277
- sendActivity: createRecordedSendActivity(sent),
278
- updateActivity: noopUpdateActivity,
279
- deleteActivity: noopDeleteActivity,
280
- };
281
- const adapter = createNoopAdapter();
282
-
283
- const ids = await sendMSTeamsMessages({
284
- replyStyle: "thread",
285
- adapter,
286
- appId: "app123",
287
- conversationRef: baseRef,
288
- context: ctx,
289
- messages: [{ text: "one" }, { text: "two" }],
290
- });
291
-
292
- expect(sent).toEqual(["one", "two"]);
293
- expect(ids).toEqual(["id:one", "id:two"]);
294
- });
295
-
296
- it("sends top-level messages via continueConversation and strips activityId", async () => {
297
- const seen: { reference?: unknown; texts: string[] } = { texts: [] };
298
-
299
- const adapter: MSTeamsAdapter = {
300
- continueConversation: async (_appId, reference, logic) => {
301
- seen.reference = reference;
302
- await logic({
303
- sendActivity: createRecordedSendActivity(seen.texts),
304
- updateActivity: noopUpdateActivity,
305
- deleteActivity: noopDeleteActivity,
306
- });
307
- },
308
- process: async () => {},
309
- updateActivity: noopUpdateActivity,
310
- deleteActivity: noopDeleteActivity,
311
- };
312
-
313
- const ids = await sendMSTeamsMessages({
314
- replyStyle: "top-level",
315
- adapter,
316
- appId: "app123",
317
- conversationRef: baseRef,
318
- messages: [{ text: "hello" }],
319
- });
320
-
321
- expect(seen.texts).toEqual(["hello"]);
322
- expect(ids).toEqual(["id:hello"]);
323
-
324
- const ref = seen.reference as {
325
- activityId?: string;
326
- conversation?: { id?: string };
327
- };
328
- expect(ref.activityId).toBeUndefined();
329
- expect(requireConversationId(ref)).toBe("19:abc@thread.tacv2");
330
- });
331
-
332
- it("preserves parsed mentions when appending OneDrive fallback file links", async () => {
333
- const tmpDir = await mkdtemp(path.join(resolvePreferredKlawTmpDir(), "msteams-mention-"));
334
- const localFile = path.join(tmpDir, "note.txt");
335
- await writeFile(localFile, "hello");
336
-
337
- try {
338
- const sent: Array<{ text?: string; entities?: unknown[] }> = [];
339
- const ctx = {
340
- sendActivity: async (activity: unknown) => {
341
- sent.push(activity as { text?: string; entities?: unknown[] });
342
- return { id: "id:one" };
343
- },
344
- updateActivity: noopUpdateActivity,
345
- deleteActivity: noopDeleteActivity,
346
- };
347
-
348
- const adapter = createNoopAdapter();
349
-
350
- const ids = await sendMSTeamsMessages({
351
- replyStyle: "thread",
352
- adapter,
353
- appId: "app123",
354
- conversationRef: {
355
- ...baseRef,
356
- conversation: {
357
- ...baseRef.conversation,
358
- conversationType: "channel",
359
- },
360
- },
361
- context: ctx,
362
- messages: [{ text: "Hello @[John](29:08q2j2o3jc09au90eucae)", mediaUrl: localFile }],
363
- tokenProvider: {
364
- getAccessToken: async () => "token",
365
- },
366
- });
367
-
368
- expect(ids).toEqual(["id:one"]);
369
- expect(graphUploadMockState.uploadAndShareOneDrive).toHaveBeenCalledOnce();
370
- expect(sent).toHaveLength(1);
371
- const firstSent = requireSentMessage(sent);
372
- expect(firstSent.text).toContain("Hello <at>John</at>");
373
- expect(firstSent.text).toContain(
374
- "📎 [upload.txt](https://onedrive.example.com/share/item123)",
375
- );
376
- const mentionEntity = requireMentionEntity(sent[0]?.entities);
377
- expect(mentionEntity.text).toBe("<at>John</at>");
378
- expect(mentionEntity.mentioned).toEqual({
379
- id: "29:08q2j2o3jc09au90eucae",
380
- name: "John",
381
- });
382
- expect(requireAiGeneratedEntity(sent[0]?.entities).additionalType).toEqual([
383
- "AIGeneratedContent",
384
- ]);
385
- } finally {
386
- await rm(tmpDir, { recursive: true, force: true });
387
- }
388
- });
389
-
390
- it("retries thread sends on throttling (429)", async () => {
391
- const attempts: string[] = [];
392
- const retryEvents: Array<{ nextAttempt: number; delayMs: number }> = [];
393
-
394
- const ctx = {
395
- sendActivity: createRecordedSendActivity(attempts, 429),
396
- updateActivity: noopUpdateActivity,
397
- deleteActivity: noopDeleteActivity,
398
- };
399
- const adapter = createNoopAdapter();
400
-
401
- const ids = await sendMSTeamsMessages({
402
- replyStyle: "thread",
403
- adapter,
404
- appId: "app123",
405
- conversationRef: baseRef,
406
- context: ctx,
407
- messages: [{ text: "one" }],
408
- retry: { maxAttempts: 2, baseDelayMs: 0, maxDelayMs: 0 },
409
- onRetry: (e) => retryEvents.push({ nextAttempt: e.nextAttempt, delayMs: e.delayMs }),
410
- });
411
-
412
- expect(attempts).toEqual(["one", "one"]);
413
- expect(ids).toEqual(["id:one"]);
414
- expect(retryEvents).toEqual([{ nextAttempt: 2, delayMs: 0 }]);
415
- });
416
-
417
- it("retries full activity preparation when media upload fails transiently", async () => {
418
- const tmpDir = await mkdtemp(path.join(resolvePreferredKlawTmpDir(), "msteams-retry-"));
419
- const localFile = path.join(tmpDir, "retry.txt");
420
- await writeFile(localFile, "hello");
421
-
422
- try {
423
- const attempts: string[] = [];
424
- const retryEvents: Array<{ nextAttempt: number; delayMs: number }> = [];
425
- let uploadAttempts = 0;
426
- graphUploadMockState.uploadAndShareOneDrive.mockImplementation(async () => {
427
- uploadAttempts += 1;
428
- if (uploadAttempts === 1) {
429
- throw Object.assign(new Error("transient upload failure"), { statusCode: 429 });
430
- }
431
- return {
432
- itemId: "item123",
433
- webUrl: "https://onedrive.example.com/item123",
434
- shareUrl: "https://onedrive.example.com/share/item123",
435
- name: "retry.txt",
436
- };
437
- });
438
-
439
- const ctx = {
440
- sendActivity: createRecordedSendActivity(attempts),
441
- updateActivity: noopUpdateActivity,
442
- deleteActivity: noopDeleteActivity,
443
- };
444
- const adapter = createNoopAdapter();
445
-
446
- const ids = await sendMSTeamsMessages({
447
- replyStyle: "thread",
448
- adapter,
449
- appId: "app123",
450
- conversationRef: {
451
- ...baseRef,
452
- conversation: {
453
- ...baseRef.conversation,
454
- conversationType: "channel",
455
- },
456
- },
457
- context: ctx,
458
- messages: [{ text: "one", mediaUrl: localFile }],
459
- tokenProvider: {
460
- getAccessToken: async () => "token",
461
- },
462
- retry: { maxAttempts: 2, baseDelayMs: 0, maxDelayMs: 0 },
463
- onRetry: (e) => retryEvents.push({ nextAttempt: e.nextAttempt, delayMs: e.delayMs }),
464
- });
465
-
466
- expect(uploadAttempts).toBe(2);
467
- expect(attempts).toHaveLength(1);
468
- expect(attempts[0]).toContain("📎 [retry.txt]");
469
- expect(ids).toEqual([`id:${attempts[0]}`]);
470
- expect(retryEvents).toEqual([{ nextAttempt: 2, delayMs: 0 }]);
471
- } finally {
472
- await rm(tmpDir, { recursive: true, force: true });
473
- }
474
- });
475
-
476
- it("does not retry thread sends on client errors (4xx)", async () => {
477
- const ctx = {
478
- sendActivity: async () => {
479
- throw Object.assign(new Error("bad request"), { statusCode: 400 });
480
- },
481
- updateActivity: noopUpdateActivity,
482
- deleteActivity: noopDeleteActivity,
483
- };
484
-
485
- const adapter = createNoopAdapter();
486
-
487
- try {
488
- await sendMSTeamsMessages({
489
- replyStyle: "thread",
490
- adapter,
491
- appId: "app123",
492
- conversationRef: baseRef,
493
- context: ctx,
494
- messages: [{ text: "one" }],
495
- retry: { maxAttempts: 3, baseDelayMs: 0, maxDelayMs: 0 },
496
- });
497
- throw new Error("expected Teams send client error");
498
- } catch (error) {
499
- expect((error as { statusCode?: unknown }).statusCode).toBe(400);
500
- }
501
- });
502
-
503
- it("falls back to proactive messaging when thread context is revoked", async () => {
504
- const proactiveSent: string[] = [];
505
- const ctx = createRevokedThreadContext();
506
- const adapter = createFallbackAdapter(proactiveSent);
507
-
508
- const ids = await sendMSTeamsMessages({
509
- replyStyle: "thread",
510
- adapter,
511
- appId: "app123",
512
- conversationRef: baseRef,
513
- context: ctx,
514
- messages: [{ text: "hello" }],
515
- });
516
-
517
- // Should have fallen back to proactive messaging
518
- expect(proactiveSent).toEqual(["hello"]);
519
- expect(ids).toEqual(["id:hello"]);
520
- });
521
-
522
- it("falls back only for remaining thread messages after context revocation", async () => {
523
- const threadSent: string[] = [];
524
- const proactiveSent: string[] = [];
525
- const ctx = createRevokedThreadContext({ failAfterAttempt: 2, sent: threadSent });
526
- const adapter = createFallbackAdapter(proactiveSent);
527
-
528
- const ids = await sendMSTeamsMessages({
529
- replyStyle: "thread",
530
- adapter,
531
- appId: "app123",
532
- conversationRef: baseRef,
533
- context: ctx,
534
- messages: [{ text: "one" }, { text: "two" }, { text: "three" }],
535
- });
536
-
537
- expect(threadSent).toEqual(["one"]);
538
- expect(proactiveSent).toEqual(["two", "three"]);
539
- expect(ids).toEqual(["id:one", "id:two", "id:three"]);
540
- });
541
-
542
- it("reconstructs threaded conversation ID for channel revoke fallback", async () => {
543
- const { proactiveSent, reference } = await sendAndCaptureRevokeFallbackReference({
544
- conversation: {
545
- id: "19:abc@thread.tacv2;messageid=deadbeef",
546
- conversationType: "channel",
547
- },
548
- });
549
-
550
- expect(proactiveSent).toEqual(["hello"]);
551
- // Conversation ID should include the thread suffix for channel messages
552
- expect(reference.conversation?.id).toBe("19:abc@thread.tacv2;messageid=activity456");
553
- expect(reference.activityId).toBeUndefined();
554
- });
555
-
556
- it("does not add thread suffix for group chat revoke fallback", async () => {
557
- const { proactiveSent, reference } = await sendAndCaptureRevokeFallbackReference({
558
- conversation: {
559
- id: "19:group123@thread.v2",
560
- conversationType: "groupChat",
561
- },
562
- });
563
-
564
- expect(proactiveSent).toEqual(["hello"]);
565
- // Group chat should NOT have thread suffix — flat conversation
566
- expect(reference.conversation?.id).toBe("19:group123@thread.v2");
567
- expect(reference.activityId).toBeUndefined();
568
- });
569
-
570
- it("uses threadId instead of activityId for channel revoke fallback (#58030)", async () => {
571
- const { proactiveSent, reference } = await sendAndCaptureRevokeFallbackReference({
572
- activityId: "current-message-id",
573
- conversation: {
574
- id: "19:abc@thread.tacv2",
575
- conversationType: "channel",
576
- },
577
- // threadId is the thread root, which differs from activityId (current message)
578
- threadId: "thread-root-msg-id",
579
- });
580
-
581
- expect(proactiveSent).toEqual(["hello"]);
582
- // Should use threadId (thread root), NOT activityId (current message)
583
- expect(reference.conversation?.id).toBe("19:abc@thread.tacv2;messageid=thread-root-msg-id");
584
- expect(reference.activityId).toBeUndefined();
585
- });
586
-
587
- it("falls back to activityId when threadId is not set (backward compat)", async () => {
588
- const { proactiveSent, reference } = await sendAndCaptureRevokeFallbackReference({
589
- activityId: "legacy-activity-id",
590
- conversation: {
591
- id: "19:abc@thread.tacv2",
592
- conversationType: "channel",
593
- },
594
- // No threadId — older stored references may not have it
595
- });
596
-
597
- expect(proactiveSent).toEqual(["hello"]);
598
- // Falls back to activityId when threadId is missing
599
- expect(reference.conversation?.id).toBe("19:abc@thread.tacv2;messageid=legacy-activity-id");
600
- });
601
-
602
- it("sends no-context thread replies proactively with the channel thread root", async () => {
603
- let capturedReference: unknown;
604
- const sent: string[] = [];
605
- const channelRef: StoredConversationReference = {
606
- activityId: "current-msg",
607
- user: { id: "user123", name: "User" },
608
- agent: { id: "bot123", name: "Bot" },
609
- conversation: {
610
- id: "19:abc@thread.tacv2",
611
- conversationType: "channel",
612
- },
613
- channelId: "msteams",
614
- serviceUrl: "https://service.example.com",
615
- threadId: "thread-root-msg-id",
616
- };
617
-
618
- const adapter: MSTeamsAdapter = {
619
- continueConversation: async (_appId, reference, logic) => {
620
- capturedReference = reference;
621
- await logic({
622
- sendActivity: createRecordedSendActivity(sent),
623
- updateActivity: noopUpdateActivity,
624
- deleteActivity: noopDeleteActivity,
625
- });
626
- },
627
- process: async () => {},
628
- updateActivity: noopUpdateActivity,
629
- deleteActivity: noopDeleteActivity,
630
- };
631
-
632
- const ids = await sendMSTeamsMessages({
633
- replyStyle: "thread",
634
- adapter,
635
- appId: "app123",
636
- conversationRef: channelRef,
637
- messages: [{ text: "hello" }],
638
- });
639
-
640
- expect(sent).toEqual(["hello"]);
641
- expect(ids).toEqual(["id:hello"]);
642
- const ref = capturedReference as { conversation?: { id?: string }; activityId?: string };
643
- expect(ref.conversation?.id).toBe("19:abc@thread.tacv2;messageid=thread-root-msg-id");
644
- expect(ref.activityId).toBeUndefined();
645
- });
646
-
647
- it("uses activityId for no-context thread replies when threadId is absent", async () => {
648
- let capturedReference: unknown;
649
- const sent: string[] = [];
650
- const channelRef: StoredConversationReference = {
651
- activityId: "legacy-activity-id",
652
- user: { id: "user123", name: "User" },
653
- agent: { id: "bot123", name: "Bot" },
654
- conversation: {
655
- id: "19:abc@thread.tacv2",
656
- conversationType: "channel",
657
- },
658
- channelId: "msteams",
659
- serviceUrl: "https://service.example.com",
660
- };
661
-
662
- const adapter: MSTeamsAdapter = {
663
- continueConversation: async (_appId, reference, logic) => {
664
- capturedReference = reference;
665
- await logic({
666
- sendActivity: createRecordedSendActivity(sent),
667
- updateActivity: noopUpdateActivity,
668
- deleteActivity: noopDeleteActivity,
669
- });
670
- },
671
- process: async () => {},
672
- updateActivity: noopUpdateActivity,
673
- deleteActivity: noopDeleteActivity,
674
- };
675
-
676
- await sendMSTeamsMessages({
677
- replyStyle: "thread",
678
- adapter,
679
- appId: "app123",
680
- conversationRef: channelRef,
681
- messages: [{ text: "hello" }],
682
- });
683
-
684
- const ref = capturedReference as { conversation?: { id?: string }; activityId?: string };
685
- expect(sent).toEqual(["hello"]);
686
- expect(ref.conversation?.id).toBe("19:abc@thread.tacv2;messageid=legacy-activity-id");
687
- expect(ref.activityId).toBeUndefined();
688
- });
689
-
690
- it("does not add thread suffix for top-level replyStyle even with threadId set", async () => {
691
- let capturedReference: unknown;
692
- const sent: string[] = [];
693
-
694
- const channelRef: StoredConversationReference = {
695
- activityId: "current-msg",
696
- user: { id: "user123", name: "User" },
697
- agent: { id: "bot123", name: "Bot" },
698
- conversation: {
699
- id: "19:abc@thread.tacv2",
700
- conversationType: "channel",
701
- },
702
- channelId: "msteams",
703
- serviceUrl: "https://service.example.com",
704
- threadId: "thread-root-msg-id",
705
- };
706
-
707
- const adapter: MSTeamsAdapter = {
708
- continueConversation: async (_appId, reference, logic) => {
709
- capturedReference = reference;
710
- await logic({
711
- sendActivity: createRecordedSendActivity(sent),
712
- updateActivity: noopUpdateActivity,
713
- deleteActivity: noopDeleteActivity,
714
- });
715
- },
716
- process: async () => {},
717
- updateActivity: noopUpdateActivity,
718
- deleteActivity: noopDeleteActivity,
719
- };
720
-
721
- await sendMSTeamsMessages({
722
- replyStyle: "top-level",
723
- adapter,
724
- appId: "app123",
725
- conversationRef: channelRef,
726
- messages: [{ text: "hello" }],
727
- });
728
-
729
- expect(sent).toEqual(["hello"]);
730
- const ref = capturedReference as { conversation?: { id?: string } };
731
- // Top-level sends should NOT include thread suffix
732
- expect(ref.conversation?.id).toBe("19:abc@thread.tacv2");
733
- });
734
-
735
- it("retries top-level sends on transient (5xx)", async () => {
736
- const attempts: string[] = [];
737
-
738
- const adapter: MSTeamsAdapter = {
739
- continueConversation: async (_appId, _reference, logic) => {
740
- await logic({
741
- sendActivity: createRecordedSendActivity(attempts, 503),
742
- updateActivity: noopUpdateActivity,
743
- deleteActivity: noopDeleteActivity,
744
- });
745
- },
746
- process: async () => {},
747
- updateActivity: noopUpdateActivity,
748
- deleteActivity: noopDeleteActivity,
749
- };
750
-
751
- const ids = await sendMSTeamsMessages({
752
- replyStyle: "top-level",
753
- adapter,
754
- appId: "app123",
755
- conversationRef: baseRef,
756
- messages: [{ text: "hello" }],
757
- retry: { maxAttempts: 2, baseDelayMs: 0, maxDelayMs: 0 },
758
- });
759
-
760
- expect(attempts).toEqual(["hello", "hello"]);
761
- expect(ids).toEqual(["id:hello"]);
762
- });
763
-
764
- it("delivers all blocks in a multi-block reply via a single continueConversation call (#29379)", async () => {
765
- // Regression: multiple text blocks (e.g. text -> tool -> text) must all
766
- // reach the user. Previously each deliver() call opened a separate
767
- // continueConversation(); Teams silently drops blocks 2+ in that case.
768
- // The fix batches all rendered messages into one sendMSTeamsMessages call
769
- // so they share a single continueConversation().
770
- const conversationCallTexts: string[][] = [];
771
- const adapter: MSTeamsAdapter = {
772
- continueConversation: async (_appId, _reference, logic) => {
773
- const batchTexts: string[] = [];
774
- await logic({
775
- sendActivity: async (activity: unknown) => {
776
- const { text } = activity as { text?: string };
777
- batchTexts.push(text ?? "");
778
- return { id: `id:${text ?? ""}` };
779
- },
780
- updateActivity: noopUpdateActivity,
781
- deleteActivity: noopDeleteActivity,
782
- });
783
- conversationCallTexts.push(batchTexts);
784
- },
785
- process: async () => {},
786
- updateActivity: noopUpdateActivity,
787
- deleteActivity: noopDeleteActivity,
788
- };
789
-
790
- // Three blocks (text + code + text) sent together in one call.
791
- const ids = await sendMSTeamsMessages({
792
- replyStyle: "top-level",
793
- adapter,
794
- appId: "app123",
795
- conversationRef: baseRef,
796
- messages: [
797
- { text: "Let me look that up..." },
798
- { text: "```\nresult = 42\n```" },
799
- { text: "The answer is 42." },
800
- ],
801
- });
802
-
803
- // All three blocks delivered.
804
- expect(ids).toHaveLength(3);
805
- // All three arrive in a single continueConversation() call, not three.
806
- expect(conversationCallTexts).toHaveLength(1);
807
- expect(conversationCallTexts[0]).toEqual([
808
- "Let me look that up...",
809
- "```\nresult = 42\n```",
810
- "The answer is 42.",
811
- ]);
812
- });
813
- });
814
-
815
- describe("buildActivity AI metadata", () => {
816
- const baseRef: StoredConversationReference = {
817
- activityId: "activity123",
818
- user: { id: "user123", name: "User" },
819
- agent: { id: "bot123", name: "Bot" },
820
- conversation: { id: "conv123", conversationType: "personal" },
821
- channelId: "msteams",
822
- serviceUrl: "https://service.example.com",
823
- };
824
-
825
- it("adds AI-generated entity to text messages", async () => {
826
- const activity = await buildActivity({ text: "hello" }, baseRef);
827
- const aiEntity = requireAiGeneratedEntity(activity.entities);
828
- expect(aiEntity.type).toBe("https://schema.org/Message");
829
- expect(aiEntity["@type"]).toBe("Message");
830
- expect(aiEntity.additionalType).toEqual(["AIGeneratedContent"]);
831
- });
832
-
833
- it("adds AI-generated entity to media-only messages", async () => {
834
- const activity = await buildActivity({ mediaUrl: "https://example.com/img.png" }, baseRef);
835
- expect(requireAiGeneratedEntity(activity.entities).additionalType).toEqual([
836
- "AIGeneratedContent",
837
- ]);
838
- });
839
-
840
- it("preserves mention entities alongside AI entity", async () => {
841
- const activity = await buildActivity({ text: "hi <at>@User</at>" }, baseRef);
842
- const entities = activity.entities as Array<Record<string, unknown>>;
843
- // Should have at least the AI entity
844
- expect(entities.length).toBeGreaterThanOrEqual(1);
845
- expect(requireAiGeneratedEntity(entities).additionalType).toEqual(["AIGeneratedContent"]);
846
- });
847
-
848
- it("sets feedbackLoopEnabled in channelData when enabled", async () => {
849
- const activity = await buildActivity(
850
- { text: "hello" },
851
- baseRef,
852
- undefined,
853
- undefined,
854
- undefined,
855
- {
856
- feedbackLoopEnabled: true,
857
- },
858
- );
859
- const channelData = activity.channelData as Record<string, unknown>;
860
- expect(channelData.feedbackLoopEnabled).toBe(true);
861
- });
862
-
863
- it("defaults feedbackLoopEnabled to false", async () => {
864
- const activity = await buildActivity({ text: "hello" }, baseRef);
865
- const channelData = activity.channelData as Record<string, unknown>;
866
- expect(channelData.feedbackLoopEnabled).toBe(false);
867
- });
868
- });
869
-
870
- // Regression coverage for #58774: proactive Teams sends fail with HTTP 403
871
- // when the Bot Framework connector does not see `tenantId` / `aadObjectId`
872
- // on the outbound conversation reference.
873
- describe("buildConversationReference tenant/aad forwarding (#58774)", () => {
874
- const storedWithChannelDataTenant: StoredConversationReference = {
875
- activityId: "activity-1",
876
- user: { id: "user123", name: "User", aadObjectId: "aad-user-123" },
877
- agent: { id: "bot123", name: "Bot" },
878
- conversation: {
879
- id: "19:abc@thread.tacv2",
880
- conversationType: "channel",
881
- },
882
- // Canonical channelData source captured by message-handler inbound code.
883
- tenantId: "tenant-abc",
884
- aadObjectId: "aad-user-123",
885
- channelId: "msteams",
886
- serviceUrl: "https://smba.trafficmanager.net/amer/",
887
- };
888
-
889
- it("forwards top-level tenantId and aadObjectId onto the outbound reference", () => {
890
- const reference = buildConversationReference(storedWithChannelDataTenant);
891
- expect(reference.tenantId).toBe("tenant-abc");
892
- expect(reference.aadObjectId).toBe("aad-user-123");
893
- expect(reference.conversation.tenantId).toBe("tenant-abc");
894
- expect(reference.user?.aadObjectId).toBe("aad-user-123");
895
- });
896
-
897
- it("falls back to conversation.tenantId when no top-level tenantId is stored (legacy ref)", () => {
898
- const legacy: StoredConversationReference = {
899
- activityId: "activity-legacy",
900
- user: { id: "user-legacy", name: "Legacy", aadObjectId: "aad-legacy" },
901
- agent: { id: "bot-legacy", name: "Bot" },
902
- conversation: {
903
- id: "a:personal-chat",
904
- conversationType: "personal",
905
- tenantId: "tenant-legacy",
906
- },
907
- channelId: "msteams",
908
- serviceUrl: "https://smba.trafficmanager.net/amer/",
909
- };
910
- const reference = buildConversationReference(legacy);
911
- expect(reference.tenantId).toBe("tenant-legacy");
912
- expect(reference.aadObjectId).toBe("aad-legacy");
913
- });
914
-
915
- it("omits tenantId and aadObjectId when neither source is available", () => {
916
- const minimal: StoredConversationReference = {
917
- activityId: "activity-2",
918
- user: { id: "user456", name: "User" },
919
- agent: { id: "bot456", name: "Bot" },
920
- conversation: { id: "19:xyz@thread.tacv2", conversationType: "channel" },
921
- channelId: "msteams",
922
- serviceUrl: "https://smba.trafficmanager.net/amer/",
923
- };
924
- const reference = buildConversationReference(minimal);
925
- expect(reference.tenantId).toBeUndefined();
926
- expect(reference.aadObjectId).toBeUndefined();
927
- expect(reference.conversation.tenantId).toBeUndefined();
928
- });
929
-
930
- it("propagates tenantId/aadObjectId through sendMSTeamsMessages proactive path", async () => {
931
- let capturedReference:
932
- | { tenantId?: string; aadObjectId?: string; user?: { aadObjectId?: string } }
933
- | undefined;
934
- const adapter: MSTeamsAdapter = {
935
- continueConversation: async (_appId, reference, logic) => {
936
- capturedReference = reference as typeof capturedReference;
937
- await logic({
938
- sendActivity: async () => ({ id: "ok" }),
939
- updateActivity: noopUpdateActivity,
940
- deleteActivity: noopDeleteActivity,
941
- });
942
- },
943
- process: async () => {},
944
- updateActivity: noopUpdateActivity,
945
- deleteActivity: noopDeleteActivity,
946
- };
947
-
948
- await sendMSTeamsMessages({
949
- replyStyle: "top-level",
950
- adapter,
951
- appId: "app123",
952
- conversationRef: storedWithChannelDataTenant,
953
- messages: [{ text: "hello" }],
954
- });
955
-
956
- expect(capturedReference?.tenantId).toBe("tenant-abc");
957
- expect(capturedReference?.aadObjectId).toBe("aad-user-123");
958
- expect(capturedReference?.user?.aadObjectId).toBe("aad-user-123");
959
- });
960
- });
961
- });