Skip to content

Commit 6efd013

Browse files
sjf-oasjf
andauthored
fix(slack): support Grid reaction and pin event listeners (#120944)
* fix(slack): support Grid reaction and pin events * refactor(slack): isolate system event routing * test(slack): align Grid event scope fixture * refactor(slack): pass optional event scope directly * fix(slack): support Grid member events --------- Co-authored-by: Sarah Fortune <[email protected]>
1 parent af708e6 commit 6efd013

18 files changed

Lines changed: 843 additions & 215 deletions

‎docs/channels/slack.md‎

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,9 @@ The relay URL must use `wss://` unless it targets localhost. Treat the bearer to
7272
One Slack account can receive messages from every workspace covered by an
7373
Enterprise Grid org-wide installation. Choose direct Socket Mode or HTTP
7474
Request URLs; relay mode is not supported for enterprise accounts. Both
75-
least-privilege manifests below enable only the V1 `message` and `app_mention`
76-
event path, immediate replies, and listener-owned status reactions.
75+
least-privilege manifests below enable the V1 message, mention, membership,
76+
reaction, and pin event paths, immediate replies, and listener-owned status
77+
reactions.
7778

7879
#### Socket Mode
7980

@@ -101,6 +102,8 @@ event path, immediate replies, and listener-owned status reactions.
101102
"im:read",
102103
"mpim:history",
103104
"mpim:read",
105+
"pins:read",
106+
"reactions:read",
104107
"reactions:write",
105108
"users:read"
106109
]
@@ -115,7 +118,13 @@ event path, immediate replies, and listener-owned status reactions.
115118
"message.channels",
116119
"message.groups",
117120
"message.im",
118-
"message.mpim"
121+
"message.mpim",
122+
"member_joined_channel",
123+
"member_left_channel",
124+
"pin_added",
125+
"pin_removed",
126+
"reaction_added",
127+
"reaction_removed"
119128
]
120129
}
121130
}
@@ -179,6 +188,8 @@ Socket Mode connection. Replace the example URL with the Gateway's public
179188
"im:read",
180189
"mpim:history",
181190
"mpim:read",
191+
"pins:read",
192+
"reactions:read",
182193
"reactions:write",
183194
"users:read"
184195
]
@@ -193,7 +204,13 @@ Socket Mode connection. Replace the example URL with the Gateway's public
193204
"message.channels",
194205
"message.groups",
195206
"message.im",
196-
"message.mpim"
207+
"message.mpim",
208+
"member_joined_channel",
209+
"member_left_channel",
210+
"pin_added",
211+
"pin_removed",
212+
"reaction_added",
213+
"reaction_removed"
197214
]
198215
}
199216
}
@@ -240,14 +257,16 @@ bot-authored `message` and `app_mention` events before dispatch, regardless of
240257
`allowBots`, because org installs do not provide a stable workspace-qualified
241258
bot identity for loop prevention.
242259

243-
Enterprise support accepts direct Socket Mode or HTTP `message` and
244-
`app_mention` events plus workspace-qualified outbound messages. Relay mode,
245-
slash commands, interactions, App Home, reaction event listeners, pins,
246-
Slack-native approvals, and bindings remain unavailable for an enterprise
247-
account. Slack action tools remain unavailable except for file uploads and
248-
adding or removing emoji reactions. Outbound acknowledgment, typing, and
249-
status reactions are supported and require `reactions:write`; inbound reaction
250-
notifications remain unavailable.
260+
Enterprise support accepts direct Socket Mode or HTTP message, mention,
261+
membership, reaction, and pin events plus workspace-qualified outbound
262+
messages. Relay mode, slash commands, channel lifecycle events, interactions,
263+
App Home, Agent and Assistant lifecycle events, Slack-native approvals, and
264+
bindings remain unavailable for an enterprise account. Slack action tools
265+
remain unavailable except for file uploads and adding or removing emoji
266+
reactions. Inbound membership, reaction, and pin notifications use the
267+
listener-owned, workspace-scoped Slack client. Outbound acknowledgment, typing,
268+
and status reactions are also supported through that client and require
269+
`reactions:write`.
251270

252271
OpenClaw records Enterprise Grid destinations as
253272
`team:<team-id>:channel:<channel-id>` or `team:<team-id>:user:<user-id>`.

