Skip to content

Commit f19aa03

Browse files
committed
fix(slack): allow group DMs to be opened from the message tool
Backport-Of: #132928
1 parent 668fd3e commit f19aa03

16 files changed

Lines changed: 425 additions & 2 deletions

‎docs/channels/slack.md‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1287,7 +1287,7 @@ Available action groups in current Slack tooling:
12871287
| memberInfo | enabled |
12881288
| emojiList | enabled |
12891289

1290-
Current Slack message actions include `send`, `upload-file`, `download-file`, `read`, `edit`, `delete`, `pin`, `unpin`, `list-pins`, `member-info`, and `emoji-list`. `download-file` accepts Slack file IDs shown in inbound file placeholders and returns image previews for images or local file metadata for other file types.
1290+
Current Slack message actions include `send`, `conversation-open`, `upload-file`, `download-file`, `read`, `edit`, `delete`, `pin`, `unpin`, `list-pins`, `member-info`, and `emoji-list`. `download-file` accepts Slack file IDs shown in inbound file placeholders and returns image previews for images or local file metadata for other file types.
12911291

12921292
## Access control and routing
12931293

@@ -1424,7 +1424,19 @@ Slack group DMs, also called multi-person direct messages or MPDMs, are not chan
14241424
To bring the app into a group DM, use one of these Slack-supported paths:
14251425

14261426
1. Convert the group DM to a private channel, then ask a current member to invite the app with `/invite @YourBot`. An API-based invite must call `conversations.invite` with a token whose actor is already a member and allowed to invite the app.
1427-
2. Have the app open a new MPDM with `conversations.open` using a bot token with `mpim:write`, passing the human recipients in `users`. Slack includes the calling bot user automatically.
1427+
2. Ask the app to use the message tool's `conversation-open` action with the human recipients in `userIds`. It calls `conversations.open` using the configured write identity; bot accounts need `mpim:write`. Slack includes the calling account automatically.
1428+
1429+
```json
1430+
{
1431+
"action": "conversation-open",
1432+
"channel": "slack",
1433+
"userIds": ["U12345678", "U23456789"]
1434+
}
1435+
```
1436+
1437+
Provide 1-8 distinct member IDs, excluding the calling account. One recipient opens a 1:1 DM (requiring `im:write`); multiple recipients open or reuse a group DM with that exact audience. The result contains `channelId` and a routable `target`. Send the message with `action: "send"` and that exact `target`.
1438+
1439+
Use `accountId` to select a configured Slack account and `teamId` for an explicit workspace. The current workspace is inherited only for the same originating account; detached Enterprise operations require `teamId`. Opening is controlled by the `messages` action gate. It does not change DM/read policy, grant history access, or send a message by itself.
14281440

14291441
## Threading, sessions, and reply tags
14301442

‎extensions/slack/src/action-runtime.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ type ConversationReadInvocationOrigin = NonNullable<
3636
>;
3737

