@openclaw/msteams 2026.5.2 → 2026.5.3-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 (197) hide show
  1. package/dist/api.js +3 -0
  2. package/dist/channel-D7hdreTh.js +984 -0
  3. package/dist/channel-config-api.js +2 -0
  4. package/dist/channel-plugin-api.js +2 -0
  5. package/dist/channel.runtime-BC1ruIfN.js +573 -0
  6. package/dist/config-schema-B8QezH6t.js +15 -0
  7. package/dist/contract-api.js +2 -0
  8. package/dist/graph-users-9uQJepqr.js +1354 -0
  9. package/dist/index.js +22 -0
  10. package/dist/oauth-BWJyilR1.js +114 -0
  11. package/dist/oauth.token-xxpoLWy5.js +115 -0
  12. package/dist/policy-DTnU2GR7.js +142 -0
  13. package/dist/probe-D_H8yFps.js +2194 -0
  14. package/dist/resolve-allowlist-D41JSziq.js +219 -0
  15. package/dist/runtime-api-DV1iVMn1.js +28 -0
  16. package/dist/runtime-api.js +2 -0
  17. package/dist/secret-contract-BuoEXmPS.js +35 -0
  18. package/dist/secret-contract-api.js +2 -0
  19. package/dist/setup-entry.js +15 -0
  20. package/dist/setup-plugin-api.js +64 -0
  21. package/dist/setup-surface-BLkFQYIQ.js +313 -0
  22. package/dist/src-CFp1QpFd.js +4064 -0
  23. package/dist/test-api.js +2 -0
  24. package/package.json +14 -6
  25. package/api.ts +0 -3
  26. package/channel-config-api.ts +0 -1
  27. package/channel-plugin-api.ts +0 -2
  28. package/config-api.ts +0 -4
  29. package/contract-api.ts +0 -4
  30. package/index.ts +0 -20
  31. package/runtime-api.ts +0 -73
  32. package/secret-contract-api.ts +0 -5
  33. package/setup-entry.ts +0 -13
  34. package/setup-plugin-api.ts +0 -3
  35. package/src/ai-entity.ts +0 -7
  36. package/src/approval-auth.ts +0 -44
  37. package/src/attachments/bot-framework.test.ts +0 -461
  38. package/src/attachments/bot-framework.ts +0 -362
  39. package/src/attachments/download.ts +0 -311
  40. package/src/attachments/graph.test.ts +0 -416
  41. package/src/attachments/graph.ts +0 -484
  42. package/src/attachments/html.ts +0 -122
  43. package/src/attachments/payload.ts +0 -14
  44. package/src/attachments/remote-media.test.ts +0 -137
  45. package/src/attachments/remote-media.ts +0 -112
  46. package/src/attachments/shared.test.ts +0 -530
  47. package/src/attachments/shared.ts +0 -626
  48. package/src/attachments/types.ts +0 -47
  49. package/src/attachments.graph.test.ts +0 -342
  50. package/src/attachments.helpers.test.ts +0 -246
  51. package/src/attachments.test-helpers.ts +0 -17
  52. package/src/attachments.test.ts +0 -687
  53. package/src/attachments.ts +0 -18
  54. package/src/block-streaming-config.test.ts +0 -61
  55. package/src/channel-api.ts +0 -1
  56. package/src/channel.actions.test.ts +0 -742
  57. package/src/channel.directory.test.ts +0 -200
  58. package/src/channel.runtime.ts +0 -56
  59. package/src/channel.setup.ts +0 -77
  60. package/src/channel.test.ts +0 -128
  61. package/src/channel.ts +0 -1136
  62. package/src/config-schema.ts +0 -6
  63. package/src/config-ui-hints.ts +0 -12
  64. package/src/conversation-store-fs.test.ts +0 -74
  65. package/src/conversation-store-fs.ts +0 -149
  66. package/src/conversation-store-helpers.test.ts +0 -202
  67. package/src/conversation-store-helpers.ts +0 -105
  68. package/src/conversation-store-memory.ts +0 -51
  69. package/src/conversation-store.shared.test.ts +0 -225
  70. package/src/conversation-store.ts +0 -71
  71. package/src/directory-live.test.ts +0 -156
  72. package/src/directory-live.ts +0 -111
  73. package/src/doctor.ts +0 -27
  74. package/src/errors.test.ts +0 -133
  75. package/src/errors.ts +0 -246
  76. package/src/feedback-reflection-prompt.ts +0 -117
  77. package/src/feedback-reflection-store.ts +0 -114
  78. package/src/feedback-reflection.test.ts +0 -237
  79. package/src/feedback-reflection.ts +0 -283
  80. package/src/file-consent-helpers.test.ts +0 -326
  81. package/src/file-consent-helpers.ts +0 -126
  82. package/src/file-consent-invoke.ts +0 -150
  83. package/src/file-consent.test.ts +0 -363
  84. package/src/file-consent.ts +0 -287
  85. package/src/graph-chat.ts +0 -55
  86. package/src/graph-group-management.test.ts +0 -318
  87. package/src/graph-group-management.ts +0 -168
  88. package/src/graph-members.test.ts +0 -89
  89. package/src/graph-members.ts +0 -48
  90. package/src/graph-messages.actions.test.ts +0 -243
  91. package/src/graph-messages.read.test.ts +0 -391
  92. package/src/graph-messages.search.test.ts +0 -213
  93. package/src/graph-messages.test-helpers.ts +0 -50
  94. package/src/graph-messages.ts +0 -534
  95. package/src/graph-teams.test.ts +0 -215
  96. package/src/graph-teams.ts +0 -114
  97. package/src/graph-thread.test.ts +0 -246
  98. package/src/graph-thread.ts +0 -146
  99. package/src/graph-upload.test.ts +0 -258
  100. package/src/graph-upload.ts +0 -531
  101. package/src/graph-users.ts +0 -29
  102. package/src/graph.test.ts +0 -516
  103. package/src/graph.ts +0 -293
  104. package/src/inbound.test.ts +0 -221
  105. package/src/inbound.ts +0 -148
  106. package/src/index.ts +0 -4
  107. package/src/media-helpers.test.ts +0 -202
  108. package/src/media-helpers.ts +0 -105
  109. package/src/mentions.test.ts +0 -244
  110. package/src/mentions.ts +0 -114
  111. package/src/messenger.test.ts +0 -865
  112. package/src/messenger.ts +0 -605
  113. package/src/monitor-handler/access.ts +0 -125
  114. package/src/monitor-handler/inbound-media.test.ts +0 -289
  115. package/src/monitor-handler/inbound-media.ts +0 -180
  116. package/src/monitor-handler/message-handler-mock-support.test-support.ts +0 -28
  117. package/src/monitor-handler/message-handler.authz.test.ts +0 -669
  118. package/src/monitor-handler/message-handler.dm-media.test.ts +0 -54
  119. package/src/monitor-handler/message-handler.test-support.ts +0 -100
  120. package/src/monitor-handler/message-handler.thread-parent.test.ts +0 -223
  121. package/src/monitor-handler/message-handler.thread-session.test.ts +0 -77
  122. package/src/monitor-handler/message-handler.ts +0 -1000
  123. package/src/monitor-handler/reaction-handler.test.ts +0 -267
  124. package/src/monitor-handler/reaction-handler.ts +0 -210
  125. package/src/monitor-handler/thread-session.ts +0 -17
  126. package/src/monitor-handler.adaptive-card.test.ts +0 -162
  127. package/src/monitor-handler.feedback-authz.test.ts +0 -314
  128. package/src/monitor-handler.file-consent.test.ts +0 -423
  129. package/src/monitor-handler.sso.test.ts +0 -563
  130. package/src/monitor-handler.test-helpers.ts +0 -180
  131. package/src/monitor-handler.ts +0 -534
  132. package/src/monitor-handler.types.ts +0 -27
  133. package/src/monitor-types.ts +0 -6
  134. package/src/monitor.lifecycle.test.ts +0 -278
  135. package/src/monitor.test.ts +0 -119
  136. package/src/monitor.ts +0 -442
  137. package/src/oauth.flow.ts +0 -77
  138. package/src/oauth.shared.ts +0 -37
  139. package/src/oauth.test.ts +0 -305
  140. package/src/oauth.token.ts +0 -158
  141. package/src/oauth.ts +0 -130
  142. package/src/outbound.test.ts +0 -130
  143. package/src/outbound.ts +0 -71
  144. package/src/pending-uploads-fs.test.ts +0 -246
  145. package/src/pending-uploads-fs.ts +0 -235
  146. package/src/pending-uploads.test.ts +0 -173
  147. package/src/pending-uploads.ts +0 -121
  148. package/src/policy.test.ts +0 -240
  149. package/src/policy.ts +0 -262
  150. package/src/polls-store-memory.ts +0 -32
  151. package/src/polls.test.ts +0 -160
  152. package/src/polls.ts +0 -323
  153. package/src/presentation.ts +0 -68
  154. package/src/probe.test.ts +0 -77
  155. package/src/probe.ts +0 -132
  156. package/src/reply-dispatcher.test.ts +0 -437
  157. package/src/reply-dispatcher.ts +0 -346
  158. package/src/reply-stream-controller.test.ts +0 -235
  159. package/src/reply-stream-controller.ts +0 -147
  160. package/src/resolve-allowlist.test.ts +0 -250
  161. package/src/resolve-allowlist.ts +0 -309
  162. package/src/revoked-context.ts +0 -17
  163. package/src/runtime.ts +0 -9
  164. package/src/sdk-types.ts +0 -59
  165. package/src/sdk.test.ts +0 -666
  166. package/src/sdk.ts +0 -884
  167. package/src/secret-contract.ts +0 -49
  168. package/src/secret-input.ts +0 -7
  169. package/src/send-context.ts +0 -231
  170. package/src/send.test.ts +0 -493
  171. package/src/send.ts +0 -637
  172. package/src/sent-message-cache.test.ts +0 -15
  173. package/src/sent-message-cache.ts +0 -56
  174. package/src/session-route.ts +0 -40
  175. package/src/setup-core.ts +0 -160
  176. package/src/setup-surface.test.ts +0 -202
  177. package/src/setup-surface.ts +0 -320
  178. package/src/sso-token-store.test.ts +0 -72
  179. package/src/sso-token-store.ts +0 -166
  180. package/src/sso.ts +0 -300
  181. package/src/storage.ts +0 -25
  182. package/src/store-fs.ts +0 -44
  183. package/src/streaming-message.test.ts +0 -262
  184. package/src/streaming-message.ts +0 -297
  185. package/src/test-runtime.ts +0 -16
  186. package/src/thread-parent-context.test.ts +0 -224
  187. package/src/thread-parent-context.ts +0 -159
  188. package/src/token-response.ts +0 -11
  189. package/src/token.test.ts +0 -259
  190. package/src/token.ts +0 -195
  191. package/src/user-agent.test.ts +0 -86
  192. package/src/user-agent.ts +0 -53
  193. package/src/webhook-timeouts.ts +0 -27
  194. package/src/welcome-card.test.ts +0 -81
  195. package/src/welcome-card.ts +0 -57
  196. package/test-api.ts +0 -1
  197. package/tsconfig.json +0 -16
