@openclaw/msteams 2026.3.13 → 2026.5.1-beta.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 (175) hide show
  1. package/api.ts +3 -0
  2. package/channel-config-api.ts +1 -0
  3. package/channel-plugin-api.ts +2 -0
  4. package/config-api.ts +4 -0
  5. package/contract-api.ts +4 -0
  6. package/index.ts +15 -12
  7. package/openclaw.plugin.json +553 -1
  8. package/package.json +46 -12
  9. package/runtime-api.ts +73 -0
  10. package/secret-contract-api.ts +5 -0
  11. package/setup-entry.ts +13 -0
  12. package/setup-plugin-api.ts +3 -0
  13. package/src/ai-entity.ts +7 -0
  14. package/src/approval-auth.ts +44 -0
  15. package/src/attachments/bot-framework.test.ts +461 -0
  16. package/src/attachments/bot-framework.ts +362 -0
  17. package/src/attachments/download.ts +63 -19
  18. package/src/attachments/graph.test.ts +416 -0
  19. package/src/attachments/graph.ts +163 -72
  20. package/src/attachments/html.ts +33 -1
  21. package/src/attachments/payload.ts +1 -1
  22. package/src/attachments/remote-media.test.ts +137 -0
  23. package/src/attachments/remote-media.ts +75 -8
  24. package/src/attachments/shared.test.ts +138 -1
  25. package/src/attachments/shared.ts +193 -26
  26. package/src/attachments/types.ts +10 -0
  27. package/src/attachments.graph.test.ts +342 -0
  28. package/src/attachments.helpers.test.ts +246 -0
  29. package/src/attachments.test-helpers.ts +17 -0
  30. package/src/attachments.test.ts +163 -418
  31. package/src/attachments.ts +5 -5
  32. package/src/block-streaming-config.test.ts +61 -0
  33. package/src/channel-api.ts +1 -0
  34. package/src/channel.actions.test.ts +742 -0
  35. package/src/channel.directory.test.ts +145 -4
  36. package/src/channel.runtime.ts +56 -0
  37. package/src/channel.setup.ts +77 -0
  38. package/src/channel.test.ts +128 -0
  39. package/src/channel.ts +1077 -395
  40. package/src/config-schema.ts +6 -0
  41. package/src/config-ui-hints.ts +12 -0
  42. package/src/conversation-store-fs.test.ts +4 -5
  43. package/src/conversation-store-fs.ts +35 -51
  44. package/src/conversation-store-helpers.test.ts +202 -0
  45. package/src/conversation-store-helpers.ts +105 -0
  46. package/src/conversation-store-memory.ts +27 -23
  47. package/src/conversation-store.shared.test.ts +225 -0
  48. package/src/conversation-store.ts +30 -0
  49. package/src/directory-live.test.ts +156 -0
  50. package/src/directory-live.ts +7 -4
  51. package/src/doctor.ts +27 -0
  52. package/src/errors.test.ts +64 -1
  53. package/src/errors.ts +50 -9
  54. package/src/feedback-reflection-prompt.ts +117 -0
  55. package/src/feedback-reflection-store.ts +114 -0
  56. package/src/feedback-reflection.test.ts +237 -0
  57. package/src/feedback-reflection.ts +283 -0
  58. package/src/file-consent-helpers.test.ts +83 -0
  59. package/src/file-consent-helpers.ts +64 -11
  60. package/src/file-consent-invoke.ts +150 -0
  61. package/src/file-consent.test.ts +363 -0
  62. package/src/file-consent.ts +165 -4
  63. package/src/graph-chat.ts +5 -3
  64. package/src/graph-group-management.test.ts +318 -0
  65. package/src/graph-group-management.ts +168 -0
  66. package/src/graph-members.test.ts +89 -0
  67. package/src/graph-members.ts +48 -0
  68. package/src/graph-messages.actions.test.ts +243 -0
  69. package/src/graph-messages.read.test.ts +391 -0
  70. package/src/graph-messages.search.test.ts +213 -0
  71. package/src/graph-messages.test-helpers.ts +50 -0
  72. package/src/graph-messages.ts +534 -0
  73. package/src/graph-teams.test.ts +215 -0
  74. package/src/graph-teams.ts +114 -0
  75. package/src/graph-thread.test.ts +246 -0
  76. package/src/graph-thread.ts +146 -0
  77. package/src/graph-upload.test.ts +161 -4
  78. package/src/graph-upload.ts +147 -56
  79. package/src/graph.test.ts +516 -0
  80. package/src/graph.ts +233 -21
  81. package/src/inbound.test.ts +156 -1
  82. package/src/inbound.ts +101 -1
  83. package/src/media-helpers.ts +1 -1
  84. package/src/mentions.test.ts +27 -18
  85. package/src/mentions.ts +2 -2
  86. package/src/messenger.test.ts +504 -23
  87. package/src/messenger.ts +133 -52
  88. package/src/monitor-handler/access.ts +125 -0
  89. package/src/monitor-handler/inbound-media.test.ts +289 -0
  90. package/src/monitor-handler/inbound-media.ts +57 -5
  91. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  92. package/src/monitor-handler/message-handler.authz.test.ts +588 -74
  93. package/src/monitor-handler/message-handler.dm-media.test.ts +54 -0
  94. package/src/monitor-handler/message-handler.test-support.ts +100 -0
  95. package/src/monitor-handler/message-handler.thread-parent.test.ts +223 -0
  96. package/src/monitor-handler/message-handler.thread-session.test.ts +77 -0
  97. package/src/monitor-handler/message-handler.ts +470 -164
  98. package/src/monitor-handler/reaction-handler.test.ts +267 -0
  99. package/src/monitor-handler/reaction-handler.ts +210 -0
  100. package/src/monitor-handler/thread-session.ts +17 -0
  101. package/src/monitor-handler.adaptive-card.test.ts +162 -0
  102. package/src/monitor-handler.feedback-authz.test.ts +314 -0
  103. package/src/monitor-handler.file-consent.test.ts +281 -79
  104. package/src/monitor-handler.sso.test.ts +563 -0
  105. package/src/monitor-handler.test-helpers.ts +180 -0
  106. package/src/monitor-handler.ts +459 -115
  107. package/src/monitor-handler.types.ts +27 -0
  108. package/src/monitor-types.ts +1 -0
  109. package/src/monitor.lifecycle.test.ts +74 -10
  110. package/src/monitor.test.ts +35 -1
  111. package/src/monitor.ts +143 -46
  112. package/src/oauth.flow.ts +77 -0
  113. package/src/oauth.shared.ts +37 -0
  114. package/src/oauth.test.ts +305 -0
  115. package/src/oauth.token.ts +158 -0
  116. package/src/oauth.ts +130 -0
  117. package/src/outbound.test.ts +10 -11
  118. package/src/outbound.ts +62 -44
  119. package/src/pending-uploads-fs.test.ts +246 -0
  120. package/src/pending-uploads-fs.ts +235 -0
  121. package/src/pending-uploads.test.ts +173 -0
  122. package/src/pending-uploads.ts +34 -2
  123. package/src/policy.test.ts +11 -5
  124. package/src/policy.ts +5 -5
  125. package/src/polls.test.ts +106 -5
  126. package/src/polls.ts +15 -7
  127. package/src/presentation.ts +68 -0
  128. package/src/probe.test.ts +27 -8
  129. package/src/probe.ts +43 -9
  130. package/src/reply-dispatcher.test.ts +437 -0
  131. package/src/reply-dispatcher.ts +259 -73
  132. package/src/reply-stream-controller.test.ts +235 -0
  133. package/src/reply-stream-controller.ts +147 -0
  134. package/src/resolve-allowlist.test.ts +105 -1
  135. package/src/resolve-allowlist.ts +112 -7
  136. package/src/runtime.ts +6 -3
  137. package/src/sdk-types.ts +43 -3
  138. package/src/sdk.test.ts +666 -0
  139. package/src/sdk.ts +867 -16
  140. package/src/secret-contract.ts +49 -0
  141. package/src/secret-input.ts +1 -1
  142. package/src/send-context.ts +76 -9
  143. package/src/send.test.ts +389 -5
  144. package/src/send.ts +140 -32
  145. package/src/sent-message-cache.ts +30 -18
  146. package/src/session-route.ts +40 -0
  147. package/src/setup-core.ts +160 -0
  148. package/src/setup-surface.test.ts +202 -0
  149. package/src/setup-surface.ts +320 -0
  150. package/src/sso-token-store.test.ts +72 -0
  151. package/src/sso-token-store.ts +166 -0
  152. package/src/sso.ts +300 -0
  153. package/src/storage.ts +1 -1
  154. package/src/store-fs.ts +2 -2
  155. package/src/streaming-message.test.ts +262 -0
  156. package/src/streaming-message.ts +297 -0
  157. package/src/test-runtime.ts +1 -1
  158. package/src/thread-parent-context.test.ts +224 -0
  159. package/src/thread-parent-context.ts +159 -0
  160. package/src/token.test.ts +237 -50
  161. package/src/token.ts +162 -7
  162. package/src/user-agent.test.ts +86 -0
  163. package/src/user-agent.ts +53 -0
  164. package/src/webhook-timeouts.ts +27 -0
  165. package/src/welcome-card.test.ts +81 -0
  166. package/src/welcome-card.ts +57 -0
  167. package/test-api.ts +1 -0
  168. package/tsconfig.json +16 -0
  169. package/CHANGELOG.md +0 -107
  170. package/src/file-lock.ts +0 -1
  171. package/src/graph-users.test.ts +0 -66
  172. package/src/onboarding.ts +0 -381
  173. package/src/polls-store.test.ts +0 -38
  174. package/src/revoked-context.test.ts +0 -39
  175. package/src/token-response.test.ts +0 -23
