Skip to content

Commit 5b1c2ee

Browse files
committed
fix(slack): wake on user-group mentions
1 parent f739edc commit 5b1c2ee

7 files changed

Lines changed: 307 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ Docs: https://docs.openclaw.ai
2727
- macOS/Voice Wake: send wake-word and Push-to-Talk transcripts through the selected macOS session target instead of always falling back to main WebChat. Fixes #51040. Thanks @carl-jeffrolc.
2828
- Providers/xAI: give Grok `web_search` a 60s default timeout, harden malformed xAI Responses parsing, and return structured timeout errors instead of aborting the tool call. Fixes #58063 and #58733. Thanks @dnishimura, @marvcasasola-svg, and @Nanako0129.
2929
- Providers/configure: preserve the existing default model when adding or reauthing a provider whose plugin returns a default-model config patch. Fixes #50268. Thanks @rixcorp-oc.
30+
- Slack/mentions: resolve `<!subteam^...>` user-group mentions through Slack `usergroups.users.list` and treat them as explicit mentions only when the bot user is a member, so mention-gated agent channels wake for real user-group mentions without config-only allowlists. Fixes #73827. Thanks @CG-Intelligence-Agent-Jack.
3031
- Slack/message tool: let `read` fetch an exact Slack message timestamp, including a specific thread reply when paired with `threadId`, instead of returning only the parent thread or recent channel history. Fixes #53943. Thanks @zomars.
3132
- Web search: point missing-key errors to `web_fetch` for known URLs and the browser tool for interactive pages. Thanks @zhaoyang97.
3233
- Web search: late-bind managed agent `web_search` calls to the current runtime config snapshot, so existing sessions do not keep stale unresolved SecretRefs after secrets reload. Fixes #75420. Thanks @richardmqq.

