Skip to content

Commit ff000ef

Browse files
Merge remote-tracking branch 'origin/main' into pr-109807-merge
2 parents f6ed408 + 4e0cc18 commit ff000ef

9 files changed

Lines changed: 1242 additions & 75 deletions

‎extensions/msteams/src/monitor-handler.adaptive-card.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ async function runMessageActivity(params: {
9393
deps?: MSTeamsMessageHandlerDeps;
9494
}) {
9595
const deps = params.deps ?? createDeps();
96-
let messageHandler: ((context: unknown, next: () => Promise<void>) => Promise<void>) | undefined;
96+
let messageHandler: Parameters<MSTeamsActivityHandler["onMessage"]>[0] | undefined;
9797
const handler: MSTeamsActivityHandler = {
9898
onMessage: (callback) => {
9999
messageHandler = callback;

‎extensions/msteams/src/monitor-handler.ts‎

Lines changed: 38 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,17 @@ import type { MSTeamsMessageHandlerDeps } from "./monitor-handler.types.js";
66
import { resolveMSTeamsSenderAccess } from "./monitor-handler/access.js";
77
import { createMSTeamsMessageHandler } from "./monitor-handler/message-handler.js";
88
import { createMSTeamsReactionHandler } from "./monitor-handler/reaction-handler.js";
9+
import type { MSTeamsIngressDispatchResult, MSTeamsIngressLifecycle } from "./msteams-ingress.js";
910
import type { MSTeamsTurnContext } from "./sdk-types.js";
1011
import { buildGroupWelcomeText, buildWelcomeCard } from "./welcome-card.js";
1112

1213
export type MSTeamsActivityHandler = {
1314
onMessage: (
14-
handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
15+
handler: (
16+
context: unknown,
17+
next: () => Promise<void>,
18+
turnAdoptionLifecycle?: MSTeamsIngressLifecycle,
19+
) => Promise<MSTeamsIngressDispatchResult | void>,
1520
) => MSTeamsActivityHandler;
1621
onMembersAdded: (
1722
handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
@@ -22,7 +27,10 @@ export type MSTeamsActivityHandler = {
2227
onReactionsRemoved: (
2328
handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
2429
) => MSTeamsActivityHandler;
25-
run?: (context: unknown) => Promise<void>;
30+
run?: (
31+
context: unknown,
32+
turnAdoptionLifecycle?: MSTeamsIngressLifecycle,
33+
) => Promise<MSTeamsIngressDispatchResult | void>;
2634
};
2735

2836
async function isInvokeAuthorized(params: {
@@ -139,37 +147,53 @@ export function registerMSTeamsHandlers<T extends MSTeamsActivityHandler>(
139147
// Wrap the original run method to intercept invokes
140148
const originalRun = handler.run;
141149
if (originalRun) {
142-
handler.run = async (context: unknown) => {
150+
handler.run = async (context: unknown, turnAdoptionLifecycle?: MSTeamsIngressLifecycle) => {
143151
const ctx = context as MSTeamsTurnContext;
144152
// Non-poll adaptiveCard/action invokes get dispatched here as text so the
145153
// agent can react. Poll votes are intercepted in monitor.ts's
146154
// app.on("card.action") handler which returns the InvokeResponse to Teams.
147155
if (ctx.activity?.type === "invoke" && ctx.activity?.name === "adaptiveCard/action") {
148156
const text = serializeMSTeamsAdaptiveCardActionValue(ctx.activity?.value);
149157
if (text) {
150-
await handleTeamsMessage({
151-
...ctx,
152-
activity: {
153-
...ctx.activity,
154-
type: "message",
155-
text,
158+
return await handleTeamsMessage(
159+
{
160+
...ctx,
161+
activity: {
162+
...ctx.activity,
163+
type: "message",
164+
text,
165+
},
156166
},
157-
});
167+
turnAdoptionLifecycle,
168+
);
158169
}
159170
return;
160171
}
161172

162-
return originalRun.call(handler, context);
173+
return originalRun.call(handler, context, turnAdoptionLifecycle);
163174
};
164175
}
165176

166-
handler.onMessage(async (context, next) => {
177+
handler.onMessage(async (context, next, turnAdoptionLifecycle) => {
178+
let nextRan = false;
179+
const runNext = async () => {
180+
nextRan = true;
181+
await next();
182+
};
167183
try {
168-
await handleTeamsMessage(context as MSTeamsTurnContext);
184+
const result = await handleTeamsMessage(context as MSTeamsTurnContext, turnAdoptionLifecycle);
185+
await runNext();
186+
return result;
169187
} catch (err) {
188+
if (turnAdoptionLifecycle) {
189+
throw err;
190+
}
170191
deps.runtime.error(`msteams handler failed: ${formatUnknownError(err)}`);
171192
}
172-
await next();
193+
if (!nextRan) {
194+
await runNext();
195+
}
196+
return undefined;
173197
});
174198

175199
handler.onMembersAdded(async (context, next) => {
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
// Microsoft Teams tests cover durable claim ownership through inbound debounce.
2+
import { createInboundDebouncer } from "openclaw/plugin-sdk/channel-inbound-debounce";
3+
import { beforeEach, describe, expect, it, vi } from "vitest";
4+
import type { OpenClawConfig } from "../../runtime-api.js";
5+
import type { MSTeamsIngressLifecycle } from "../msteams-ingress.js";
6+
import type { MSTeamsTurnContext } from "../sdk-types.js";
7+
import "./message-handler-mock-support.test-support.js";
8+
import { getRuntimeApiMockState } from "./message-handler-mock-support.test-support.js";
9+
import { createMSTeamsMessageHandler } from "./message-handler.js";
10+
import { buildChannelActivity, createMessageHandlerDeps } from "./message-handler.test-support.js";
11+
12+
const runtimeApiMockState = getRuntimeApiMockState();
13+
14+
function createLifecycle(): MSTeamsIngressLifecycle & {
15+
adoptedCount: () => number;
16+
abandonedCount: () => number;
17+
} {
18+
let adopted = 0;
19+
let abandoned = 0;
20+
return {
21+
abortSignal: new AbortController().signal,
22+
onAdopted: async () => {
23+
adopted += 1;
24+
},
25+
onDeferred: () => {},
26+
onAdoptionFinalizing: () => {},
27+
onAbandoned: async () => {
28+
abandoned += 1;
29+
},
30+
adoptedCount: () => adopted,
31+
abandonedCount: () => abandoned,
32+
};
33+
}
34+
35+
function context(activity: MSTeamsTurnContext["activity"]): MSTeamsTurnContext {
36+
return {
37+
activity,
38+
sendActivity: vi.fn(async () => ({ id: "sent" })),
39+
sendActivities: vi.fn(async () => []),
40+
updateActivity: vi.fn(async () => ({ id: "updated" })),
41+
deleteActivity: vi.fn(async () => {}),
42+
};
43+
}
44+
45+
function directActivity(id: string, text: string): MSTeamsTurnContext["activity"] {
46+
return {
47+
...buildChannelActivity({
48+
id,
49+
text,
50+
conversation: { id: "dm-conversation", conversationType: "personal" },
51+
channelData: {},
52+
entities: [],
53+
}),
54+
} as MSTeamsTurnContext["activity"];
55+
}
56+
57+
function createHandler(cfg: OpenClawConfig) {
58+
const { deps } = createMessageHandlerDeps(cfg, {
59+
createInboundDebouncer,
60+
resolveInboundDebounceMs: vi.fn(() => 40),
61+
});
62+
return createMSTeamsMessageHandler(deps);
63+
}
64+
65+
describe("Microsoft Teams drain claim ownership", () => {
66+
beforeEach(() => {
67+
runtimeApiMockState.dispatchReplyWithBufferedBlockDispatcher.mockClear();
68+
});
69+
70+
it("defers a claimed activity and binds completion to reply adoption", async () => {
71+
const handler = createHandler({
72+
channels: { msteams: { dmPolicy: "open", allowFrom: ["*"] } },
73+
} as OpenClawConfig);
74+
const lifecycle = createLifecycle();
75+
76+
const result = await handler(context(directActivity("activity-one", "hello")), lifecycle);
77+
78+
expect(result).toEqual({ kind: "deferred" });
79+
await vi.waitFor(
80+
() => {
81+
expect(runtimeApiMockState.dispatchReplyWithBufferedBlockDispatcher).toHaveBeenCalledTimes(
82+
1,
83+
);
84+
expect(lifecycle.adoptedCount()).toBe(1);
85+
},
86+
{ timeout: 5_000 },
87+
);
88+
const dispatchParams = runtimeApiMockState.dispatchReplyWithBufferedBlockDispatcher.mock
89+
.calls[0]?.[0] as
90+
| { replyOptions?: { turnAdoptionLifecycle?: { admission?: string } } }
91+
| undefined;
92+
expect(dispatchParams?.replyOptions?.turnAdoptionLifecycle).toMatchObject({
93+
admission: "exclusive",
94+
});
95+
expect(lifecycle.abandonedCount()).toBe(0);
96+
});
97+
98+
it("fans merged-flush adoption to every constituent claim", async () => {
99+
const handler = createHandler({
100+
messages: { inbound: { debounceMs: 40 } },
101+
channels: { msteams: { dmPolicy: "open", allowFrom: ["*"] } },
102+
} as OpenClawConfig);
103+
const first = createLifecycle();
104+
const second = createLifecycle();
105+
106+
const results = [
107+
await handler(context(directActivity("activity-first", "part one")), first),
108+
await handler(context(directActivity("activity-second", "part two")), second),
109+
];
110+
111+
expect(results).toEqual([{ kind: "deferred" }, { kind: "deferred" }]);
112+
await vi.waitFor(
113+
() => {
114+
expect(runtimeApiMockState.dispatchReplyWithBufferedBlockDispatcher).toHaveBeenCalledTimes(
115+
1,
116+
);
117+
expect(first.adoptedCount()).toBe(1);
118+
expect(second.adoptedCount()).toBe(1);
119+
},
120+
{ timeout: 5_000 },
121+
);
122+
const dispatchParams = runtimeApiMockState.dispatchReplyWithBufferedBlockDispatcher.mock
123+
.calls[0]?.[0] as { ctx?: { BodyForAgent?: string } } | undefined;
124+
expect(dispatchParams?.ctx?.BodyForAgent).toContain("part one\npart two");
125+
expect(first.abandonedCount()).toBe(0);
126+
expect(second.abandonedCount()).toBe(0);
127+
});
128+
129+
it("completes a gated no-dispatch turn instead of stalling its claim", async () => {
130+
const { deps } = createMessageHandlerDeps(
131+
{
132+
channels: {
133+
msteams: {
134+
groupPolicy: "open",
135+
requireMention: true,
136+
},
137+
},
138+
} as OpenClawConfig,
139+
{
140+
createInboundDebouncer,
141+
resolveInboundDebounceMs: vi.fn(() => 20),
142+
},
143+
);
144+
const handler = createMSTeamsMessageHandler(deps);
145+
const lifecycle = createLifecycle();
146+
const gatedActivity = buildChannelActivity({
147+
id: "activity-gated",
148+
text: "not for the bot",
149+
entities: [],
150+
}) as MSTeamsTurnContext["activity"];
151+
152+
const result = await handler(context(gatedActivity), lifecycle);
153+
154+
expect(result).toEqual({ kind: "deferred" });
155+
await vi.waitFor(() => expect(lifecycle.adoptedCount()).toBe(1), { timeout: 5_000 });
156+
expect(runtimeApiMockState.dispatchReplyWithBufferedBlockDispatcher).not.toHaveBeenCalled();
157+
expect(lifecycle.abandonedCount()).toBe(0);
158+
});
159+
});

0 commit comments

Comments
 (0)