package/src/probe.ts CHANGED
@@ -2,11 +2,11 @@ import {
2
2
  normalizeStringEntries,
3
3
  type BaseProbeResult,
4
4
  type MSTeamsConfig,
5
- } from "openclaw/plugin-sdk/msteams";
5
+ } from "../runtime-api.js";
6
6
  import { formatUnknownError } from "./errors.js";
7
- import { loadMSTeamsSdkWithAuth } from "./sdk.js";
7
+ import { createMSTeamsTokenProvider, loadMSTeamsSdkWithAuth } from "./sdk.js";
8
8
  import { readAccessToken } from "./token-response.js";
9
- import { resolveMSTeamsCredentials } from "./token.js";
9
+ import { loadDelegatedTokens, resolveMSTeamsCredentials } from "./token.js";
10
10
 
11
11
  export type ProbeMSTeamsResult = BaseProbeResult<string> & {
12
12
  appId?: string;
@@ -16,6 +16,12 @@ export type ProbeMSTeamsResult = BaseProbeResult<string> & {
16
16
  roles?: string[];
17
17
  scopes?: string[];
18
18
  };
19
+ delegatedAuth?: {
20
+ ok: boolean;
21
+ error?: string;
22
+ scopes?: string[];
23
+ userPrincipalName?: string;
24
+ };
19
25
  };