@@ -1,346 +0,0 @@
1
- import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/text-runtime";
2
- import {
3
- createChannelReplyPipeline,
4
- logTypingFailure,
5
- resolveChannelMediaMaxBytes,
6
- type OpenClawConfig,
7
- type MSTeamsReplyStyle,
8
- type RuntimeEnv,
9
- } from "../runtime-api.js";
10
- import type { MSTeamsAccessTokenProvider } from "./attachments/types.js";
11
- import type { StoredConversationReference } from "./conversation-store.js";
12
- import {
13
- classifyMSTeamsSendError,
14
- formatMSTeamsSendErrorHint,
15
- formatUnknownError,
16
- } from "./errors.js";
17
- import {
18
- buildConversationReference,
19
- type MSTeamsAdapter,
20
- type MSTeamsRenderedMessage,
21
- renderReplyPayloadsToMessages,
22
- sendMSTeamsMessages,
23
- } from "./messenger.js";
24
- import type { MSTeamsMonitorLogger } from "./monitor-types.js";
25
- import { createTeamsReplyStreamController } from "./reply-stream-controller.js";
26
- import { withRevokedProxyFallback } from "./revoked-context.js";
27
- import { getMSTeamsRuntime } from "./runtime.js";
28
- import type { MSTeamsTurnContext } from "./sdk-types.js";
29
-
30
- export { pickInformativeStatusText } from "./reply-stream-controller.js";
31
-
32
- export function createMSTeamsReplyDispatcher(params: {
33
- cfg: OpenClawConfig;
34
- agentId: string;
35
- sessionKey: string;
36
- accountId?: string;
37
- runtime: RuntimeEnv;
38
- log: MSTeamsMonitorLogger;
39
- adapter: MSTeamsAdapter;
40
- appId: string;
41
- conversationRef: StoredConversationReference;
42
- context: MSTeamsTurnContext;
43
- replyStyle: MSTeamsReplyStyle;
44
- textLimit: number;
45
- onSentMessageIds?: (ids: string[]) => void;
46
- tokenProvider?: MSTeamsAccessTokenProvider;
47
- sharePointSiteId?: string;
48
- }) {
49
- const core = getMSTeamsRuntime();
50
- const msteamsCfg = params.cfg.channels?.msteams;
51
- const conversationType = normalizeOptionalLowercaseString(
52
- params.conversationRef.conversation?.conversationType,
53
- );
54
- const isTypingSupported = conversationType === "personal" || conversationType === "groupchat";
55
-
56
- /**
57
- * Keepalive cadence for the typing indicator while the bot is running
58
- * (including long tool chains). Bot Framework 1:1 TurnContext proxies
59
- * expire after ~30s of inactivity; sending a typing activity every 8s
60
- * keeps the proxy alive so the post-tool reply can still land via the
61
- * turn context. Sits in the middle of the 5-10s range recommended in
62
- * #59731.
63
- */
64
- const TYPING_KEEPALIVE_INTERVAL_MS = 8_000;
65
-
66
- /**
67
- * TTL ceiling for the typing keepalive loop. The default in
68
- * createTypingCallbacks is 60s, which is too short for the Teams long tool
69
- * chains described in #59731 (60s+ total runs are common). Give tool
70
- * chains up to 10 minutes before auto-stopping the keepalive.
71
- */
72
- const TYPING_KEEPALIVE_MAX_DURATION_MS = 10 * 60_000;
73
-
74
- // Forward reference: sendTypingIndicator is built before the stream
75
- // controller exists, but the keepalive tick needs to check stream state so
76
- // we don't overlay "..." typing on the visible streaming card. The ref is
77
- // wired once the stream controller is constructed below.
78
- const streamActiveRef: { current: () => boolean } = { current: () => false };
79
-
80
- const rawSendTypingIndicator = async () => {
81
- await withRevokedProxyFallback({
82
- run: async () => {
83
- await params.context.sendActivity({ type: "typing" });
84
- },
85
- onRevoked: async () => {
86
- const baseRef = buildConversationReference(params.conversationRef);
87
- await params.adapter.continueConversation(
88
- params.appId,
89
- { ...baseRef, activityId: undefined },
90
- async (ctx) => {
91
- await ctx.sendActivity({ type: "typing" });
92
- },
93
- );
94
- },
95
- onRevokedLog: () => {
96
- params.log.debug?.("turn context revoked, sending typing via proactive messaging");
97
- },
98
- });
99
- };
100
-
101
- const sendTypingIndicator = isTypingSupported
102
- ? async () => {
103
- // While the streaming card is actively being updated the user
104
- // already sees a live indicator in the stream — don't overlay a
105
- // plain "..." typing on top of it. Between segments (tool chain)
106
- // the stream is finalized, so typing indicators are appropriate
107
- // and they are what keep the TurnContext alive. See #59731.
108
- if (streamActiveRef.current()) {
109
- return;
110
- }
111
- await rawSendTypingIndicator();
112
- }
113
- : async () => {};
114
-
115
- const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelReplyPipeline({
116
- cfg: params.cfg,
117
- agentId: params.agentId,
118
- channel: "msteams",
119
- accountId: params.accountId,
120
- typing: {
121
- start: sendTypingIndicator,
122
- keepaliveIntervalMs: TYPING_KEEPALIVE_INTERVAL_MS,
123
- maxDurationMs: TYPING_KEEPALIVE_MAX_DURATION_MS,
124
- onStartError: (err) => {
125
- logTypingFailure({
126
- log: (message) => params.log.debug?.(message),
127
- channel: "msteams",
128
- action: "start",
129
- error: err,
130
- });
131
- },
132
- },
133
- });
134
-
135
- const chunkMode = core.channel.text.resolveChunkMode(params.cfg, "msteams");
136
- const tableMode = core.channel.text.resolveMarkdownTableMode({
137
- cfg: params.cfg,
138
- channel: "msteams",
139
- });
140
- const mediaMaxBytes = resolveChannelMediaMaxBytes({
141
- cfg: params.cfg,
142
- resolveChannelLimitMb: ({ cfg }) => cfg.channels?.msteams?.mediaMaxMb,
143
- });
144
- const feedbackLoopEnabled = params.cfg.channels?.msteams?.feedbackEnabled !== false;
145
- const streamController = createTeamsReplyStreamController({
146
- conversationType,
147
- context: params.context,
148
- feedbackLoopEnabled,
149
- log: params.log,
150
- });
151
- // Wire the forward-declared gate used by sendTypingIndicator.
152
- streamActiveRef.current = () => streamController.isStreamActive();
153
-
154
- const blockStreamingEnabled =
155
- typeof msteamsCfg?.blockStreaming === "boolean" ? msteamsCfg.blockStreaming : false;
156
- const typingIndicatorEnabled =
157
- typeof msteamsCfg?.typingIndicator === "boolean" ? msteamsCfg.typingIndicator : true;
158
-
159
- const pendingMessages: MSTeamsRenderedMessage[] = [];
160
-
161
- const sendMessages = async (messages: MSTeamsRenderedMessage[]): Promise<string[]> => {
162
- return sendMSTeamsMessages({
163
- replyStyle: params.replyStyle,
164
- adapter: params.adapter,
165
- appId: params.appId,
166
- conversationRef: params.conversationRef,
167
- context: params.context,
168
- messages,
169
- retry: {},
170
- onRetry: (event) => {
171
- params.log.debug?.("retrying send", {
172
- replyStyle: params.replyStyle,
173
- ...event,
174
- });
175
- },
176
- tokenProvider: params.tokenProvider,
177
- sharePointSiteId: params.sharePointSiteId,
178
- mediaMaxBytes,
179
- feedbackLoopEnabled,
180
- });
181
- };
182
-
183
- const queueDeliveryFailureSystemEvent = (failure: {
184
- failed: number;
185
- total: number;
186
- error: unknown;
187
- }) => {
188
- const classification = classifyMSTeamsSendError(failure.error);
189
- const errorText = formatUnknownError(failure.error);
190
- const failedAll = failure.failed >= failure.total;
191
- const summary = failedAll
192
- ? "the previous reply was not delivered"
193
- : `${failure.failed} of ${failure.total} message blocks were not delivered`;
194
- const sentences = [
195
- `Microsoft Teams delivery failed: ${summary}.`,
196
- `The user may not have received ${failedAll ? "that reply" : "the full reply"}.`,
197
- `Error: ${errorText}.`,
198
- classification.statusCode != null ? `Status: ${classification.statusCode}.` : undefined,
199
- classification.kind === "transient" || classification.kind === "throttled"
200
- ? "Retrying later may succeed."
201
- : undefined,
202
- ].filter(Boolean);
203
- core.system.enqueueSystemEvent(sentences.join(" "), {
204
- sessionKey: params.sessionKey,
205
- contextKey: `msteams:delivery-failure:${params.conversationRef.conversation?.id ?? "unknown"}`,
206
- });
207
- };
208
-
209
- const flushPendingMessages = async () => {
210
- if (pendingMessages.length === 0) {
211
- return;
212
- }
213
- const toSend = pendingMessages.splice(0);
214
- const total = toSend.length;
215
- let ids: string[];
216
- try {
217
- ids = await sendMessages(toSend);
218
- } catch (batchError) {
219
- ids = [];
220
- let failed = 0;
221
- let lastFailedError: unknown = batchError;
222
- for (const msg of toSend) {
223
- try {
224
- const msgIds = await sendMessages([msg]);
225
- ids.push(...msgIds);
226
- } catch (msgError) {
227
- failed += 1;
228
- lastFailedError = msgError;
229
- params.log.debug?.("individual message send failed, continuing with remaining blocks");
230
- }
231
- }
232
- if (failed > 0) {
233
- params.log.warn?.(`failed to deliver ${failed} of ${total} message blocks`, {
234
- failed,
235
- total,
236
- });
237
- queueDeliveryFailureSystemEvent({
238
- failed,
239
- total,
240
- error: lastFailedError,
241
- });
242
- }
243
- }
244
- if (ids.length > 0) {
245
- params.onSentMessageIds?.(ids);
246
- }
247
- };
248
-
249
- const {
250
- dispatcher,
251
- replyOptions,
252
- markDispatchIdle: baseMarkDispatchIdle,
253
- } = core.channel.reply.createReplyDispatcherWithTyping({
254
- ...replyPipeline,
255
- humanDelay: core.channel.reply.resolveHumanDelayConfig(params.cfg, params.agentId),
256
- onReplyStart: async () => {
257
- await streamController.onReplyStart();
258
- // Always start the typing keepalive loop when typing is enabled and
259
- // supported by this conversation type. The sendTypingIndicator gate
260
- // skips actual sends while the stream card is visually active, so
261
- // during the first text segment the user only sees the streaming UI.
262
- // Once the stream finalizes (between segments / during tool chains),
263
- // the loop starts sending typing activities and keeps the Bot Framework
264
- // TurnContext alive so the post-tool reply can still land. See #59731.
265
- if (typingIndicatorEnabled) {
266
- await typingCallbacks?.onReplyStart?.();
267
- }
268
- },
269
- typingCallbacks,
270
- deliver: async (payload) => {
271
- const preparedPayload = streamController.preparePayload(payload);
272
- if (!preparedPayload) {
273
- return;
274
- }
275
-
276
- const messages = renderReplyPayloadsToMessages([preparedPayload], {
277
- textChunkLimit: params.textLimit,
278
- chunkText: true,
279
- mediaMode: "split",
280
- tableMode,
281
- chunkMode,
282
- });
283
- pendingMessages.push(...messages);
284
-
285
- // When block streaming is enabled, flush immediately so blocks are
286
- // delivered progressively instead of batching until markDispatchIdle.
287
- if (blockStreamingEnabled) {
288
- await flushPendingMessages();
289
- }
290
- },
291
- onError: (err, info) => {
292
- const errMsg = formatUnknownError(err);
293
- const classification = classifyMSTeamsSendError(err);
294
- const hint = formatMSTeamsSendErrorHint(classification);
295
- params.runtime.error?.(
296
- `msteams ${info.kind} reply failed: ${errMsg}${hint ? ` (${hint})` : ""}`,
297
- );
298
- params.log.error("reply failed", {
299
- kind: info.kind,
300
- error: errMsg,
301
- classification,
302
- hint,
303
- });
304
- },
305
- });
306
-
307
- const markDispatchIdle = (): Promise<void> => {
308
- return flushPendingMessages()
309
- .catch((err) => {
310
- const errMsg = formatUnknownError(err);
311
- const classification = classifyMSTeamsSendError(err);
312
- const hint = formatMSTeamsSendErrorHint(classification);
313
- params.runtime.error?.(`msteams flush reply failed: ${errMsg}${hint ? ` (${hint})` : ""}`);
314
- params.log.error("flush reply failed", {
315
- error: errMsg,
316
- classification,
317
- hint,
318
- });
319
- })
320
- .then(() => {
321
- return streamController.finalize().catch((err) => {
322
- params.log.debug?.("stream finalize failed", { error: formatUnknownError(err) });
323
- });
324
- })
325
- .finally(() => {
326
- baseMarkDispatchIdle();
327
- });
328
- };
329
-
330
- return {
331
- dispatcher,
332
- replyOptions: {
333
- ...replyOptions,
334
- ...(streamController.hasStream()
335
- ? {
336
- onPartialReply: (payload: { text?: string }) =>
337
- streamController.onPartialReply(payload),
338
- }
339
- : {}),
340
- disableBlockStreaming:
341
- typeof msteamsCfg?.blockStreaming === "boolean" ? !msteamsCfg.blockStreaming : undefined,
342
- onModelSelected,
343
- },
344
- markDispatchIdle,
345
- };
346
- }
@@ -1,235 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
-
3
- const streamInstances = vi.hoisted(
4
- () =>
5
- [] as Array<{
6
- hasContent: boolean;
7
- isFinalized: boolean;
8
- isFailed: boolean;
9
- streamedLength: number;
10
- sendInformativeUpdate: ReturnType<typeof vi.fn>;
11
- update: ReturnType<typeof vi.fn>;
12
- finalize: ReturnType<typeof vi.fn>;
13
- }>,
14
- );
15
-
16
- vi.mock("./streaming-message.js", () => ({
17
- TeamsHttpStream: class {
18
- hasContent = false;
19
- isFinalized = false;
20
- isFailed = false;
21
- streamedLength = 0;
22
- sendInformativeUpdate = vi.fn(async () => {});
23
- update = vi.fn(function (
24
- this: { hasContent: boolean; streamedLength: number },
25
- payloadText?: string,
26
- ) {
27
- this.hasContent = true;
28
- this.streamedLength = payloadText?.length ?? 0;
29
- });
30
- finalize = vi.fn(async function (this: { isFinalized: boolean }) {
31
- this.isFinalized = true;
32
- });
33
-
34
- constructor() {
35
- streamInstances.push(this as never);
36
- }
37
- },
38
- }));
39
-
40
- import { createTeamsReplyStreamController } from "./reply-stream-controller.js";
41
-
42
- describe("createTeamsReplyStreamController", () => {
43
- function createController() {
44
- streamInstances.length = 0;
45
- return createTeamsReplyStreamController({
46
- conversationType: "personal",
47
- context: { sendActivity: vi.fn(async () => ({ id: "a" })) } as never,
48
- feedbackLoopEnabled: false,
49
- log: { debug: vi.fn() } as never,
50
- });
51
- }
52
-
53
- it("suppresses fallback for first text segment that was streamed", () => {
54
- const ctrl = createController();
55
- ctrl.onPartialReply({ text: "Hello world" });
56
-
57
- const result = ctrl.preparePayload({ text: "Hello world" });
58
- expect(result).toBeUndefined();
59
- });
60
-
61
- it("when stream fails after partial delivery, fallback sends only remaining text", () => {
62
- const ctrl = createController();
63
- const fullText = "a".repeat(4000) + "b".repeat(200);
64
-
65
- ctrl.onPartialReply({ text: fullText });
66
- streamInstances[0].hasContent = false;
67
- streamInstances[0].isFailed = true;
68
- streamInstances[0].isFinalized = true;
69
- streamInstances[0].streamedLength = 4000;
70
-
71
- const result = ctrl.preparePayload({ text: fullText });
72
- expect(result).toEqual({ text: "b".repeat(200) });
73
- });
74
-
75
- it("when stream fails before sending content, fallback sends full text", () => {
76
- const ctrl = createController();
77
- const fullText = "Failure at first chunk";
78
-
79
- ctrl.onPartialReply({ text: fullText });
80
- streamInstances[0].hasContent = false;
81
- streamInstances[0].isFailed = true;
82
- streamInstances[0].isFinalized = true;
83
- streamInstances[0].streamedLength = 0;
84
-
85
- const result = ctrl.preparePayload({ text: fullText });
86
- expect(result).toEqual({ text: fullText });
87
- });
88
-
89
- it("allows fallback delivery for second text segment after tool calls", () => {
90
- const ctrl = createController();
91
-
92
- // First text segment: streaming tokens arrive
93
- ctrl.onPartialReply({ text: "First segment" });
94
-
95
- // First segment complete: preparePayload suppresses (stream handled it)
96
- const result1 = ctrl.preparePayload({ text: "First segment" });
97
- expect(result1).toBeUndefined();
98
-
99
- // Tool calls happen... then second text segment arrives via deliver()
100
- // preparePayload should allow fallback delivery for this segment
101
- const result2 = ctrl.preparePayload({ text: "Second segment after tools" });
102
- expect(result2).toEqual({ text: "Second segment after tools" });
103
- });
104
-
105
- it("finalizes the stream when suppressing first segment", () => {
106
- const ctrl = createController();
107
- ctrl.onPartialReply({ text: "Streamed text" });
108
-
109
- ctrl.preparePayload({ text: "Streamed text" });
110
-
111
- expect(streamInstances[0]?.finalize).toHaveBeenCalled();
112
- });
113
-
114
- it("uses fallback even when onPartialReply fires after stream finalized", () => {
115
- const ctrl = createController();
116
-
117
- // First text segment: streaming tokens arrive
118
- ctrl.onPartialReply({ text: "First segment" });
119
-
120
- // First segment complete: preparePayload suppresses and finalizes stream
121
- const result1 = ctrl.preparePayload({ text: "First segment" });
122
- expect(result1).toBeUndefined();
123
- expect(streamInstances[0]?.isFinalized).toBe(true);
124
-
125
- // Post-tool partial replies fire again (stream.update is a no-op since finalized)
126
- ctrl.onPartialReply({ text: "Second segment" });
127
-
128
- // Must still use fallback because stream is finalized and can't deliver
129
- const result2 = ctrl.preparePayload({ text: "Second segment" });
130
- expect(result2).toEqual({ text: "Second segment" });
131
- });
132
-
133
- it("delivers all segments across 3+ tool call rounds", () => {
134
- const ctrl = createController();
135
-
136
- // Round 1: text → tool
137
- ctrl.onPartialReply({ text: "Segment 1" });
138
- expect(ctrl.preparePayload({ text: "Segment 1" })).toBeUndefined();
139
-
140
- // Round 2: text → tool
141
- ctrl.onPartialReply({ text: "Segment 2" });
142
- const r2 = ctrl.preparePayload({ text: "Segment 2" });
143
- expect(r2).toEqual({ text: "Segment 2" });
144
-
145
- // Round 3: final text
146
- ctrl.onPartialReply({ text: "Segment 3" });
147
- const r3 = ctrl.preparePayload({ text: "Segment 3" });
148
- expect(r3).toEqual({ text: "Segment 3" });
149
- });
150
-
151
- it("passes media+text payload through fully after stream finalized", () => {
152
- const ctrl = createController();
153
-
154
- // First segment streamed and finalized
155
- ctrl.onPartialReply({ text: "Streamed text" });
156
- ctrl.preparePayload({ text: "Streamed text" });
157
-
158
- // Second segment has both text and media — should pass through fully
159
- const result = ctrl.preparePayload({
160
- text: "Post-tool text with image",
161
- mediaUrl: "https://example.com/tool-output.png",
162
- });
163
- expect(result).toEqual({
164
- text: "Post-tool text with image",
165
- mediaUrl: "https://example.com/tool-output.png",
166
- });
167
- });
168
-
169
- it("still strips text from media payloads when stream handled text", () => {
170
- const ctrl = createController();
171
- ctrl.onPartialReply({ text: "Some text" });
172
-
173
- const result = ctrl.preparePayload({
174
- text: "Some text",
175
- mediaUrl: "https://example.com/image.png",
176
- });
177
- expect(result).toEqual({
178
- text: undefined,
179
- mediaUrl: "https://example.com/image.png",
180
- });
181
- });
182
-
183
- describe("isStreamActive", () => {
184
- it("returns false before any tokens arrive so typing keepalive can warm up", () => {
185
- const ctrl = createController();
186
- expect(ctrl.isStreamActive()).toBe(false);
187
- });
188
-
189
- it("returns false after the informative update but before tokens arrive", async () => {
190
- const ctrl = createController();
191
- await ctrl.onReplyStart();
192
- expect(ctrl.isStreamActive()).toBe(false);
193
- });
194
-
195
- it("returns true while the stream is actively receiving tokens", () => {
196
- const ctrl = createController();
197
- ctrl.onPartialReply({ text: "Streaming tokens" });
198
- expect(ctrl.isStreamActive()).toBe(true);
199
- });
200
-
201
- it("returns false after the stream is finalized between tool rounds", () => {
202
- const ctrl = createController();
203
-
204
- ctrl.onPartialReply({ text: "First segment" });
205
- expect(ctrl.isStreamActive()).toBe(true);
206
-
207
- // First segment complete: stream is finalized so the typing keepalive
208
- // can resume during the tool chain that follows.
209
- ctrl.preparePayload({ text: "First segment" });
210
- expect(ctrl.isStreamActive()).toBe(false);
211
- });
212
-
213
- it("returns false when the stream has failed", () => {
214
- const ctrl = createController();
215
-
216
- ctrl.onPartialReply({ text: "First segment" });
217
- expect(ctrl.isStreamActive()).toBe(true);
218
-
219
- streamInstances[0].isFailed = true;
220
- expect(ctrl.isStreamActive()).toBe(false);
221
- });
222
-
223
- it("returns false when conversationType is not personal", () => {
224
- streamInstances.length = 0;
225
- const ctrl = createTeamsReplyStreamController({
226
- conversationType: "channel",
227
- context: { sendActivity: vi.fn() } as never,
228
- feedbackLoopEnabled: false,
229
- log: { debug: vi.fn() } as never,
230
- });
231
- ctrl.onPartialReply({ text: "anything" });
232
- expect(ctrl.isStreamActive()).toBe(false);
233
- });
234
- });
235
- });