Skip to content

Commit d739c5d

Browse files
committed
fix(feishu): honor session activation mode for group admission
1 parent 9dc1694 commit d739c5d

4 files changed

Lines changed: 547 additions & 0 deletions

File tree

Lines changed: 299 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,299 @@
1+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2+
import { tmpdir } from "node:os";
3+
import { join } from "node:path";
4+
import type { EnvelopeFormatOptions } from "openclaw/plugin-sdk/channel-inbound";
5+
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6+
import type { ClawdbotConfig, PluginRuntime } from "../runtime-api.js";
7+
import type { FeishuMessageEvent } from "./bot.js";
8+
import { clearGroupNameCache, handleFeishuMessage } from "./bot.js";
9+
import { setFeishuRuntime } from "./runtime.js";
10+
11+
// Regression coverage for issue #50490: switching a Feishu group from
12+
// `mentionRequired: false` to `/activation mention` via the runtime command
13+
// must immediately gate non-@ messages. The shared command handler in
14+
// `src/auto-reply/reply/commands-session.ts` stores `groupActivation` on the
15+
// session entry; the Feishu admission gate has to consult it in addition to
16+
// the static config flag (Telegram and WhatsApp already do this).
17+
18+
const { mockCreateFeishuReplyDispatcher, mockCreateFeishuClient, mockResolveAgentRoute } =
19+
vi.hoisted(() => ({
20+
mockCreateFeishuReplyDispatcher: vi.fn((_params?: unknown) => ({
21+
dispatcher: {
22+
sendToolResult: vi.fn(),
23+
sendBlockReply: vi.fn(),
24+
sendFinalReply: vi.fn(),
25+
waitForIdle: vi.fn(),
26+
getQueuedCounts: vi.fn(() => ({ tool: 0, block: 0, final: 0 })),
27+
getFailedCounts: vi.fn(() => ({ tool: 0, block: 0, final: 0 })),
28+
markComplete: vi.fn(),
29+
},
30+
replyOptions: {},
31+
markDispatchIdle: vi.fn(),
32+
})),
33+
mockCreateFeishuClient: vi.fn(() => ({
34+
contact: {
35+
user: { get: vi.fn().mockResolvedValue({ data: { user: { name: "Sender" } } }) },
36+
},
37+
im: {
38+
chat: {
39+
get: vi.fn().mockResolvedValue({ code: 0, data: { name: "Group" } }),
40+
},
41+
},
42+
})),
43+
mockResolveAgentRoute: vi.fn(),
44+
}));
45+
46+
vi.mock("./reply-dispatcher.js", () => ({
47+
createFeishuReplyDispatcher: mockCreateFeishuReplyDispatcher,
48+
}));
49+
50+
vi.mock("./client.js", () => ({
51+
createFeishuClient: mockCreateFeishuClient,
52+
}));
53+
54+
function createRuntimeEnv() {
55+
return {
56+
log: vi.fn(),
57+
error: vi.fn(),
58+
writeStdout: vi.fn(),
59+
writeJson: vi.fn(),
60+
exit: vi.fn((code: number): never => {
61+
throw new Error(`exit ${code}`);
62+
}),
63+
};
64+
}
65+
66+
describe("Feishu group activation session override (#50490)", () => {
67+
const dispatched: Array<Record<string, unknown>> = [];
68+
let tmpStateDir: string;
69+
let sessionStorePath: string;
70+
71+
const mockFinalizeInboundContext: PluginRuntime["channel"]["reply"]["finalizeInboundContext"] = (
72+
ctx,
73+
) => {
74+
dispatched.push(ctx);
75+
return {
76+
...ctx,
77+
CommandAuthorized: typeof ctx.CommandAuthorized === "boolean" ? ctx.CommandAuthorized : false,
78+
CommandTurn: { kind: "normal", source: "message", authorized: false },
79+
};
80+
};
81+
const mockDispatchReplyFromConfig = vi
82+
.fn()
83+
.mockResolvedValue({ queuedFinal: false, counts: { final: 1 } });
84+
const mockWithReplyDispatcher: PluginRuntime["channel"]["reply"]["withReplyDispatcher"] = async ({
85+
dispatcher,
86+
run,
87+
onSettled,
88+
}) => {
89+
try {
90+
return await run();
91+
} finally {
92+
dispatcher.markComplete();
93+
try {
94+
await dispatcher.waitForIdle();
95+
} finally {
96+
await onSettled?.();
97+
}
98+
}
99+
};
100+
const resolveEnvelopeFormatOptionsMock: PluginRuntime["channel"]["reply"]["resolveEnvelopeFormatOptions"] =
101+
() => ({}) satisfies EnvelopeFormatOptions;
102+
103+
const runtimeStub = {
104+
system: { enqueueSystemEvent: vi.fn() },
105+
channel: {
106+
routing: {
107+
resolveAgentRoute: (params: unknown) => mockResolveAgentRoute(params),
108+
},
109+
session: {
110+
resolveStorePath: ((..._args: unknown[]) =>
111+
sessionStorePath) as unknown as PluginRuntime["channel"]["session"]["resolveStorePath"],
112+
recordInboundSession: vi.fn().mockResolvedValue(undefined),
113+
readSessionUpdatedAt: vi.fn(() => undefined),
114+
},
115+
reply: {
116+
resolveEnvelopeFormatOptions: resolveEnvelopeFormatOptionsMock,
117+
formatAgentEnvelope: vi.fn((params: { body: string }) => params.body),
118+
finalizeInboundContext: mockFinalizeInboundContext,
119+
dispatchReplyFromConfig: mockDispatchReplyFromConfig,
120+
withReplyDispatcher: mockWithReplyDispatcher,
121+
},
122+
commands: {
123+
shouldComputeCommandAuthorized: vi.fn(() => false),
124+
resolveCommandAuthorizedFromAuthorizers: vi.fn(() => false),
125+
},
126+
media: {
127+
saveMediaBuffer: vi.fn().mockResolvedValue({
128+
path: "/tmp/inbound-clip.mp4",
129+
contentType: "video/mp4",
130+
}),
131+
},
132+
inbound: {
133+
run: vi.fn(async (params: Parameters<PluginRuntime["channel"]["inbound"]["run"]>[0]) => {
134+
const input = await params.adapter.ingest(params.raw);
135+
if (!input) {
136+
return {
137+
admission: { kind: "drop" as const, reason: "ingest-null" },
138+
dispatched: false,
139+
};
140+
}
141+
const eventClass = { kind: "message" as const, canStartAgentTurn: true };
142+
const turn = await params.adapter.resolveTurn(input, eventClass, {});
143+
if (!("runDispatch" in turn)) {
144+
throw new Error("activation-override test runtime only supports prepared turns");
145+
}
146+
await turn.recordInboundSession({
147+
storePath: turn.storePath,
148+
sessionKey: turn.ctxPayload.SessionKey ?? turn.routeSessionKey,
149+
ctx: turn.ctxPayload,
150+
groupResolution: turn.record?.groupResolution,
151+
createIfMissing: turn.record?.createIfMissing,
152+
updateLastRoute: turn.record?.updateLastRoute,
153+
onRecordError: turn.record?.onRecordError ?? (() => undefined),
154+
});
155+
return {
156+
admission: { kind: "dispatch" as const },
157+
dispatched: true,
158+
ctxPayload: turn.ctxPayload,
159+
routeSessionKey: turn.routeSessionKey,
160+
dispatchResult: await turn.runDispatch(),
161+
};
162+
}),
163+
},
164+
pairing: {
165+
readAllowFromStore: vi.fn().mockResolvedValue([]),
166+
upsertPairingRequest: vi.fn().mockResolvedValue({ code: "ABCDEFGH", created: false }),
167+
buildPairingReply: vi.fn(() => "Pairing response"),
168+
},
169+
},
170+
media: { detectMime: vi.fn(async () => "application/octet-stream") },
171+
} as unknown as PluginRuntime;
172+
173+
function createOpenGroupConfig(): ClawdbotConfig {
174+
return {
175+
channels: {
176+
feishu: {
177+
appId: "cli_test",
178+
appSecret: "sec_test", // pragma: allowlist secret
179+
groupPolicy: "open",
180+
// Static config admits every group message. The session-level
181+
// `/activation mention` override must still kick in.
182+
requireMention: false,
183+
},
184+
},
185+
};
186+
}
187+
188+
function createMentionRequiredGroupConfig(): ClawdbotConfig {
189+
return {
190+
channels: {
191+
feishu: {
192+
appId: "cli_test",
193+
appSecret: "sec_test", // pragma: allowlist secret
194+
groupPolicy: "open",
195+
requireMention: true,
196+
},
197+
},
198+
};
199+
}
200+
201+
function createInboundEvent(options: {
202+
messageId: string;
203+
mentioned: boolean;
204+
}): FeishuMessageEvent {
205+
return {
206+
sender: { sender_id: { open_id: "ou-sender" } },
207+
message: {
208+
message_id: options.messageId,
209+
chat_id: "oc-activation-group",
210+
chat_type: "group",
211+
message_type: "text",
212+
content: JSON.stringify({ text: options.mentioned ? "@bot hello" : "hello" }),
213+
...(options.mentioned
214+
? {
215+
mentions: [
216+
{
217+
key: "@_user_1",
218+
id: { open_id: "bot-open-id" },
219+
name: "Bot",
220+
tenant_key: "",
221+
},
222+
],
223+
}
224+
: {}),
225+
},
226+
};
227+
}
228+
229+
beforeEach(() => {
230+
vi.clearAllMocks();
231+
clearGroupNameCache();
232+
dispatched.length = 0;
233+
tmpStateDir = mkdtempSync(join(tmpdir(), "feishu-activation-"));
234+
sessionStorePath = join(tmpStateDir, "sessions.json");
235+
mockResolveAgentRoute.mockReturnValue({
236+
agentId: "main",
237+
channel: "feishu",
238+
accountId: "default",
239+
sessionKey: "agent:main:feishu:group:oc-activation-group",
240+
mainSessionKey: "agent:main:main",
241+
lastRoutePolicy: "session",
242+
matchedBy: "default",
243+
});
244+
setFeishuRuntime(runtimeStub);
245+
});
246+
247+
afterEach(() => {
248+
rmSync(tmpStateDir, { recursive: true, force: true });
249+
});
250+
251+
afterAll(() => {
252+
vi.doUnmock("./reply-dispatcher.js");
253+
vi.doUnmock("./client.js");
254+
vi.resetModules();
255+
});
256+
257+
function writeSessionActivation(activation: "mention" | "always" | undefined) {
258+
const entry =
259+
activation === undefined
260+
? {}
261+
: { "agent:main:feishu:group:oc-activation-group": { groupActivation: activation } };
262+
writeFileSync(sessionStorePath, JSON.stringify(entry), "utf-8");
263+
}
264+
265+
it("drops non-mentioned group messages once /activation mention is recorded on the session entry", async () => {
266+
// Reproduces #50490. With `mentionRequired: false` the config-only gate
267+
// would admit every message, but the runtime override must trump it.
268+
// We assert that the gate returns early — `inbound.run` is not even
269+
// entered, so `finalizeInboundContext` / `dispatchReplyFromConfig` stay
270+
// untouched. Admission of @-mentioned messages keeps working because the
271+
// override only flips `requireMention`, not anything downstream — that is
272+
// covered by the existing `handleFeishuMessage` suite.
273+
writeSessionActivation("mention");
274+
275+
await handleFeishuMessage({
276+
cfg: createOpenGroupConfig(),
277+
event: createInboundEvent({ messageId: "msg-no-mention", mentioned: false }),
278+
runtime: createRuntimeEnv(),
279+
});
280+
281+
expect(dispatched).toHaveLength(0);
282+
expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
283+
});
284+
285+
it("admits non-mentioned group messages once /activation always is recorded on the session entry", async () => {
286+
// Covers the inverse override: static config requires @-mentions, but the
287+
// runtime session switch must force the group back to always-on admission.
288+
writeSessionActivation("always");
289+
290+
await handleFeishuMessage({
291+
cfg: createMentionRequiredGroupConfig(),
292+
event: createInboundEvent({ messageId: "msg-always-no-mention", mentioned: false }),
293+
runtime: createRuntimeEnv(),
294+
});
295+
296+
expect(dispatched).toHaveLength(1);
297+
expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
298+
});
299+
});