20
26
 
21
27
  function decodeJwtPayload(token: string): Record<string, unknown> | null {
@@ -64,9 +70,13 @@ export async function probeMSTeams(cfg?: MSTeamsConfig): Promise<ProbeMSTeamsRes
64
70
  }
65
71
 
66
72
  try {
67
- const { sdk, authConfig } = await loadMSTeamsSdkWithAuth(creds);
68
- const tokenProvider = new sdk.MsalTokenProvider(authConfig);
69
- await tokenProvider.getAccessToken("https://api.botframework.com");
73
+ const { app } = await loadMSTeamsSdkWithAuth(creds);
74
+ const tokenProvider = createMSTeamsTokenProvider(app);
75
+ const botTokenValue = await tokenProvider.getAccessToken("https://api.botframework.com");
76
+ if (!botTokenValue) {
77
+ throw new Error("Failed to acquire bot token");
78
+ }
79
+
70
80
  let graph:
71
81
  | {
72
82
  ok: boolean;
@@ -76,8 +86,8 @@ export async function probeMSTeams(cfg?: MSTeamsConfig): Promise<ProbeMSTeamsRes
76
86
  }
77
87
  | undefined;
78
88
  try {
79
- const graphToken = await tokenProvider.getAccessToken("https://graph.microsoft.com");
80
- const accessToken = readAccessToken(graphToken);
89
+ const graphTokenValue = await tokenProvider.getAccessToken("https://graph.microsoft.com");
90
+ const accessToken = readAccessToken(graphTokenValue);
81
91
  const payload = accessToken ? decodeJwtPayload(accessToken) : null;
82
92
  graph = {
83
93
  ok: true,
@@ -87,7 +97,31 @@ export async function probeMSTeams(cfg?: MSTeamsConfig): Promise<ProbeMSTeamsRes
87
97
  } catch (err) {
88
98
  graph = { ok: false, error: formatUnknownError(err) };
89
99
  }
90
- return { ok: true, appId: creds.appId, ...(graph ? { graph } : {}) };
100
+ let delegatedAuth: ProbeMSTeamsResult["delegatedAuth"];
101
+ if (cfg?.delegatedAuth?.enabled) {
102
+ try {
103
+ const tokens = loadDelegatedTokens();
104
+ if (tokens) {
105
+ const isExpired = tokens.expiresAt <= Date.now();
106
+ delegatedAuth = {
107
+ ok: !isExpired,
108
+ scopes: tokens.scopes,
109
+ userPrincipalName: tokens.userPrincipalName,
110
+ ...(isExpired ? { error: "token expired (will auto-refresh on next use)" } : {}),
111
+ };
112
+ } else {
113
+ delegatedAuth = { ok: false, error: "no delegated tokens found (run setup wizard)" };
114
+ }
115
+ } catch {
116
+ delegatedAuth = { ok: false, error: "failed to load delegated tokens" };
117
+ }
118
+ }
119
+ return {
120
+ ok: true,
121
+ appId: creds.appId,
122
+ ...(graph ? { graph } : {}),
123
+ ...(delegatedAuth ? { delegatedAuth } : {}),
124
+ };
91
125
  } catch (err) {
92
126
  return {
93
127
  ok: false,
@@ -0,0 +1,437 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ const createChannelReplyPipelineMock = vi.hoisted(() => vi.fn());
4
+ const createReplyDispatcherWithTypingMock = vi.hoisted(() => vi.fn());
5
+ const getMSTeamsRuntimeMock = vi.hoisted(() => vi.fn());
6
+ const enqueueSystemEventMock = vi.hoisted(() => vi.fn());
7
+ const renderReplyPayloadsToMessagesMock = vi.hoisted(() => vi.fn(() => []));
8
+ const sendMSTeamsMessagesMock = vi.hoisted(() => vi.fn(async () => []));
9
+ const streamInstances = vi.hoisted(
10
+ () =>
11
+ [] as Array<{
12
+ hasContent: boolean;
13
+ isFinalized: boolean;
14
+ isFailed: boolean;
15
+ streamedLength: number;
16
+ sendInformativeUpdate: ReturnType<typeof vi.fn>;
17
+ update: ReturnType<typeof vi.fn>;
18
+ finalize: ReturnType<typeof vi.fn>;
19
+ }>,
20
+ );
21
+
22
+ vi.mock("../runtime-api.js", () => ({
23
+ createChannelReplyPipeline: createChannelReplyPipelineMock,
24
+ logTypingFailure: vi.fn(),
25
+ resolveChannelMediaMaxBytes: vi.fn(() => 8 * 1024 * 1024),
26
+ }));
27
+
28
+ vi.mock("./runtime.js", () => ({
29
+ getMSTeamsRuntime: getMSTeamsRuntimeMock,
30
+ }));
31
+
32
+ vi.mock("./messenger.js", () => ({
33
+ buildConversationReference: vi.fn((ref) => ref),
34
+ renderReplyPayloadsToMessages: renderReplyPayloadsToMessagesMock,
35
+ sendMSTeamsMessages: sendMSTeamsMessagesMock,
36
+ }));
37
+
38
+ vi.mock("./errors.js", () => ({
39
+ classifyMSTeamsSendError: vi.fn(() => ({})),
40
+ formatMSTeamsSendErrorHint: vi.fn(() => undefined),
41
+ formatUnknownError: vi.fn((err) => String(err)),
42
+ }));
43
+
44
+ vi.mock("./revoked-context.js", () => ({
45
+ withRevokedProxyFallback: async ({ run }: { run: () => Promise<unknown> }) => await run(),
46
+ }));
47
+
48
+ vi.mock("./streaming-message.js", () => ({
49
+ TeamsHttpStream: class {
50
+ hasContent = false;
51
+ isFinalized = false;
52
+ isFailed = false;
53
+ streamedLength = 0;
54
+ sendInformativeUpdate = vi.fn(async () => {});
55
+ update = vi.fn();
56
+ finalize = vi.fn(async function (this: { isFinalized: boolean }) {
57
+ this.isFinalized = true;
58
+ });
59
+
60
+ constructor() {
61
+ streamInstances.push(this);
62
+ }
63
+ },
64
+ }));
65
+
66
+ import { createMSTeamsReplyDispatcher, pickInformativeStatusText } from "./reply-dispatcher.js";
67
+
68
+ describe("createMSTeamsReplyDispatcher", () => {
69
+ let typingCallbacks: {
70
+ onReplyStart: ReturnType<typeof vi.fn>;
71
+ onIdle: ReturnType<typeof vi.fn>;
72
+ onCleanup: ReturnType<typeof vi.fn>;
73
+ };
74
+
75
+ beforeEach(() => {
76
+ vi.clearAllMocks();
77
+ streamInstances.length = 0;
78
+
79
+ typingCallbacks = {
80
+ onReplyStart: vi.fn(async () => {}),
81
+ onIdle: vi.fn(),
82
+ onCleanup: vi.fn(),
83
+ };
84
+
85
+ createChannelReplyPipelineMock.mockReturnValue({
86
+ onModelSelected: vi.fn(),
87
+ typingCallbacks,
88
+ });
89
+
90
+ createReplyDispatcherWithTypingMock.mockImplementation((options) => ({
91
+ dispatcher: {},
92
+ replyOptions: {},
93
+ markDispatchIdle: vi.fn(),
94
+ _options: options,
95
+ }));
96
+
97
+ getMSTeamsRuntimeMock.mockReturnValue({
98
+ system: {
99
+ enqueueSystemEvent: enqueueSystemEventMock,
100
+ },
101
+ channel: {
102
+ text: {
103
+ resolveChunkMode: vi.fn(() => "length"),
104
+ resolveMarkdownTableMode: vi.fn(() => "code"),
105
+ },
106
+ reply: {
107
+ createReplyDispatcherWithTyping: createReplyDispatcherWithTypingMock,
108
+ resolveHumanDelayConfig: vi.fn(() => undefined),
109
+ },
110
+ },
111
+ });
112
+ });
113
+
114
+ let lastCreatedDispatcher: ReturnType<typeof createMSTeamsReplyDispatcher> | undefined;
115
+ let lastContextSendActivity: ReturnType<typeof vi.fn> | undefined;
116
+
117
+ function createDispatcher(
118
+ conversationType: string = "personal",
119
+ msteamsConfig: Record<string, unknown> = {},
120
+ extraParams: { onSentMessageIds?: (ids: string[]) => void } = {},
121
+ ) {
122
+ const contextSendActivity = vi.fn(async () => ({ id: "activity-1" }));
123
+ lastContextSendActivity = contextSendActivity;
124
+ const dispatcher = createMSTeamsReplyDispatcher({
125
+ cfg: { channels: { msteams: msteamsConfig } } as never,
126
+ agentId: "agent",
127
+ sessionKey: "agent:main:main",
128
+ runtime: { error: vi.fn() } as never,
129
+ log: { debug: vi.fn(), error: vi.fn(), warn: vi.fn() } as never,
130
+ adapter: {
131
+ continueConversation: vi.fn(),
132
+ process: vi.fn(),
133
+ updateActivity: vi.fn(),
134
+ deleteActivity: vi.fn(),
135
+ } as never,
136
+ appId: "app",
137
+ conversationRef: {
138
+ conversation: { id: "conv", conversationType },
139
+ user: { id: "user" },
140
+ agent: { id: "bot" },
141
+ channelId: "msteams",
142
+ serviceUrl: "https://service.example.com",
143
+ } as never,
144
+ context: {
145
+ sendActivity: contextSendActivity,
146
+ } as never,
147
+ replyStyle: "thread",
148
+ textLimit: 4000,
149
+ ...extraParams,
150
+ });
151
+ lastCreatedDispatcher = dispatcher;
152
+ return dispatcher;
153
+ }
154
+
155
+ function getContextSendActivity(): ReturnType<typeof vi.fn> {
156
+ if (!lastContextSendActivity) {
157
+ throw new Error("createDispatcher must be called first");
158
+ }
159
+ return lastContextSendActivity;
160
+ }
161
+
162
+ async function triggerPartialReply(text: string): Promise<void> {
163
+ if (!lastCreatedDispatcher) {
164
+ throw new Error("createDispatcher must be called first");
165
+ }
166
+ lastCreatedDispatcher.replyOptions.onPartialReply?.({ text });
167
+ }
168
+
169
+ it("sends an informative status update on reply start for personal chats", async () => {
170
+ createDispatcher("personal");
171
+ const options = createReplyDispatcherWithTypingMock.mock.calls[0]?.[0];
172
+
173
+ await options.onReplyStart?.();
174
+
175
+ expect(streamInstances).toHaveLength(1);
176
+ expect(streamInstances[0]?.sendInformativeUpdate).toHaveBeenCalledTimes(1);
177
+ });
178
+
179
+ it("starts the typing keepalive in personal chats so the TurnContext survives long tool chains", async () => {
180
+ createDispatcher("personal");
181
+ const options = createReplyDispatcherWithTypingMock.mock.calls[0]?.[0];
182
+
183
+ await options.onReplyStart?.();
184
+
185
+ // In addition to the streaming card's informative update, the typing
186
+ // keepalive is now started on personal chats so Bot Framework proxies
187
+ // stay alive during long tool chains (#59731).
188
+ expect(typingCallbacks.onReplyStart).toHaveBeenCalledTimes(1);
189
+ });
190
+
191
+ it("skips the typing keepalive in personal chats when typingIndicator=false", async () => {
192
+ createDispatcher("personal", { typingIndicator: false });
193
+ const options = createReplyDispatcherWithTypingMock.mock.calls[0]?.[0];
194
+
195
+ await options.onReplyStart?.();
196
+
197
+ // Even though we still send the informative update, the opt-out
198
+ // disables the typing keepalive.
199
+ expect(streamInstances[0]?.sendInformativeUpdate).toHaveBeenCalledTimes(1);
200
+ expect(typingCallbacks.onReplyStart).not.toHaveBeenCalled();
201
+ });
202
+
203
+ it("passes a longer keepalive TTL so the loop survives long tool chains", () => {
204
+ createDispatcher("personal");
205
+
206
+ const pipelineArgs = createChannelReplyPipelineMock.mock.calls[0]?.[0];
207
+ expect(pipelineArgs?.typing?.keepaliveIntervalMs).toBeGreaterThan(3_000);
208
+ expect(pipelineArgs?.typing?.keepaliveIntervalMs).toBeLessThanOrEqual(10_000);
209
+ // Issue #59731 reports 60s+ tool chains — the default 60s TTL is too
210
+ // tight so the dispatcher passes its own generous ceiling.
211
+ expect(pipelineArgs?.typing?.maxDurationMs).toBeGreaterThanOrEqual(300_000);
212
+ });
213
+
214
+ it("allows typing keepalive sends before any stream tokens arrive", async () => {
215
+ createDispatcher("personal");
216
+ const pipelineArgs = createChannelReplyPipelineMock.mock.calls[0]?.[0];
217
+ const sendTyping = pipelineArgs?.typing?.start as () => Promise<void>;
218
+
219
+ // No onPartialReply has been called yet, so the stream is not active.
220
+ // The typing keepalive should be allowed to warm the TurnContext.
221
+ const contextSendActivity = getContextSendActivity();
222
+ contextSendActivity.mockClear();
223
+ await sendTyping();
224
+ expect(contextSendActivity).toHaveBeenCalledWith({ type: "typing" });
225
+ });
226
+
227
+ it("suppresses typing keepalive sends while the stream card is actively chunking", async () => {
228
+ createDispatcher("personal");
229
+ const pipelineArgs = createChannelReplyPipelineMock.mock.calls[0]?.[0];
230
+ const sendTyping = pipelineArgs?.typing?.start as () => Promise<void>;
231
+
232
+ // Simulate the stream actively receiving a partial chunk. While the
233
+ // stream card is live we do not want a plain "..." typing indicator
234
+ // layered on top of it.
235
+ await triggerPartialReply("streaming content");
236
+
237
+ const contextSendActivity = getContextSendActivity();
238
+ contextSendActivity.mockClear();
239
+ await sendTyping();
240
+ expect(contextSendActivity).not.toHaveBeenCalled();
241
+ });
242
+
243
+ it("resumes typing keepalive sends once the stream finalizes between tool rounds", async () => {
244
+ createDispatcher("personal");
245
+ const pipelineArgs = createChannelReplyPipelineMock.mock.calls[0]?.[0];
246
+ const sendTyping = pipelineArgs?.typing?.start as () => Promise<void>;
247
+
248
+ // First segment: tokens flow, stream is active, typing is gated off.
249
+ await triggerPartialReply("first segment tokens");
250
+ const stream = streamInstances[0];
251
+ if (!stream) {
252
+ throw new Error("expected a Teams stream instance to be created");
253
+ }
254
+ const contextSendActivity = getContextSendActivity();
255
+ contextSendActivity.mockClear();
256
+ await sendTyping();
257
+ expect(contextSendActivity).not.toHaveBeenCalled();
258
+
259
+ // First segment complete: the stream is finalized ahead of the tool
260
+ // chain. Mirror what preparePayload does by flipping the mocked stream's
261
+ // finalized flag. The controller's isStreamActive check reads this via
262
+ // the real stream controller wired into the dispatcher.
263
+ stream.isFinalized = true;
264
+
265
+ // During the tool chain the loop should be allowed to fire again so
266
+ // the Bot Framework proxy stays warm. See #59731.
267
+ contextSendActivity.mockClear();
268
+ await sendTyping();
269
+ expect(contextSendActivity).toHaveBeenCalledWith({ type: "typing" });
270
+ });
271
+
272
+ it("fires native typing in group chats (no stream) because the gate never applies", async () => {
273
+ createDispatcher("groupchat");
274
+ const pipelineArgs = createChannelReplyPipelineMock.mock.calls[0]?.[0];
275
+ const sendTyping = pipelineArgs?.typing?.start as () => Promise<void>;
276
+
277
+ // In group chats we don't create a stream, so isStreamActive() always
278
+ // returns false and the typing indicator still fires normally.
279
+ const contextSendActivity = getContextSendActivity();
280
+ contextSendActivity.mockClear();
281
+ await sendTyping();
282
+ expect(contextSendActivity).toHaveBeenCalledWith({ type: "typing" });
283
+ });
284
+
285
+ it("is a no-op for channel conversations (typing unsupported)", async () => {
286
+ createDispatcher("channel");
287
+ const pipelineArgs = createChannelReplyPipelineMock.mock.calls[0]?.[0];
288
+ const sendTyping = pipelineArgs?.typing?.start as () => Promise<void>;
289
+
290
+ const contextSendActivity = getContextSendActivity();
291
+ contextSendActivity.mockClear();
292
+ await sendTyping();
293
+ // Teams channel conversations do not support the typing activity at
294
+ // all, so the start callback is a no-op regardless of stream state.
295
+ expect(contextSendActivity).not.toHaveBeenCalled();
296
+ });
297
+
298
+ it("sends native typing indicator for channel conversations by default", async () => {
299
+ createDispatcher("channel");
300
+ const options = createReplyDispatcherWithTypingMock.mock.calls[0]?.[0];
301
+
302
+ await options.onReplyStart?.();
303
+
304
+ expect(streamInstances).toHaveLength(0);
305
+ expect(typingCallbacks.onReplyStart).toHaveBeenCalledTimes(1);
306
+ });
307
+
308
+ it("skips native typing indicator when typingIndicator=false", async () => {
309
+ createDispatcher("channel", { typingIndicator: false });
310
+ const options = createReplyDispatcherWithTypingMock.mock.calls[0]?.[0];
311
+
312
+ await options.onReplyStart?.();
313
+
314
+ expect(typingCallbacks.onReplyStart).not.toHaveBeenCalled();
315
+ });
316
+
317
+ it("only sends the informative status update once", async () => {
318
+ createDispatcher("personal");
319
+ const options = createReplyDispatcherWithTypingMock.mock.calls[0]?.[0];
320
+
321
+ await options.onReplyStart?.();
322
+ await options.onReplyStart?.();
323
+
324
+ expect(streamInstances[0]?.sendInformativeUpdate).toHaveBeenCalledTimes(1);
325
+ });
326
+
327
+ it("forwards partial replies into the Teams stream", async () => {
328
+ const dispatcher = createDispatcher("personal");
329
+
330
+ dispatcher.replyOptions.onPartialReply?.({ text: "partial response" });
331
+
332
+ expect(streamInstances[0]?.update).toHaveBeenCalledWith("partial response");
333
+ });
334
+
335
+ it("does not create a stream for channel conversations", async () => {
336
+ createDispatcher("channel");
337
+
338
+ expect(streamInstances).toHaveLength(0);
339
+ });
340
+
341
+ it("sets disableBlockStreaming=false when blockStreaming=true", () => {
342
+ const dispatcher = createDispatcher("personal", { blockStreaming: true });
343
+
344
+ expect(dispatcher.replyOptions.disableBlockStreaming).toBe(false);
345
+ });
346
+
347
+ it("sets disableBlockStreaming=true when blockStreaming=false", () => {
348
+ const dispatcher = createDispatcher("personal", { blockStreaming: false });
349
+
350
+ expect(dispatcher.replyOptions.disableBlockStreaming).toBe(true);
351
+ });
352
+
353
+ it("leaves disableBlockStreaming undefined when blockStreaming is not set", () => {
354
+ const dispatcher = createDispatcher("personal", {});
355
+
356
+ expect(dispatcher.replyOptions.disableBlockStreaming).toBeUndefined();
357
+ });
358
+
359
+ it("flushes messages immediately on deliver when blockStreaming is enabled", async () => {
360
+ renderReplyPayloadsToMessagesMock.mockReturnValue([{ content: "hello" }] as never);
361
+ sendMSTeamsMessagesMock.mockResolvedValue(["id-1"] as never);
362
+
363
+ createDispatcher("personal", { blockStreaming: true });
364
+ const options = createReplyDispatcherWithTypingMock.mock.calls[0]?.[0];
365
+
366
+ // Call deliver — with blockStreaming enabled it should flush immediately
367
+ await options.deliver({ text: "block content" });
368
+
369
+ expect(sendMSTeamsMessagesMock).toHaveBeenCalledTimes(1);
370
+ });
371
+
372
+ it("does not flush messages on deliver when blockStreaming is disabled", async () => {
373
+ renderReplyPayloadsToMessagesMock.mockReturnValue([{ content: "hello" }] as never);
374
+
375
+ createDispatcher("personal", { blockStreaming: false });
376
+ const options = createReplyDispatcherWithTypingMock.mock.calls[0]?.[0];
377
+
378
+ await options.deliver({ text: "block content" });
379
+
380
+ expect(sendMSTeamsMessagesMock).not.toHaveBeenCalled();
381
+ });
382
+
383
+ it("queues a system event when some queued Teams messages fail to send", async () => {
384
+ const onSentMessageIds = vi.fn();
385
+ renderReplyPayloadsToMessagesMock.mockReturnValue([
386
+ { content: "one" },
387
+ { content: "two" },
388
+ ] as never);
389
+ sendMSTeamsMessagesMock
390
+ .mockRejectedValueOnce(Object.assign(new Error("gateway timeout"), { statusCode: 502 }))
391
+ .mockResolvedValueOnce(["id-1"] as never)
392
+ .mockRejectedValueOnce(Object.assign(new Error("gateway timeout"), { statusCode: 502 }));
393
+
394
+ const dispatcher = createDispatcher(
395
+ "personal",
396
+ { blockStreaming: false },
397
+ { onSentMessageIds },
398
+ );
399
+ const options = createReplyDispatcherWithTypingMock.mock.calls[0]?.[0];
400
+
401
+ await options.deliver({ text: "block content" });
402
+ await dispatcher.markDispatchIdle();
403
+
404
+ expect(onSentMessageIds).toHaveBeenCalledWith(["id-1"]);
405
+ expect(enqueueSystemEventMock).toHaveBeenCalledWith(
406
+ expect.stringContaining("Microsoft Teams delivery failed"),
407
+ expect.objectContaining({
408
+ sessionKey: "agent:main:main",
409
+ contextKey: "msteams:delivery-failure:conv",
410
+ }),
411
+ );
412
+ expect(enqueueSystemEventMock).toHaveBeenCalledWith(
413
+ expect.stringContaining("The user may not have received the full reply"),
414
+ expect.any(Object),
415
+ );
416
+ });
417
+
418
+ it("does not queue a delivery-failure system event when Teams send succeeds", async () => {
419
+ renderReplyPayloadsToMessagesMock.mockReturnValue([{ content: "hello" }] as never);
420
+ sendMSTeamsMessagesMock.mockResolvedValue(["id-1"] as never);
421
+
422
+ const dispatcher = createDispatcher("personal", { blockStreaming: false });
423
+ const options = createReplyDispatcherWithTypingMock.mock.calls[0]?.[0];
424
+
425
+ await options.deliver({ text: "block content" });
426
+ await dispatcher.markDispatchIdle();
427
+
428
+ expect(enqueueSystemEventMock).not.toHaveBeenCalled();
429
+ });
430
+ });
431
+
432
+ describe("pickInformativeStatusText", () => {
433
+ it("selects a deterministic status line for a fixed random source", () => {
434
+ expect(pickInformativeStatusText(() => 0)).toBe("Thinking...");
435
+ expect(pickInformativeStatusText(() => 0.99)).toBe("Putting an answer together...");
436
+ });
437
+ });