|
| 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