‎docs/channels/slack.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ Base manifest (Socket Mode default):
205205
"pins:write",
206206
"reactions:read",
207207
"reactions:write",
208+
"usergroups:read",
208209
"users:read"
209210
]
210211
}
@@ -572,6 +573,7 @@ Current Slack message actions include `send`, `upload-file`, `download-file`, `r
572573
Mention sources:
573574

574575
- explicit app mention (`<@botId>`)
576+
- Slack user-group mention (`<!subteam^S...>`) when the bot user is a member of that user group; requires `usergroups:read`
575577
- mention regex patterns (`agents.list[].groupChat.mentionPatterns`, fallback `messages.groupChat.mentionPatterns`)
576578
- implicit reply-to-bot thread behavior (disabled when `thread.requireExplicitMention` is `true`)
577579

‎extensions/slack/src/monitor/message-handler/prepare.test.ts‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
createSlackSessionStoreFixture,
2828
createSlackTestAccount,
2929
} from "./prepare.test-helpers.js";
30+
import { clearSlackSubteamMentionCacheForTest } from "./subteam-mentions.js";
3031

3132
const enqueueSystemEventMock = vi.hoisted(() => vi.fn());
3233

@@ -49,6 +50,7 @@ describe("slack prepareSlackMessage inbound contract", () => {
4950
resetSlackThreadStarterCacheForTest();
5051
clearSlackThreadParticipationCache();
5152
clearSlackAllowFromCacheForTest();
53+
clearSlackSubteamMentionCacheForTest();
5254
enqueueSystemEventMock.mockClear();
5355
});
5456

@@ -1183,6 +1185,95 @@ describe("slack prepareSlackMessage inbound contract", () => {
11831185
expect(new Set([root!.ctxPayload.SessionKey, followUp!.ctxPayload.SessionKey]).size).toBe(1);
11841186
});
11851187

1188+
it("treats Slack user-group mentions as explicit mentions when the bot is a member", async () => {
1189+
const usergroupsUsersList = vi.fn().mockResolvedValue({
1190+
ok: true,
1191+
users: ["U_OTHER", "B1"],
1192+
});
1193+
const slackCtx = createInboundSlackCtx({
1194+
cfg: {
1195+
channels: {
1196+
slack: {
1197+
enabled: true,
1198+
groupPolicy: "open",
1199+
channels: { C0AGENTS: { requireMention: true } },
1200+
},
1201+
},
1202+
} as OpenClawConfig,
1203+
appClient: {
1204+
usergroups: { users: { list: usergroupsUsersList } },
1205+
} as unknown as App["client"],
1206+
defaultRequireMention: true,
1207+
});
1208+
slackCtx.resolveChannelName = async () => ({ name: "agents", type: "channel" });
1209+
slackCtx.resolveUserName = async () => ({ name: "Bek" });
1210+
1211+
const prepared = await prepareSlackMessage({
1212+
ctx: slackCtx,
1213+
account: createSlackAccount(),
1214+
message: {
1215+
type: "message",
1216+
channel: "C0AGENTS",
1217+
channel_type: "channel",
1218+
user: "U_BEK",
1219+
text: "<!subteam^S0AGENTS|agents> triage this",
1220+
ts: "1777244692.409919",
1221+
} as SlackMessageEvent,
1222+
opts: { source: "message" },
1223+
});
1224+
1225+
expect(usergroupsUsersList).toHaveBeenCalledWith({
1226+
usergroup: "S0AGENTS",
1227+
team_id: "T1",
1228+
});
1229+
expect(prepared).toBeTruthy();
1230+
expect(prepared!.ctxPayload.WasMentioned).toBe(true);
1231+
});
1232+
1233+
it("drops Slack user-group mentions when the bot is not a member", async () => {
1234+
const usergroupsUsersList = vi.fn().mockResolvedValue({
1235+
ok: true,
1236+
users: ["U_OTHER"],
1237+
});
1238+
const slackCtx = createInboundSlackCtx({
1239+
cfg: {
1240+
channels: {
1241+
slack: {
1242+
enabled: true,
1243+
groupPolicy: "open",
1244+
channels: { C0AGENTS: { requireMention: true } },
1245+
},
1246+
},
1247+
} as OpenClawConfig,
1248+
appClient: {
1249+
usergroups: { users: { list: usergroupsUsersList } },
1250+
} as unknown as App["client"],
1251+
defaultRequireMention: true,
1252+
});
1253+
slackCtx.resolveChannelName = async () => ({ name: "agents", type: "channel" });
1254+
slackCtx.resolveUserName = async () => ({ name: "Bek" });
1255+
1256+
const prepared = await prepareSlackMessage({
1257+
ctx: slackCtx,
1258+
account: createSlackAccount(),
1259+
message: {
1260+
type: "message",
1261+
channel: "C0AGENTS",
1262+
channel_type: "channel",
1263+
user: "U_BEK",
1264+
text: "<!subteam^S0AGENTS|agents> triage this",
1265+
ts: "1777244692.409920",
1266+
} as SlackMessageEvent,
1267+
opts: { source: "message" },
1268+
});
1269+
1270+
expect(usergroupsUsersList).toHaveBeenCalledWith({
1271+
usergroup: "S0AGENTS",
1272+
team_id: "T1",
1273+
});
1274+
expect(prepared).toBeNull();
1275+
});
1276+
11861277
it("keeps a regex-mentioned Slack thread root and URL-only follow-up on one parent session", async () => {
11871278
const { storePath } = storeFixture.makeTmpStorePath();
11881279
const rootTs = "1777244692.409919";

‎extensions/slack/src/monitor/message-handler/prepare.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ import { resolveSlackThreadStarter } from "../thread.js";
6262
import { resolveSlackMessageContent } from "./prepare-content.js";
6363
import { resolveSlackRoutingContext } from "./prepare-routing.js";
6464
import { resolveSlackThreadContextData } from "./prepare-thread-context.js";
65+
import { isSlackSubteamMentionForBot } from "./subteam-mentions.js";
6566
import type { PreparedSlackMessage } from "./types.js";
6667

6768
const mentionRegexCache = new WeakMap<SlackMonitorContext, Map<string, RegExp[]>>();
@@ -284,9 +285,17 @@ export async function prepareSlackMessage(params: {
284285
return null;
285286
}
286287
const { senderId, allowFromLower } = authorization;
287-
const hasAnyMention = /<@[^>]+>/.test(message.text ?? "");
288+
const hasAnyMention = /<@[^>]+>|<!subteam\^[^>]+>/.test(message.text ?? "");
288289
const explicitlyMentioned = Boolean(
289-
ctx.botUserId && message.text?.includes(`<@${ctx.botUserId}>`),
290+
ctx.botUserId &&
291+
(message.text?.includes(`<@${ctx.botUserId}>`) ||
292+
(await isSlackSubteamMentionForBot({
293+
client: ctx.app.client,
294+
text: message.text,
295+
botUserId: ctx.botUserId,
296+
teamId: ctx.teamId,
297+
log: logVerbose,
298+
}))),
290299
);
291300
const seedTopLevelRoomThreadBySource =
292301
opts.source === "app_mention" || opts.wasMentioned === true || explicitlyMentioned;
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import type { WebClient } from "@slack/web-api";
2+
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
import {
4+
clearSlackSubteamMentionCacheForTest,
5+
extractSlackSubteamMentionIds,
6+
isSlackSubteamMentionForBot,
7+
} from "./subteam-mentions.js";
8+
9+
function createClient(users: string[]) {
10+
return {
11+
usergroups: {
12+
users: {
13+
list: vi.fn(async () => ({ ok: true, users })),
14+
},
15+
},
16+
} as unknown as WebClient & {
17+
usergroups: { users: { list: ReturnType<typeof vi.fn> } };
18+
};
19+
}
20+
21+
describe("Slack subteam mentions", () => {
22+
beforeEach(() => {
23+
clearSlackSubteamMentionCacheForTest();
24+
});
25+
26+
it("extracts unique user-group ids from Slack mention tokens", () => {
27+
expect(
28+
extractSlackSubteamMentionIds("<!subteam^S123|eng> <!subteam^s456> <!subteam^S123>"),
29+
).toEqual(["S123", "S456"]);
30+
});
31+
32+
it("matches when the bot user is a member of a mentioned user group", async () => {
33+
const client = createClient(["U_OTHER", "U_BOT"]);
34+
35+
await expect(
36+
isSlackSubteamMentionForBot({
37+
client,
38+
text: "<!subteam^S123|eng> ping",
39+
botUserId: "u_bot",
40+
teamId: "T1",
41+
now: 1,
42+
}),
43+
).resolves.toBe(true);
44+
45+
expect(client.usergroups.users.list).toHaveBeenCalledWith({
46+
usergroup: "S123",
47+
team_id: "T1",
48+
});
49+
});
50+
51+
it("fails closed and caches successful membership lookups", async () => {
52+
const client = createClient(["U_OTHER"]);
53+
54+
await expect(
55+
isSlackSubteamMentionForBot({
56+
client,
57+
text: "<!subteam^S123> ping",
58+
botUserId: "U_BOT",
59+
now: 1,
60+
}),
61+
).resolves.toBe(false);
62+
await expect(
63+
isSlackSubteamMentionForBot({
64+
client,
65+
text: "<!subteam^S123> ping again",
66+
botUserId: "U_BOT",
67+
now: 2,
68+
}),
69+
).resolves.toBe(false);
70+
71+
expect(client.usergroups.users.list).toHaveBeenCalledTimes(1);
72+
});
73+
74+
it("fails closed when Slack rejects the user-group lookup", async () => {
75+
const log = vi.fn();
76+
const client = createClient([]);
77+
client.usergroups.users.list.mockRejectedValueOnce(new Error("missing_scope"));
78+
79+
await expect(
80+
isSlackSubteamMentionForBot({
81+
client,
82+
text: "<!subteam^S123> ping",
83+
botUserId: "U_BOT",
84+
log,
85+
}),
86+
).resolves.toBe(false);
87+
expect(log).toHaveBeenCalledWith(expect.stringContaining("missing_scope"));
88+
});
89+
});
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import type { WebClient } from "@slack/web-api";
2+
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
3+
import { normalizeOptionalString } from "openclaw/plugin-sdk/text-runtime";
4+
5+
const SUBTEAM_MENTION_RE = /<!subteam\^([A-Z0-9]+)(?:\|[^>]*)?>/gi;
6+
const SUBTEAM_MEMBER_CACHE_TTL_MS = 5 * 60 * 1000;
7+
8+
type CacheEntry = {
9+
expiresAt: number;
10+
users: ReadonlySet<string>;
11+
};
12+
13+
let subteamMemberCache = new WeakMap<WebClient, Map<string, CacheEntry>>();
14+
15+
function normalizeSlackId(value: unknown): string | undefined {
16+
return typeof value === "string" && value.trim() ? value.trim().toUpperCase() : undefined;
17+
}
18+
19+
export function extractSlackSubteamMentionIds(text?: string | null): string[] {
20+
if (!text) {
21+
return [];
22+
}
23+
const ids = new Set<string>();
24+
for (const match of text.matchAll(SUBTEAM_MENTION_RE)) {
25+
const id = normalizeSlackId(match[1]);
26+
if (id) {
27+
ids.add(id);
28+
}
29+
}
30+
return [...ids];
31+
}
32+
33+
async function readSlackSubteamUsers(params: {
34+
client: WebClient;
35+
subteamId: string;
36+
teamId?: string;
37+
now: number;
38+
log?: (message: string) => void;
39+
}): Promise<ReadonlySet<string>> {
40+
let bySubteam = subteamMemberCache.get(params.client);
41+
if (!bySubteam) {
42+
bySubteam = new Map<string, CacheEntry>();
43+
subteamMemberCache.set(params.client, bySubteam);
44+
}
45+
const cacheKey = `${normalizeSlackId(params.teamId) ?? ""}:${params.subteamId}`;
46+
const cached = bySubteam.get(cacheKey);
47+
if (cached && cached.expiresAt > params.now) {
48+
return cached.users;
49+
}
50+
51+
try {
52+
const response = await params.client.usergroups.users.list({
53+
usergroup: params.subteamId,
54+
...(params.teamId ? { team_id: params.teamId } : {}),
55+
});
56+
if (!response.ok) {
57+
params.log?.(
58+
`slack: failed to resolve user-group mention ${params.subteamId}: ${response.error ?? "unknown_error"}`,
59+
);
60+
return new Set();
61+
}
62+
const users = new Set(
63+
(response.users ?? []).map((userId) => normalizeSlackId(userId)).filter(Boolean) as string[],
64+
);
65+
bySubteam.set(cacheKey, {
66+
expiresAt: params.now + SUBTEAM_MEMBER_CACHE_TTL_MS,
67+
users,
68+
});
69+
return users;
70+
} catch (err) {
71+
params.log?.(
72+
`slack: failed to resolve user-group mention ${params.subteamId}: ${formatErrorMessage(err)}`,
73+
);
74+
return new Set();
75+
}
76+
}
77+
78+
export async function isSlackSubteamMentionForBot(params: {
79+
client: WebClient;
80+
text?: string | null;
81+
botUserId?: string | null;
82+
teamId?: string;
83+
now?: number;
84+
log?: (message: string) => void;
85+
}): Promise<boolean> {
86+
const botUserId = normalizeSlackId(params.botUserId);
87+
if (!botUserId) {
88+
return false;
89+
}
90+
const subteamIds = extractSlackSubteamMentionIds(params.text);
91+
if (subteamIds.length === 0) {
92+
return false;
93+
}
94+
const now = params.now ?? Date.now();
95+
for (const subteamId of subteamIds) {
96+
const users = await readSlackSubteamUsers({
97+
client: params.client,
98+
subteamId,
99+
teamId: normalizeOptionalString(params.teamId),
100+
now,
101+
log: params.log,
102+
});
103+
if (users.has(botUserId)) {
104+
return true;
105+
}
106+
}
107+
return false;
108+
}
109+
110+
export function clearSlackSubteamMentionCacheForTest(): void {
111+
subteamMemberCache = new WeakMap<WebClient, Map<string, CacheEntry>>();
112+
}

‎extensions/slack/src/setup-shared.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ export function buildSlackManifest(botName = "OpenClaw") {
5656
"pins:write",
5757
"reactions:read",
5858
"reactions:write",
59+
"usergroups:read",
5960
"users:read",
6061
],
6162
},

0 commit comments

Comments
 (0)