3838
const messagingActions = new Set([
39+
"openConversation",
3940
"sendMessage",
4041
"uploadFile",
4142
"editMessage",
@@ -73,6 +74,7 @@ export const slackActionRuntime = {
7374
listSlackEmojis: createLazySlackAction("listSlackEmojis"),
7475
listSlackPins: createLazySlackAction("listSlackPins"),
7576
listSlackReactions: createLazySlackAction("listSlackReactions"),
77+
openSlackConversation: createLazySlackAction("openSlackConversation"),
7678
parseSlackBlocksInput,
7779
pinSlackMessage: createLazySlackAction("pinSlackMessage"),
7880
reactSlackMessage: createLazySlackAction("reactSlackMessage"),
@@ -661,6 +663,17 @@ export async function handleSlackAction(
661663
throw new Error("Slack messages are disabled.");
662664
}
663665
switch (action) {
666+
case "openConversation": {
667+
const teamId =
668+
readStringParam(params, "teamId") ??
669+
resolveTrustedCurrentSlackTeamId({ account, context });
670+
assertSlackDetachedTargetAllowed(account.accountId, teamId);
671+
const result = await slackActionRuntime.openSlackConversation(
672+
params.userIds,
673+
buildActionOpts("write", teamId),
674+
);
675+
return jsonResult({ ok: true, ...result });
676+
}
664677
case "sendMessage": {
665678
const to = readStringParam(params, "to", { required: true });
666679
const target = resolveSlackActionTarget(account, to, context);

‎extensions/slack/src/actions.runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export {
77
listSlackEmojis,
88
listSlackPins,
99
listSlackReactions,
10+
openSlackConversation,
1011
pinSlackMessage,
1112
reactSlackMessage,
1213
readSlackMessages,

‎extensions/slack/src/actions.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ import type { SlackAuthoredTextPlacement } from "./authored-text.js";
1010
import { buildSlackBlocksFallbackText } from "./blocks-fallback.js";
1111
import { validateSlackBlocksArray } from "./blocks-input.js";
1212
import { createSlackLookupClient, getSlackWriteClient } from "./client.js";
13+
import {
14+
openSlackConversationWithClient,
15+
parseSlackConversationOpenInput,
16+
} from "./conversation-open.js";
1317
import { assertSlackDetachedTargetAllowed } from "./detached-target-admission.js";
1418
import { buildSlackEditTextPayload } from "./edit-text.js";
1519
import { SLACK_EDIT_TEXT_MAX_BYTES } from "./limits.js";
@@ -464,6 +468,12 @@ export async function deleteSlackMessage(
464468
});
465469
}
466470

471+
export async function openSlackConversation(userIds: unknown, opts: SlackActionClientOpts = {}) {
472+
const input = parseSlackConversationOpenInput(userIds, opts.teamId);
473+
const client = await getClient({ ...opts, teamId: input.teamId }, "write");
474+
return await openSlackConversationWithClient(client, input);
475+
}
476+
467477
export async function resolveSlackConversationName(
468478
channelId: string,
469479
opts: SlackActionClientOpts = {},

‎extensions/slack/src/channel-actions-setup-status.contract.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { slackSetupPlugin } from "../setup-plugin-api.js";
1111

1212
const slackDefaultActions = [
1313
"send",
14+
"conversation-open",
1415
"react",
1516
"reactions",
1617
"read",

‎extensions/slack/src/channel.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,7 @@ describe("slackPlugin actions", () => {
347347
"send",
348348
"react",
349349
"reactions",
350+
"conversation-open",
350351
"read",
351352
"edit",
352353
"delete",
Lines changed: 281 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,281 @@
1+
import { WebClient, type WebClientOptions } from "@slack/web-api";
2+
import type {
3+
ChannelMessageActionContext,
4+
ChannelMessageActionName,
5+
} from "openclaw/plugin-sdk/channel-contract";
6+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
7+
import { afterEach, describe, expect, it, vi } from "vitest";
8+
import { createSlackActions } from "./channel-actions.js";
9+
import * as slackClient from "./client.js";
10+
import { registerSlackInstallationState } from "./installation-identity-state.js";
11+
12+
type SlackRequest = {
13+
method: string;
14+
args: Record<string, string>;
15+
authorization: string | null;
16+
};
17+
18+
function createConversationFixture(
19+
conversationId = "C01234567",
20+
openResponse?: Record<string, unknown>,
21+
) {
22+
const requests: SlackRequest[] = [];
23+
const cfg: OpenClawConfig = {
24+
channels: {
25+
slack: {
26+
botToken: "xoxb-test",
27+
userToken: "xoxp-readonly",
28+
userTokenReadOnly: true,
29+
},
30+
},
31+
};
32+
const fetch: NonNullable<WebClientOptions["fetch"]> = async (input, init) => {
33+
const url = new URL(String(input));
34+
if (typeof init?.body !== "string") {
35+
throw new Error("Expected a form-encoded Slack request body");
36+
}
37+
const args = Object.fromEntries(new URLSearchParams(init.body));
38+
const method = url.pathname.split("/").at(-1) ?? "";
39+
requests.push({ method, args, authorization: new Headers(init?.headers).get("authorization") });
40+
const response =
41+
method === "conversations.open"
42+
? (openResponse ?? { ok: true, channel: { id: conversationId } })
43+
: method === "chat.postMessage"
44+
? { ok: true, channel: args.channel, ts: "171234.567", message: { text: args.text } }
45+
: undefined;
46+
if (!response) {
47+
throw new Error(`Unexpected Slack request: ${method}`);
48+
}
49+
return new Response(JSON.stringify(response), {
50+
headers: { "content-type": "application/json" },
51+
});
52+
};
53+
vi.spyOn(slackClient, "getSlackWriteClient").mockImplementation(
54+
(token, options) => new WebClient(token, { ...options, fetch, retryConfig: { retries: 0 } }),
55+
);
56+
vi.spyOn(slackClient, "createSlackLookupClient").mockImplementation(() => {
57+
throw new Error("Opening and sending must not use the read client");
58+
});
59+
const adapter = createSlackActions("slack");
60+
const invoke = (
61+
action: ChannelMessageActionName,
62+
params: Record<string, unknown>,
63+
overrides: Partial<ChannelMessageActionContext> = {},
64+
) =>
65+
adapter.handleAction!({
66+
channel: "slack",
67+
action,
68+
cfg,
69+
params,
70+
accountId: "default",
71+
requesterAccountId: "default",
72+
toolContext: {
73+
currentChannelProvider: "slack",
74+
currentChannelId: "team:T11111111:channel:C09999999",
75+
currentThreadTs: "170000.111",
76+
replyToMode: "all",
77+
},
78+
...overrides,
79+
});
80+
return { adapter, cfg, invoke, requests };
81+
}
82+
83+
afterEach(() => {
84+
vi.restoreAllMocks();
85+
vi.unstubAllEnvs();
86+
});
87+
88+
describe("Slack conversation-open", () => {
89+
it("exposes the recipient contract to the message tool", () => {
90+
const { adapter, cfg } = createConversationFixture();
91+
const discovery = adapter.describeMessageTool({ cfg, accountId: "default" });
92+
expect(discovery?.actions).toContain("conversation-open");
93+
const contributions = discovery?.schema;
94+
const schema = (Array.isArray(contributions) ? contributions : [contributions]).find((entry) =>
95+
entry?.actions?.includes("conversation-open"),
96+
);
97+
expect(schema?.properties.userIds).toMatchObject({ type: "array", minItems: 1, maxItems: 8 });
98+
});
99+
100+
it.each(["C01234567", "G01234567"])(
101+
"opens one group DM and sends to its returned %s target as the bot",
102+
async (channelId) => {
103+
const { invoke, requests } = createConversationFixture(channelId);
104+
const opened = await invoke("conversation-open", { userIds: ["U11111111", "U22222222"] });
105+
const target = `team:T11111111:channel:${channelId}`;
106+
expect(opened.details).toEqual({ ok: true, channelId, target });
107+
expect(requests).toEqual([
108+
{
109+
method: "conversations.open",
110+
args: { users: "U11111111,U22222222", team_id: "T11111111" },
111+
authorization: "Bearer xoxb-test",
112+
},
113+
]);
114+
115+
await invoke("send", { to: target, message: "Hello together" });
116+
expect(requests.map((request) => request.method)).toEqual([
117+
"conversations.open",
118+
"chat.postMessage",
119+
]);
120+
expect(requests[1]).toMatchObject({
121+
authorization: "Bearer xoxb-test",
122+
args: { channel: channelId, text: "Hello together", team_id: "T11111111" },
123+
});
124+
expect(requests[1]?.args).not.toHaveProperty("thread_ts");
125+
},
126+
);
127+
128+
it("opens a one-to-one DM without requiring a current conversation", async () => {
129+
const { invoke, requests } = createConversationFixture("D01234567");
130+
const installation = registerSlackInstallationState("default", "workspace");
131+
try {
132+
const opened = await invoke(
133+
"conversation-open",
134+
{ userIds: ["U11111111"] },
135+
{ toolContext: undefined },
136+
);
137+
expect(opened.details).toEqual({
138+
ok: true,
139+
channelId: "D01234567",
140+
target: "channel:D01234567",
141+
});
142+
expect(requests).toHaveLength(1);
143+
expect(requests[0]?.args).toEqual({ users: "U11111111" });
144+
} finally {
145+
installation.release();
146+
}
147+
});
148+
149+
it("accepts eight recipients, including legacy W-prefixed user IDs", async () => {
150+
const { invoke, requests } = createConversationFixture();
151+
const userIds = ["W11111111", ...Array.from({ length: 7 }, (_, index) => `U2222222${index}`)];
152+
await invoke("conversation-open", { userIds });
153+
expect(requests[0]?.args.users).toBe(userIds.join(","));
154+
});
155+
156+
it.each([
157+
{ name: "missing recipients", userIds: undefined },
158+
{ name: "no recipients", userIds: [] },
159+
{ name: "a comma-separated string", userIds: "U11111111,U22222222" },
160+
{ name: "a channel ID", userIds: ["C11111111"] },
161+
{ name: "a mention", userIds: ["<@U11111111>"] },
162+
{ name: "duplicate recipients", userIds: ["U11111111", "U11111111"] },
163+
{ name: "duplicates after trimming", userIds: ["U11111111", " U11111111 "] },
164+
{
165+
name: "too many recipients",
166+
userIds: Array.from({ length: 9 }, (_, index) => `U1111111${index}`),
167+
},
168+
])("rejects $name before calling Slack", async ({ userIds }) => {
169+
const { invoke, requests } = createConversationFixture();
170+
await expect(invoke("conversation-open", { userIds })).rejects.toThrow();
171+
expect(requests).toEqual([]);
172+
});
173+
174+
it("honors the messages action gate in discovery and execution", async () => {
175+
const { adapter, cfg, invoke, requests } = createConversationFixture();
176+
cfg.channels!.slack!.actions = { messages: false };
177+
expect(adapter.describeMessageTool({ cfg, accountId: "default" })?.actions).not.toContain(
178+
"conversation-open",
179+
);
180+
await expect(
181+
invoke("conversation-open", { userIds: ["U11111111", "U22222222"] }),
182+
).rejects.toThrow("Slack messages are disabled");
183+
expect(requests).toEqual([]);
184+
});
185+
186+
it("does not grant group-DM read access or change inbound policy", async () => {
187+
const { cfg, invoke, requests } = createConversationFixture();
188+
cfg.channels!.slack!.dm = { groupEnabled: false, groupChannels: ["G99999999"] };
189+
const policy = structuredClone(cfg);
190+
await invoke("conversation-open", { userIds: ["U11111111", "U22222222"] });
191+
expect(requests.map((request) => request.method)).toEqual(["conversations.open"]);
192+
expect(requests[0]?.args).not.toHaveProperty("return_im");
193+
expect(cfg).toEqual(policy);
194+
});
195+
196+
it("does not fall back to a user read token when the bot token is missing", async () => {
197+
const { adapter, cfg, invoke, requests } = createConversationFixture();
198+
vi.stubEnv("SLACK_BOT_TOKEN", undefined);
199+
cfg.channels!.slack!.botToken = undefined;
200+
expect(adapter.describeMessageTool({ cfg, accountId: "default" })?.actions).not.toContain(
201+
"conversation-open",
202+
);
203+
await expect(invoke("conversation-open", { userIds: ["U11111111"] })).rejects.toThrow(
204+
"botToken is required",
205+
);
206+
expect(requests).toEqual([]);
207+
});
208+
209+
it("uses the user token only for an explicitly configured user identity", async () => {
210+
const { cfg, invoke, requests } = createConversationFixture();
211+
cfg.channels!.slack!.postAs = "user";
212+
await invoke("conversation-open", { userIds: ["U11111111", "U22222222"] });
213+
expect(requests[0]?.authorization).toBe("Bearer xoxp-readonly");
214+
});
215+
216+
it.each([
217+
{ name: "detached", overrides: { toolContext: undefined } },
218+
{ name: "cross-account", overrides: { requesterAccountId: "another-account" } },
219+
{
220+
name: "conflicting-workspace",
221+
overrides: {
222+
toolContext: {
223+
currentChannelProvider: "slack",
224+
currentChannelId: "team:T11111111:channel:C09999999",
225+
currentMessagingTarget: "team:T22222222:channel:C09999999",
226+
},
227+
},
228+
},
229+
])("requires an explicit workspace for $name Enterprise calls", async ({ overrides }) => {
230+
const { invoke, requests } = createConversationFixture();
231+
const installation = registerSlackInstallationState("default", "enterprise");
232+
try {
233+
await expect(
234+
invoke("conversation-open", { userIds: ["U11111111", "U22222222"] }, overrides),
235+
).rejects.toThrow("unsupported_enterprise_slack_delivery");
236+
expect(requests).toEqual([]);
237+
} finally {
238+
installation.release();
239+
}
240+
});
241+
242+
it("preserves an explicit workspace on detached Enterprise calls", async () => {
243+
const { invoke, requests } = createConversationFixture();
244+
const installation = registerSlackInstallationState("default", "enterprise");
245+
try {
246+
const opened = await invoke(
247+
"conversation-open",
248+
{ userIds: ["U11111111", "U22222222"], teamId: "T22222222" },
249+
{ toolContext: undefined },
250+
);
251+
expect(opened.details).toEqual({
252+
ok: true,
253+
channelId: "C01234567",
254+
target: "team:T22222222:channel:C01234567",
255+
});
256+
expect(requests[0]?.args.team_id).toBe("T22222222");
257+
} finally {
258+
installation.release();
259+
}
260+
});
261+
262+
it("rejects a malformed explicit workspace before calling Slack", async () => {
263+
const { invoke, requests } = createConversationFixture();
264+
await expect(
265+
invoke("conversation-open", { userIds: ["U11111111"], teamId: "U11111111" }),
266+
).rejects.toThrow();
267+
expect(requests).toEqual([]);
268+
});
269+
270+
it.each([
271+
{ response: { ok: false, error: "missing_scope" }, error: "missing_scope" },
272+
{ response: { ok: true, channel: {} }, error: "valid conversation ID" },
273+
{ response: { ok: true, channel: { id: "U11111111" } }, error: "valid conversation ID" },
274+
])("reports Slack failures without sending a message: $error", async ({ response, error }) => {
275+
const { invoke, requests } = createConversationFixture("C01234567", response);
276+
await expect(
277+
invoke("conversation-open", { userIds: ["U11111111", "U22222222"] }),
278+
).rejects.toThrow(error);
279+
expect(requests.map((request) => request.method)).toEqual(["conversations.open"]);
280+
});
281+
});

0 commit comments

Comments
 (0)