‎extensions/feishu/src/bot.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,10 @@ import { createFeishuClient } from "./client.js";
5050
import { finalizeFeishuMessageProcessing, tryRecordMessagePersistent } from "./dedup.js";
5151
import { resolveFeishuMessageDedupeKey } from "./dedupe-key.js";
5252
import { maybeCreateDynamicAgent } from "./dynamic-agent.js";
53+
import {
54+
applyFeishuGroupActivationOverride,
55+
resolveFeishuGroupActivationOverride,
56+
} from "./group-activation.js";
5357
import { extractMentionTargets, isMentionForwardRequest } from "./mention.js";
5458
import {
5559
hasExplicitFeishuGroupConfig,
@@ -696,6 +700,40 @@ export async function handleFeishuMessage(params: {
696700
groupPolicy,
697701
}));
698702

703+
// Honor the session-level `/activation mention|always` override before
704+
// gating non-mentioned messages. Without this the config-only
705+
// `mentionRequired` decides admission and the runtime switch silently
706+
// has no effect (#50490). Mirrors Telegram (`bot-core.ts`
707+
// `resolveGroupActivation`) and WhatsApp (`group-activation.ts`
708+
// `resolveGroupActivationFor`) / QQBot (`engine/group/activation.ts`).
709+
const activationRuntime = getFeishuRuntime();
710+
const activationRoute = activationRuntime.channel.routing.resolveAgentRoute({
711+
cfg,
712+
channel: "feishu",
713+
accountId: account.accountId,
714+
peer: {
715+
kind: "group",
716+
id: groupSession?.peerId ?? ctx.chatId,
717+
},
718+
parentPeer: groupSession?.parentPeer ?? null,
719+
});
720+
const activationStorePath = activationRuntime.channel.session.resolveStorePath(
721+
cfg.session?.store,
722+
{ agentId: activationRoute.agentId },
723+
);
724+
const sessionGroupActivation = resolveFeishuGroupActivationOverride({
725+
storePath: activationStorePath,
726+
sessionKey: activationRoute.sessionKey,
727+
onError: (err) =>
728+
log(
729+
`feishu[${account.accountId}]: failed to load session activation for ${activationRoute.sessionKey}: ${String(err)}`,
730+
),
731+
});
732+
requireMention = applyFeishuGroupActivationOverride({
733+
configRequireMention: requireMention,
734+
activation: sessionGroupActivation,
735+
});
736+
699737
const groupSenderActivationIngress = await resolveFeishuGroupSenderActivationIngressAccess({
700738
cfg,
701739
accountId: account.accountId,

0 commit comments

Comments
 (0)