‎extensions/slack/src/monitor/auth.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,7 @@ export async function authorizeSlackSystemEventSender(params: {
490490
senderId?: string;
491491
channelId?: string;
492492
channelType?: string | null;
493+
eventScope?: SlackEventScope;
493494
expectedSenderId?: string;
494495
/** When true, requires expectedSenderId, rejects ambiguous channel types,
495496
* and applies interactive-only owner allowFrom checks without changing the
@@ -518,7 +519,7 @@ export async function authorizeSlackSystemEventSender(params: {
518519
const info: {
519520
name?: string;
520521
type?: "im" | "mpim" | "channel" | "group";
521-
} = await params.ctx.resolveChannelName(channelId).catch(() => ({}));
522+
} = await params.ctx.resolveChannelName(channelId, params.eventScope).catch(() => ({}));
522523
channelName = info.name;
523524
const resolvedTypeSource = params.channelType ?? info.type;
524525
channelType = normalizeSlackChannelType(resolvedTypeSource, channelId);
@@ -564,7 +565,7 @@ export async function authorizeSlackSystemEventSender(params: {
564565
}
565566

566567
const senderInfo: { name?: string } = await params.ctx
567-
.resolveUserName(senderId)
568+
.resolveUserName(senderId, params.eventScope)
568569
.catch(() => ({}));
569570
const senderName = senderInfo.name;
570571
const ingressChannelType = channelType ?? "channel";

‎extensions/slack/src/monitor/context.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,13 @@ function createTestContext(params?: {
5858
});
5959
}
6060

61+
function createEnterpriseEventScope(teamId: string): SlackEventScope {
62+
return {
63+
teamId,
64+
client: {} as SlackEventScope["client"],
65+
};
66+
}
67+
6168
beforeEach(() => setSlackRuntime(null as never));
6269
afterEach(() => setSlackRuntime(null as never));
6370

@@ -143,6 +150,34 @@ describe("createSlackMonitorContext resolveSlackSystemEventSessionKey", () => {
143150
}),
144151
).toBe("agent:main:slack:group:c0mpdm42");
145152
});
153+
154+
it("partitions enterprise channel system events by workspace", () => {
155+
const ctx = createTestContext();
156+
const resolveForTeam = (teamId: string) =>
157+
ctx.resolveSlackSystemEventSessionKey({
158+
channelId: "C_SHARED",
159+
channelType: "channel",
160+
senderId: "U_ACTOR",
161+
eventScope: createEnterpriseEventScope(teamId),
162+
});
163+
164+
expect(resolveForTeam("T111")).toBe("agent:main:slack:channel:team:t111:channel:c_shared");
165+
expect(resolveForTeam("T222")).toBe("agent:main:slack:channel:team:t222:channel:c_shared");
166+
});
167+
168+
it("partitions enterprise main DM system events by workspace", () => {
169+
const ctx = createTestContext({ dmScope: "main" });
170+
const resolveForTeam = (teamId: string) =>
171+
ctx.resolveSlackSystemEventSessionKey({
172+
channelId: "D_SHARED",
173+
channelType: "im",
174+
senderId: "U_SHARED",
175+
eventScope: createEnterpriseEventScope(teamId),
176+
});
177+
178+
expect(resolveForTeam("T111")).toBe("agent:main:main:account:default:team:t111");
179+
expect(resolveForTeam("T222")).toBe("agent:main:main:account:default:team:t222");
180+
});
146181
});
147182

148183
describe("createSlackMonitorContext channel metadata cache", () => {

‎extensions/slack/src/monitor/context.ts‎

Lines changed: 26 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,8 @@ import type {
99
} from "openclaw/plugin-sdk/config-contracts";
1010
import type { SessionScope } from "openclaw/plugin-sdk/config-contracts";
1111
import type { DmPolicy, GroupPolicy } from "openclaw/plugin-sdk/config-contracts";
12-
import { resolveRuntimeConversationBindingRoute } from "openclaw/plugin-sdk/conversation-runtime";
1312
import { createDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
1413
import type { HistoryEntry } from "openclaw/plugin-sdk/reply-history";
15-
import { resolveAgentRoute } from "openclaw/plugin-sdk/routing";
1614
import { resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
1715
import { logVerbose } from "openclaw/plugin-sdk/runtime-env";
1816
import { getChildLogger } from "openclaw/plugin-sdk/runtime-env";
@@ -37,6 +35,8 @@ import {
3735
type SlackSuggestedPromptsInput,
3836
updateSlackSuggestedPrompts,
3937
} from "./suggested-prompts.js";
38+
import { resolveSlackSystemEventRouteSessionKey } from "./system-event-session.js";
39+
import { qualifySlackRoutePeerId } from "./workspace-routing.js";
4040

4141
export { normalizeSlackChannelType, resolveSlackChatType } from "./channel-type.js";
4242
export { DEFAULT_SLACK_SUGGESTED_PROMPTS } from "./suggested-prompts.js";
@@ -162,6 +162,7 @@ export type SlackMonitorContext = {
162162
channelType?: string | null;
163163
senderId?: string | null;
164164
threadTs?: string | null;
165+
eventScope?: SlackEventScope;
165166
}) => string;
166167
isChannelAllowed: (params: {
167168
channelId?: string;
@@ -381,13 +382,14 @@ export function createSlackMonitorContext(params: {
381382
channelType?: string | null;
382383
senderId?: string | null;
383384
threadTs?: string | null;
385+
eventScope?: SlackEventScope;
384386
}) => {
385387
const channelId = normalizeOptionalString(p.channelId) ?? "";
386388
const senderId = normalizeOptionalString(p.senderId) ?? "";
387389
// System events can omit channel_type too; prefer a type already seen on events
388390
// for this channel over C-prefix inference so they key the same session (#102676).
389391
const channelType = normalizeSlackChannelType(
390-
p.channelType ?? recallSlackChannelType(channelId),
392+
p.channelType ?? recallSlackChannelType(channelId, p.eventScope),
391393
channelId,
392394
);
393395
const isDirectMessage = channelType === "im";
@@ -401,60 +403,31 @@ export function createSlackMonitorContext(params: {
401403
? `slack:group:${channelId}`
402404
: `slack:channel:${channelId}`;
403405
const chatType = isDirectMessage ? "direct" : isGroup ? "group" : "channel";
404-
// Resolve through shared channel/account bindings so system events route to
405-
// the same agent session as regular inbound messages.
406-
try {
407-
const peerKind = isDirectMessage ? "direct" : isGroup ? "group" : "channel";
408-
const peerId = isDirectMessage ? senderId : channelId;
409-
if (peerId) {
410-
const route = resolveAgentRoute({
411-
cfg: params.cfg,
412-
channel: "slack",
413-
accountId: params.accountId,
414-
teamId: params.teamId,
415-
peer: { kind: peerKind, id: peerId },
416-
});
417-
const threadTs = normalizeOptionalString(p.threadTs);
418-
const baseConversationId = isDirectMessage ? `user:${senderId}` : channelId;
419-
const threadBindingRoute = threadTs
420-
? resolveRuntimeConversationBindingRoute({
421-
route,
422-
conversation: {
423-
channel: "slack",
424-
accountId: params.accountId,
425-
conversationId: threadTs,
426-
parentConversationId: baseConversationId,
427-
},
428-
})
429-
: null;
430-
const runtimeRoute =
431-
threadBindingRoute?.boundSessionKey || threadBindingRoute?.bindingRecord
432-
? threadBindingRoute
433-
: resolveRuntimeConversationBindingRoute({
434-
route,
435-
conversation: {
436-
channel: "slack",
437-
accountId: params.accountId,
438-
conversationId: baseConversationId,
439-
},
440-
});
441-
if (runtimeRoute.boundSessionKey) {
442-
return runtimeRoute.route.sessionKey;
443-
}
444-
return resolveThreadSessionKeys({
445-
baseSessionKey: runtimeRoute.route.sessionKey,
446-
threadId: threadTs,
447-
parentSessionKey:
448-
threadTs && params.threadInheritParent ? runtimeRoute.route.sessionKey : undefined,
449-
}).sessionKey;
450-
}
451-
} catch {
452-
// Fall through to legacy key derivation.
406+
const routedSessionKey = resolveSlackSystemEventRouteSessionKey({
407+
cfg: params.cfg,
408+
accountId: params.accountId,
409+
teamId: params.teamId,
410+
threadInheritParent: params.threadInheritParent,
411+
channelId,
412+
channelType,
413+
senderId,
414+
threadTs: p.threadTs,
415+
eventScope: p.eventScope,
416+
});
417+
if (routedSessionKey) {
418+
return routedSessionKey;
453419
}
454420

421+
const fallbackFrom = p.eventScope
422+
? `slack:${qualifySlackRoutePeerId({
423+
id: isDirectMessage ? senderId : channelId,
424+
kind: isDirectMessage ? "user" : "channel",
425+
eventScope: p.eventScope,
426+
})}`
427+
: from;
455428
const legacySessionKey = resolveSessionKey(
456429
params.sessionScope,
457-
{ From: from, ChatType: chatType, Provider: "slack" },
430+
{ From: fallbackFrom, ChatType: chatType, Provider: "slack" },
458431
params.mainKey,
459432
resolveDefaultAgentId(params.cfg),
460433
);
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// Slack tests cover Enterprise Grid event registration boundaries.
2+
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
3+
import type { ResolvedSlackAccount } from "../accounts.js";
4+
import type { SlackMonitorContext } from "./context.js";
5+
import type { SlackMessageHandler } from "./message-handler.js";
6+
7+
const registrations = vi.hoisted(() => ({
8+
agent: vi.fn(),
9+
assistant: vi.fn(),
10+
channel: vi.fn(),
11+
home: vi.fn(),
12+
interaction: vi.fn(),
13+
member: vi.fn(),
14+
message: vi.fn(),
15+
pin: vi.fn(),
16+
reaction: vi.fn(),
17+
}));
18+
19+
vi.mock("./events/agent.js", () => ({ registerSlackAgentEvents: registrations.agent }));
20+
vi.mock("./events/assistant.js", () => ({
21+
registerSlackAssistantEvents: registrations.assistant,
22+
}));
23+
vi.mock("./events/channels.js", () => ({ registerSlackChannelEvents: registrations.channel }));
24+
vi.mock("./events/home.js", () => ({ registerSlackHomeEvents: registrations.home }));
25+
vi.mock("./events/interactions.js", () => ({
26+
registerSlackInteractionEvents: registrations.interaction,
27+
}));
28+
vi.mock("./events/members.js", () => ({ registerSlackMemberEvents: registrations.member }));
29+
vi.mock("./events/messages.js", () => ({ registerSlackMessageEvents: registrations.message }));
30+
vi.mock("./events/pins.js", () => ({ registerSlackPinEvents: registrations.pin }));
31+
vi.mock("./events/reactions.js", () => ({
32+
registerSlackReactionEvents: registrations.reaction,
33+
}));
34+
35+
let registerSlackMonitorEvents: typeof import("./events.js").registerSlackMonitorEvents;
36+
37+
function registerForInstallation(kind: "enterprise" | "workspace") {
38+
const installationIdentity =
39+
kind === "enterprise"
40+
? ({ kind, enterpriseId: "E_TEST" } as const)
41+
: ({ kind, teamId: "T_TEST" } as const);
42+
registerSlackMonitorEvents({
43+
ctx: { installationIdentity } as SlackMonitorContext,
44+
account: {} as ResolvedSlackAccount,
45+
handleSlackMessage: vi.fn() as SlackMessageHandler,
46+
});
47+
}
48+
49+
describe("registerSlackMonitorEvents", () => {
50+
beforeAll(async () => {
51+
({ registerSlackMonitorEvents } = await import("./events.js"));
52+
});
53+
54+
beforeEach(() => {
55+
for (const registration of Object.values(registrations)) {
56+
registration.mockClear();
57+
}
58+
});
59+
60+
it("registers messages, reactions, pins, and member events for enterprise installs", () => {
61+
registerForInstallation("enterprise");
62+
63+
expect(registrations.message).toHaveBeenCalledOnce();
64+
expect(registrations.reaction).toHaveBeenCalledOnce();
65+
expect(registrations.pin).toHaveBeenCalledOnce();
66+
expect(registrations.member).toHaveBeenCalledOnce();
67+
expect(registrations.channel).not.toHaveBeenCalled();
68+
expect(registrations.home).not.toHaveBeenCalled();
69+
expect(registrations.agent).not.toHaveBeenCalled();
70+
expect(registrations.interaction).not.toHaveBeenCalled();
71+
expect(registrations.assistant).not.toHaveBeenCalled();
72+
});
73+
74+
it("preserves the full event set for workspace installs", () => {
75+
registerForInstallation("workspace");
76+
77+
for (const registration of Object.values(registrations)) {
78+
expect(registration).toHaveBeenCalledOnce();
79+
}
80+
});
81+
});

‎extensions/slack/src/monitor/events.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,13 @@ export function registerSlackMonitorEvents(params: {
2424
ctx: params.ctx,
2525
handleSlackMessage: params.handleSlackMessage,
2626
});
27+
registerSlackReactionEvents({ ctx: params.ctx, trackEvent: params.trackEvent });
28+
registerSlackPinEvents({ ctx: params.ctx, trackEvent: params.trackEvent });
29+
registerSlackMemberEvents({ ctx: params.ctx, trackEvent: params.trackEvent });
2730
if (params.ctx.installationIdentity.kind === "enterprise") {
2831
return;
2932
}
30-
registerSlackReactionEvents({ ctx: params.ctx, trackEvent: params.trackEvent });
31-
registerSlackMemberEvents({ ctx: params.ctx, trackEvent: params.trackEvent });
3233
registerSlackChannelEvents({ ctx: params.ctx, trackEvent: params.trackEvent });
33-
registerSlackPinEvents({ ctx: params.ctx, trackEvent: params.trackEvent });
3434
registerSlackHomeEvents({
3535
ctx: params.ctx,
3636
slashCommandName: params.appHomeSlashCommandName,

0 commit comments

Comments
 (0)