Skip to content

Commit 97f2882

Browse files
committed
fix(slack): scope Grid native approvals by team
1 parent df2edbc commit 97f2882

15 files changed

Lines changed: 405 additions & 116 deletions

‎docs/channels/slack.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -242,11 +242,12 @@ bot identity for loop prevention.
242242

243243
Enterprise support accepts direct Socket Mode or HTTP `message` and
244244
`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
245+
slash commands, general interactions, App Home, reaction event listeners,
246+
pins, and bindings remain unavailable for an enterprise account. Slack-native
247+
approval buttons are supported and stay scoped to the workspace that originated
248+
the approval. Slack action tools remain unavailable except for file uploads and
249+
adding or removing emoji reactions. Outbound acknowledgment, typing, and status
250+
reactions are supported and require `reactions:write`; inbound reaction
250251
notifications remain unavailable.
251252

252253
OpenClaw records Enterprise Grid destinations as
@@ -1738,6 +1739,7 @@ Slack can act as a native approval client with interactive buttons and interacti
17381739
- Plugin approvals use Slack-native buttons when Slack is enabled as a native approval client for the originating session, or when `approvals.plugin` routes to the originating Slack session or a Slack target.
17391740
- Plugin approval DMs use Slack plugin approvers from `channels.slack.allowFrom`, named-account `allowFrom`, or the account default route.
17401741
- Approver authorization is still enforced: exec-only approvers cannot approve plugin requests unless they are also plugin approvers.
1742+
- Enterprise Grid org installs derive the workspace from the qualified Slack origin target. Approval prompts, approver DMs, button callbacks, and final message updates stay in that workspace.
17411743

17421744
This uses the same shared approval button surface as other channels. When `interactivity` is enabled in your Slack app settings, approval prompts render as Block Kit buttons directly in the conversation.
17431745
When those buttons are present, they are the primary approval UX; OpenClaw

‎docs/gateway/config-channels.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -480,11 +480,13 @@ WhatsApp runs through the gateway's web channel (Baileys Web). It starts automat
480480
`allowFrom: ["*"]`. Channel and user policies must use stable Slack IDs;
481481
mutable names and unsupported channel prefixes fail startup. V1 handles only
482482
direct Socket Mode or HTTP `message` and `app_mention` events with immediate
483-
replies; relay, commands, interactions, App Home, reaction event listeners,
484-
pins, action tools, native approvals, bindings, deferred delivery, and
485-
proactive sends are unavailable. Listener-owned acknowledgment, typing, and
486-
status reactions remain available with `reactions:write`; inbound reaction
487-
notifications and reaction action tools are unavailable. See
483+
replies; relay, commands, general interactions, App Home, reaction event
484+
listeners, pins, action tools, bindings, deferred delivery, and proactive
485+
sends are unavailable. Slack-native approval buttons remain available and
486+
use the originating workspace for delivery and updates. Listener-owned
487+
acknowledgment, typing, and status reactions remain available with
488+
`reactions:write`; inbound reaction notifications and reaction action tools
489+
are unavailable. See
488490
[Enterprise Grid org-wide installs](/channels/slack#enterprise-grid-org-wide-installs)
489491
for the least-privilege manifest, setup workflow, and complete restrictions.
490492
- `botToken`, `appToken`, `signingSecret`, and `userToken` accept plaintext

‎extensions/slack/src/approval-handler.runtime.test.ts‎

Lines changed: 86 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,27 @@ import type {
33
ApprovalActionView,
44
ApprovalMetadataView,
55
} from "openclaw/plugin-sdk/approval-handler-runtime";
6-
import { describe, expect, it, vi } from "vitest";
6+
import { beforeEach, describe, expect, it, vi } from "vitest";
77
import { decodeSlackApprovalAction } from "./approval-actions.js";
88
import { slackApprovalNativeRuntime } from "./approval-handler.runtime.js";
9-
import { countSlackTextUtf8Bytes } from "./truncate.js";
9+
10+
const { sendMessageSlackMock, updateMessageSlackMock } = vi.hoisted(() => ({
11+
sendMessageSlackMock: vi.fn(),
12+
updateMessageSlackMock: vi.fn(),
13+
}));
14+
15+
vi.mock("./send.js", () => ({
16+
sendMessageSlack: sendMessageSlackMock,
17+
updateMessageSlack: updateMessageSlackMock,
18+
}));
1019

1120
type SlackPayload = {
1221
text: string;
1322
blocks?: unknown;
1423
};
15-
type ChatUpdatePayload = {
16-
channel?: string;
17-
ts?: string;
18-
text?: string;
19-
blocks?: unknown;
20-
};
2124
type SlackUpdateEntryParams = Parameters<
2225
NonNullable<typeof slackApprovalNativeRuntime.transport.updateEntry>
2326
>[0];
24-
const SLACK_CHAT_UPDATE_TEXT_MAX_BYTES = 4000;
2527
const APPROVAL_TIMING = {
2628
createdAtMs: 0,
2729
expiresAtMs: 60_000,
@@ -220,29 +222,14 @@ function decodeSlackApprovalElements(block: { elements?: unknown[] } | undefined
220222
);
221223
}
222224

223-
function readChatUpdatePayload(
224-
chatUpdate: { mock: { calls: unknown[][] } },
225-
index: number,
226-
): ChatUpdatePayload {
227-
const call = chatUpdate.mock.calls[index];
228-
if (!call) {
229-
throw new Error(`Expected Slack chat.update call #${index + 1}`);
230-
}
231-
const [payload] = call;
232-
if (!payload || typeof payload !== "object") {
233-
throw new Error(`Expected Slack chat.update payload #${index + 1}`);
234-
}
235-
return payload as ChatUpdatePayload;
236-
}
237-
238225
async function updateSlackApprovalEntry(
239226
context: SlackUpdateEntryParams["context"],
240227
payload: SlackUpdateEntryParams["payload"],
241228
): Promise<void> {
242229
await slackApprovalNativeRuntime.transport.updateEntry?.({
243230
...APPROVAL_CONTEXT,
244231
context,
245-
entry: { channelId: "C123", messageTs: "1712345678.999999" },
232+
entry: { channelId: "C123", messageTs: "1712345678.999999", teamId: "T123" },
246233
payload,
247234
phase: "resolved",
248235
});
@@ -300,10 +287,73 @@ function findApprovalMrkdwn(payload: SlackPayload, prefix: string): string {
300287
}
301288

302289
describe("slackApprovalNativeRuntime", () => {
290+
beforeEach(() => {
291+
sendMessageSlackMock.mockReset();
292+
updateMessageSlackMock.mockReset();
293+
});
294+
303295
it("subscribes to plugin approval events", () => {
304296
expect(slackApprovalNativeRuntime.eventKinds).toEqual(["exec", "plugin"]);
305297
});
306298

299+
it("carries a qualified target workspace into the pending approval receipt", async () => {
300+
const request = {
301+
id: "req-grid",
302+
request: { command: "echo hi" },
303+
...APPROVAL_TIMING,
304+
};
305+
const pendingPayload = { text: "Approval required", blocks: [] };
306+
const prepared = await slackApprovalNativeRuntime.transport.prepareTarget({
307+
...APPROVAL_CONTEXT,
308+
plannedTarget: {
309+
surface: "origin",
310+
reason: "preferred",
311+
target: { to: "team:T123:channel:C123", threadId: "1712345678.100000" },
312+
},
313+
request,
314+
approvalKind: "exec",
315+
view: {} as never,
316+
pendingPayload,
317+
});
318+
if (!prepared) {
319+
throw new Error("expected prepared Slack approval target");
320+
}
321+
sendMessageSlackMock.mockResolvedValueOnce({
322+
channelId: "C123",
323+
messageId: "1712345678.200000",
324+
});
325+
326+
const entry = await slackApprovalNativeRuntime.transport.deliverPending({
327+
...APPROVAL_CONTEXT,
328+
plannedTarget: {
329+
surface: "origin",
330+
reason: "preferred",
331+
target: { to: "team:T123:channel:C123", threadId: "1712345678.100000" },
332+
},
333+
preparedTarget: prepared.target,
334+
request,
335+
approvalKind: "exec",
336+
view: {} as never,
337+
pendingPayload,
338+
});
339+
340+
expect(prepared.target).toEqual({
341+
to: "team:T123:channel:C123",
342+
threadTs: "1712345678.100000",
343+
teamId: "T123",
344+
});
345+
expect(sendMessageSlackMock).toHaveBeenCalledWith(
346+
"team:T123:channel:C123",
347+
"Approval required",
348+
expect.objectContaining({ accountId: "default", threadTs: "1712345678.100000" }),
349+
);
350+
expect(entry).toEqual({
351+
channelId: "C123",
352+
messageTs: "1712345678.200000",
353+
teamId: "T123",
354+
});
355+
});
356+
307357
it("does not leave dangling surrogates when truncating exec approval command mrkdwn", async () => {
308358
const commandText = `${"a".repeat(2598)}😀tail`;
309359
const payload = await buildExecPendingPayload({
@@ -434,7 +484,7 @@ describe("slackApprovalNativeRuntime", () => {
434484
).toBe(false);
435485
});
436486

437-
it("caps resolved update fallback text to Slack chat.update limits while preserving blocks", async () => {
487+
it("updates a delivered approval through its persisted workspace scope", async () => {
438488
const blocks = [
439489
{
440490
type: "section",
@@ -444,36 +494,22 @@ describe("slackApprovalNativeRuntime", () => {
444494
},
445495
},
446496
];
447-
const chatUpdate = vi.fn(async (_payload: { text: string; blocks: typeof blocks }) => ({}));
448497
const context = {
449-
app: {
450-
client: {
451-
chat: {
452-
update: chatUpdate,
453-
},
454-
},
455-
},
498+
app: {},
456499
config: {},
457500
} as never;
458501

459-
await updateSlackApprovalEntry(context, {
460-
text: "a".repeat(SLACK_CHAT_UPDATE_TEXT_MAX_BYTES),
502+
await updateSlackApprovalEntry(context, { text: "Resolved", blocks });
503+
504+
expect(updateMessageSlackMock).toHaveBeenCalledWith({
505+
cfg: APPROVAL_CONTEXT.cfg,
506+
accountId: "default",
507+
teamId: "T123",
508+
channelId: "C123",
509+
messageTs: "1712345678.999999",
510+
text: "Resolved",
461511
blocks,
462512
});
463-
464-
await updateSlackApprovalEntry(context, { text: "a".repeat(5000), blocks });
465-
466-
const firstUpdate = readChatUpdatePayload(chatUpdate, 0);
467-
const secondUpdate = readChatUpdatePayload(chatUpdate, 1);
468-
expect(firstUpdate.channel).toBe("C123");
469-
expect(firstUpdate.ts).toBe("1712345678.999999");
470-
expect(firstUpdate.text).toBe("a".repeat(SLACK_CHAT_UPDATE_TEXT_MAX_BYTES));
471-
expect(firstUpdate.blocks).toBe(blocks);
472-
expect(secondUpdate.channel).toBe("C123");
473-
expect(secondUpdate.ts).toBe("1712345678.999999");
474-
expect(secondUpdate.text).toMatch(/…$/);
475-
expect(secondUpdate.blocks).toBe(blocks);
476-
expect(countSlackTextUtf8Bytes(secondUpdate.text ?? "")).toBe(SLACK_CHAT_UPDATE_TEXT_MAX_BYTES);
477513
});
478514

479515
it("keeps pending metadata context within Slack Block Kit limits", async () => {

‎extensions/slack/src/approval-handler.runtime.ts‎

Lines changed: 32 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,15 @@ import {
2525
shouldHandleSlackNativeApprovalRequest,
2626
} from "./approval-native-gates.js";
2727
import { normalizeSlackApproverId } from "./exec-approvals.js";
28-
import { SLACK_EDIT_TEXT_MAX_BYTES } from "./limits.js";
2928
import { resolveSlackReplyBlocks } from "./reply-blocks.js";
30-
import { sendMessageSlack } from "./send.js";
31-
import { truncateSlackTextByUtf8Bytes } from "./truncate.js";
29+
import { sendMessageSlack, updateMessageSlack } from "./send.js";
30+
import { parseSlackTarget } from "./target-parsing.js";
3231

3332
type SlackBlock = Block | KnownBlock;
3433
type SlackPendingApproval = {
3534
channelId: string;
3635
messageTs: string;
36+
teamId?: string;
3737
};
3838
type SlackPendingDelivery = {
3939
text: string;
@@ -407,28 +407,9 @@ function buildSlackExpiredBlocks(view: ExpiredApprovalView): SlackBlock[] {
407407
: buildSlackExecExpiredBlocks(view);
408408
}
409409

410-
async function updateMessage(params: {
411-
app: App;
412-
channelId: string;
413-
messageTs: string;
414-
text: string;
415-
blocks: SlackBlock[];
416-
}): Promise<void> {
417-
try {
418-
await params.app.client.chat.update({
419-
channel: params.channelId,
420-
ts: params.messageTs,
421-
text: truncateSlackTextByUtf8Bytes(params.text, SLACK_EDIT_TEXT_MAX_BYTES),
422-
blocks: params.blocks,
423-
});
424-
} catch (err) {
425-
logError(`slack approvals: failed to update message: ${String(err)}`);
426-
}
427-
}
428-
429410
export const slackApprovalNativeRuntime = createChannelApprovalNativeRuntimeAdapter<
430411
SlackPendingDelivery,
431-
{ to: string; threadTs?: string },
412+
{ to: string; threadTs?: string; teamId?: string },
432413
SlackPendingApproval,
433414
never,
434415
SlackPendingDelivery
@@ -478,14 +459,20 @@ export const slackApprovalNativeRuntime = createChannelApprovalNativeRuntimeAdap
478459
}),
479460
},
480461
transport: {
481-
prepareTarget: ({ plannedTarget }) => ({
482-
dedupeKey: buildChannelApprovalNativeTargetKey(plannedTarget.target),
483-
target: {
484-
to: plannedTarget.target.to,
485-
threadTs:
486-
plannedTarget.target.threadId != null ? String(plannedTarget.target.threadId) : undefined,
487-
},
488-
}),
462+
prepareTarget: ({ plannedTarget }) => {
463+
const teamId = parseSlackTarget(plannedTarget.target.to, { defaultKind: "channel" })?.teamId;
464+
return {
465+
dedupeKey: buildChannelApprovalNativeTargetKey(plannedTarget.target),
466+
target: {
467+
to: plannedTarget.target.to,
468+
threadTs:
469+
plannedTarget.target.threadId != null
470+
? String(plannedTarget.target.threadId)
471+
: undefined,
472+
...(teamId ? { teamId } : {}),
473+
},
474+
};
475+
},
489476
deliverPending: async ({ cfg, accountId, context, preparedTarget, pendingPayload }) => {
490477
const resolved = resolveHandlerContext({ cfg, accountId, context });
491478
if (!resolved) {
@@ -501,6 +488,7 @@ export const slackApprovalNativeRuntime = createChannelApprovalNativeRuntimeAdap
501488
return {
502489
channelId: message.channelId,
503490
messageTs: message.messageId,
491+
...(preparedTarget.teamId ? { teamId: preparedTarget.teamId } : {}),
504492
};
505493
},
506494
updateEntry: async ({ cfg, accountId, context, entry, payload }) => {
@@ -509,13 +497,19 @@ export const slackApprovalNativeRuntime = createChannelApprovalNativeRuntimeAdap
509497
return;
510498
}
511499
const nextPayload = payload;
512-
await updateMessage({
513-
app: resolved.context.app,
514-
channelId: entry.channelId,
515-
messageTs: entry.messageTs,
516-
text: nextPayload.text,
517-
blocks: nextPayload.blocks,
518-
});
500+
try {
501+
await updateMessageSlack({
502+
cfg,
503+
accountId: resolved.accountId,
504+
teamId: entry.teamId,
505+
channelId: entry.channelId,
506+
messageTs: entry.messageTs,
507+
text: nextPayload.text,
508+
blocks: nextPayload.blocks,
509+
});
510+
} catch (err) {
511+
logError(`slack approvals: failed to update message: ${String(err)}`);
512+
}
519513
},
520514
},
521515
observe: {

‎extensions/slack/src/approval-native-gates.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,7 @@ function isSlackApprovalTransportEnabled(params: {
7474
cfg: OpenClawConfig;
7575
accountId?: string | null;
7676
}): boolean {
77-
const account = resolveSlackAccount(params);
78-
return account.config.enterpriseOrgInstall !== true && isSlackPluginAccountConfigured(account);
77+
return isSlackPluginAccountConfigured(resolveSlackAccount(params));
7978
}
8079

8180
function resolveSlackNativeApprovalConfig(params: {

0 commit comments

Comments
 (0)