@desplega.ai/slack-mock 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # slack-mock
2
+
3
+ A mock Slack server for end-to-end testing Slack bots. It speaks the Slack Web
4
+ API and Socket Mode, so a real `@slack/bolt` app connects to it unchanged
5
+ (only `clientOptions.slackApiUrl` differs). Messages, threads, reactions,
6
+ files, modals and assistant threads are stored, journaled as JSONL, and
7
+ rendered as Slack-looking HTML for screenshots.
8
+
9
+ Built for the [agent-swarm](../agent-swarm) Slack integration. Bun + TypeScript,
10
+ no runtime dependencies.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ bun add -d @desplega.ai/slack-mock # from npm (once published)
16
+ bun add -d github:desplega-ai/slack-mock # or straight from the repo (Bun runs the TypeScript sources)
17
+ ```
18
+
19
+ ## Quick start (from a checkout)
20
+
21
+ ```bash
22
+ bun install
23
+ bun run start # slack-mock serve --port 4040
24
+ bun run demo # same, seeded with threads, blocks, files, an ephemeral and a DM
25
+ ```
26
+
27
+ Point your bot at it:
28
+
29
+ ```bash
30
+ SLACK_BOT_TOKEN=xoxb-mock-bot-token \
31
+ SLACK_APP_TOKEN=xapp-mock-app-token \
32
+ SLACK_API_URL=http://127.0.0.1:4040/api/ \
33
+ bun src/http.ts # agent-swarm reads SLACK_API_URL into clientOptions.slackApiUrl
34
+ ```
35
+
36
+ Talk to the bot as a human and watch the thread:
37
+
38
+ ```bash
39
+ curl -X POST http://127.0.0.1:4040/mock/messages -H 'content-type: application/json' \
40
+ -d '{"channel":"general","user":"alice","text":"<@U0BOT00000> hello"}'
41
+ open http://127.0.0.1:4040/c/general # live view (add ?refresh=2)
42
+ bun src/cli.ts screenshot http://127.0.0.1:4040/c/general --out general.png
43
+ ```
44
+
45
+ ## In tests
46
+
47
+ ```ts
48
+ import { App } from "@slack/bolt";
49
+ import { SlackMock } from "@desplega.ai/slack-mock";
50
+
51
+ const slack = await SlackMock.start({ port: 0, manifest: "slack-manifest.json" });
52
+ const app = new App({
53
+ token: slack.env.SLACK_BOT_TOKEN,
54
+ appToken: slack.env.SLACK_APP_TOKEN,
55
+ socketMode: true,
56
+ clientOptions: { slackApiUrl: slack.env.SLACK_API_URL },
57
+ });
58
+ await app.start();
59
+ await slack.waitForConnection();
60
+
61
+ const ask = await slack.postMessage({ channel: "general", user: "alice", text: `<@${slack.bot.userId}> hi` });
62
+ const reply = await slack.waitForMessage({ channel: "general", thread_ts: ask.ts, from: "bot" });
63
+ ```
64
+
65
+ What tests can do:
66
+
67
+ | humans do | `postMessage` (text, thread, files), `editMessage`, `deleteMessage`, `addReaction`, `slashCommand`, `clickButton`, `submitView`, `startAssistantThread`, `changeAssistantContext`, `addUser`, `addChannel`, `openDm`, `invite` |
68
+ |---|---|
69
+ | observe | `messages`, `thread`, `ephemeralMessages`, `findMessages`, `waitForMessage`, `apiCalls`, `waitForApiCall`, `deliveries` (every envelope and its ack), `assistantThread` |
70
+ | break things | `injectFault({ method, error, httpStatus, retryAfterSec, extra })`, `disconnectSockets("refresh_requested")`, options `ackTimeoutMs`, `maxRetries`, `triggerIdTtlMs`, `echoBotMessages`, `subscribedEvents` |
71
+
72
+ The same operations exist over HTTP under `/mock/*` for use from another
73
+ process (see `docs/design.md`).
74
+
75
+ ## Slack behaviour that is modelled
76
+
77
+ - Socket Mode: `apps.connections.open`, `hello`, envelopes for `events_api`,
78
+ `slash_commands` and `interactive`, acks with response payloads,
79
+ redelivery with `retry_attempt` when an envelope is not acked, server
80
+ pings, `disconnect` messages, reconnects.
81
+ - Events: `message` (channels, groups, im), `app_mention`, `message_changed`,
82
+ `message_deleted`, `file_share`, `reaction_added/removed`,
83
+ `member_joined_channel`, `assistant_thread_started`,
84
+ `assistant_thread_context_changed`. The bot's own messages are echoed back
85
+ like Slack does (Bolt's `ignoreSelf` drops them).
86
+ - Web API: auth, chat (post, update, delete, ephemeral, permalink, streams),
87
+ conversations (list, info, create, join, invite, archive, history, replies,
88
+ members, open), users (info, list, lookupByEmail), reactions, files
89
+ (info, upload v2 flow, download with bearer token), views (open, update,
90
+ push), assistant.threads (status, title, prompts), pins, bots, team.
91
+ Errors come back as `{ ok: false, error }` with the real codes
92
+ (`not_in_channel`, `already_reacted`, `message_not_found`, `name_taken`,
93
+ `expired_trigger_id`, `message_not_in_streaming_state`, ...).
94
+ - Slash command and interactive `response_url`s are served by the mock
95
+ (`ephemeral` / `in_channel`, `replace_original`, `delete_original`).
96
+
97
+ ## Commands
98
+
99
+ ```bash
100
+ bun test # unit and integration tests (real Bolt client)
101
+ bun run test:e2e # boots ../agent-swarm against the mock (AGENT_SWARM_REPO to override; needs agent-swarm PR #1310)
102
+ bun run typecheck
103
+ bun run lint
104
+ bun run build # dist/ (JS for Bun + .d.ts). CI publishes to npm when the version in package.json changes on main
105
+ ```
106
+
107
+ ## Docs
108
+
109
+ - `skills/slack-mock/SKILL.md`: how to use the package from another repo (agents and humans).
110
+ - `docs/design.md`: architecture, decisions, status.
111
+ - `docs/research/`: the research behind it (agent-swarm's inbound/outbound
112
+ Slack surface, Bolt and socket-mode internals, payload shapes, protocol
113
+ docs and prior art, e2e conventions, Block Kit surface).
package/dist/body.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export type Args = Record<string, unknown>;
2
+ export declare function parseArgs(req: Request): Promise<Args>;
3
+ export declare function bearerToken(req: Request, args: Args): string | undefined;
4
+ export declare function str(args: Args, key: string): string | undefined;
5
+ export declare function num(args: Args, key: string, fallback: number): number;
6
+ export declare function bool(args: Args, key: string): boolean | undefined;
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ import {
4
+ SlackMock
5
+ } from "./index-thgwpw70.js";
6
+ import {
7
+ screenshot
8
+ } from "./index-v7mbr1cx.js";
9
+
10
+ // src/cli.ts
11
+ import { parseArgs } from "util";
12
+ var USAGE = `slack-mock: a mock Slack server (Web API + Socket Mode) for testing bots
13
+
14
+ Usage:
15
+ slack-mock serve [--port 4040] [--host 127.0.0.1] [--data ./data/slack.jsonl] [--manifest app.json] [--no-seed] [--quiet] [--panel 50]
16
+ slack-mock screenshot <url> --out shot.png [--width 800] [--height 1000]
17
+
18
+ serve prints the env vars to give your bot (SLACK_BOT_TOKEN, SLACK_APP_TOKEN, SLACK_API_URL)
19
+ and the URLs of the HTML views. Inject messages with the admin API, e.g.
20
+ curl -X POST http://127.0.0.1:4040/mock/messages -H 'content-type: application/json' \\
21
+ -d '{"channel":"general","user":"alice","text":"<@U0BOT00000> hello"}'
22
+ `;
23
+ async function main(argv) {
24
+ const [command, ...rest] = argv;
25
+ if (command === "serve") {
26
+ const { values } = parseArgs({
27
+ args: rest,
28
+ options: {
29
+ port: { type: "string", default: "4040" },
30
+ host: { type: "string", default: "127.0.0.1" },
31
+ data: { type: "string" },
32
+ manifest: { type: "string" },
33
+ "no-seed": { type: "boolean", default: false },
34
+ quiet: { type: "boolean", default: false },
35
+ panel: { type: "string" }
36
+ }
37
+ });
38
+ const mock = await SlackMock.start({
39
+ panelWidth: values.panel,
40
+ port: Number(values.port),
41
+ host: values.host,
42
+ dataFile: values.data,
43
+ manifest: values.manifest,
44
+ seed: !values["no-seed"],
45
+ log: !values.quiet
46
+ });
47
+ console.log(`slack-mock listening on ${mock.baseUrl}`);
48
+ console.log("");
49
+ console.log("Bot environment:");
50
+ for (const [k, v] of Object.entries(mock.env))
51
+ console.log(` ${k}=${v}`);
52
+ console.log("");
53
+ console.log(`Workspace: ${mock.baseUrl}/ (bot user ${mock.bot.userId}, team ${mock.team.id})`);
54
+ for (const c of mock.store.channels.values())
55
+ console.log(` #${c.name}: ${mock.baseUrl}/c/${c.id}`);
56
+ console.log("");
57
+ console.log(`Admin API: POST ${mock.baseUrl}/mock/messages {channel,user,text,thread_ts}`);
58
+ const stop = async () => {
59
+ await mock.stop();
60
+ process.exit(0);
61
+ };
62
+ process.on("SIGINT", stop);
63
+ process.on("SIGTERM", stop);
64
+ return;
65
+ }
66
+ if (command === "screenshot") {
67
+ const { values, positionals } = parseArgs({
68
+ args: rest,
69
+ allowPositionals: true,
70
+ options: {
71
+ out: { type: "string", default: "slack-mock.png" },
72
+ width: { type: "string", default: "800" },
73
+ height: { type: "string", default: "1000" }
74
+ }
75
+ });
76
+ const url = positionals[0];
77
+ if (!url)
78
+ throw new Error("screenshot needs a URL");
79
+ const out = await screenshot(url, {
80
+ out: values.out,
81
+ width: Number(values.width),
82
+ height: Number(values.height)
83
+ });
84
+ console.log(out);
85
+ return;
86
+ }
87
+ console.log(USAGE);
88
+ if (command && command !== "help" && command !== "--help")
89
+ process.exit(1);
90
+ }
91
+ main(process.argv.slice(2)).catch((e) => {
92
+ console.error(e instanceof Error ? e.message : e);
93
+ process.exit(1);
94
+ });
@@ -0,0 +1,36 @@
1
+ import { type Store, wireFile } from "./store.ts";
2
+ import type { SlackChannel, SlackMessage, SlackUser, SlackView } from "./types.ts";
3
+ export declare const VERIFICATION_TOKEN = "mock-verification-token";
4
+ export declare function eventCallback(store: Store, event: Record<string, unknown>): Record<string, unknown>;
5
+ /** The `message` event for a stored message (any subtype). */
6
+ export declare function messageEvent(store: Store, m: SlackMessage, channel: SlackChannel): Record<string, unknown>;
7
+ export declare function appMentionEvent(store: Store, m: SlackMessage): Record<string, unknown>;
8
+ export declare function messageChangedEvent(store: Store, m: SlackMessage, previous: SlackMessage): Record<string, unknown>;
9
+ export declare function messageDeletedEvent(store: Store, m: SlackMessage): Record<string, unknown>;
10
+ export declare function reactionEvent(kind: "reaction_added" | "reaction_removed", m: SlackMessage, name: string, user: string): Record<string, unknown>;
11
+ export declare function memberJoinedEvent(store: Store, channel: SlackChannel, user: string, inviter?: string): Record<string, unknown>;
12
+ export declare function assistantThreadStartedEvent(store: Store, dm: SlackChannel, user: string, threadTs: string, context?: Record<string, unknown>): Record<string, unknown>;
13
+ export declare function assistantThreadContextChangedEvent(store: Store, dm: SlackChannel, user: string, threadTs: string, context: Record<string, unknown>): Record<string, unknown>;
14
+ export declare function slashCommandPayload(store: Store, input: {
15
+ command: string;
16
+ text: string;
17
+ user: SlackUser;
18
+ channel: SlackChannel;
19
+ responseUrl: string;
20
+ triggerId: string;
21
+ }): Record<string, unknown>;
22
+ export declare function blockActionsPayload(store: Store, input: {
23
+ user: SlackUser;
24
+ channel: SlackChannel;
25
+ message: SlackMessage;
26
+ actions: Array<Record<string, unknown>>;
27
+ responseUrl: string;
28
+ triggerId: string;
29
+ }): Record<string, unknown>;
30
+ export declare function viewSubmissionPayload(store: Store, input: {
31
+ user: SlackUser;
32
+ view: SlackView;
33
+ values: Record<string, Record<string, unknown>>;
34
+ triggerId: string;
35
+ }): Record<string, unknown>;
36
+ export { wireFile };
package/dist/ids.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export declare function slackId(prefix: string, length?: number): string;
2
+ /**
3
+ * Slack message timestamps look like "1700000000.123456": unix seconds plus a
4
+ * six-digit sequence. They must be unique per channel and strictly increasing,
5
+ * so we derive them from a monotonic microsecond clock.
6
+ */
7
+ export declare function nextTs(): string;
8
+ export declare function nowUnix(): number;