# channelstack docs > channelstack is a test harness for apps and AI agents that live in Slack, GitHub, Linear, Notion, email (Resend and Gmail) and Discord. One server fakes those platforms in memory, and OpenAI's API for the agent's model: tests act as people (`ana.say("@my-agent hi", { channel })`) and check what a person would see (`expect(thread).toHaveReplyFrom("my-agent")`). The same tests run against the real platforms in live mode. SDKs for TypeScript (Vitest), Python (pytest) and Rust. # Overview Source: https://channelstack.dev/docs channelstack tests the apps and agents you build for Slack, GitHub, Linear, Notion, Resend, Gmail and Discord: a Slack bot, a GitHub App, a Linear or Notion integration, an agent people email, a Discord bot, a notification bot, or an AI agent. It runs those platforms as fakes on your machine, and OpenAI's API for your agent's model, so a test can play the people in a conversation and check what they would see. ```ts title="TypeScript" import { expect, test } from "vitest"; test("a mention gets exactly one reply, in the thread", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); const channel = await slack.createChannel({ participants: [ana, slack.app] }); const msg = await ana.say("@my-agent summarize yesterday's incidents", { channel }); await expect(msg.thread).toHaveReplyFrom("my-agent", { text: /incident/i }); await expect(msg.thread).toHaveRepliesFrom(slack.app, { count: 1 }); await expect(channel).not.toHaveChannelMessageFrom("my-agent"); }); ``` ```python title="Python" import re from channelstack import SlackFixture from pytest_channelstack import expect async def test_a_mention_gets_exactly_one_reply_in_the_thread(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") channel = await slack.create_channel(participants=[ana, slack.app]) msg = await ana.say("@my-agent summarize yesterday's incidents", channel=channel) await expect(msg.thread).to_have_reply_from("my-agent", text=re.compile("incident", re.I)) await expect(msg.thread).to_have_replies_from(slack.app, count=1) await expect(channel).not_to_have_channel_message_from("my-agent") ``` ```rust title="Rust" let ana = slack.create_user().name("Ana").await?; let channel = slack .create_channel() .participants(vec![&ana as &dyn Handle, &slack.app()]) .await?; let msg = ana .say("@my-agent summarize yesterday's incidents") .channel(&channel) .await?; expect(&msg.thread()) .to_have_reply_from("my-agent") .text(Regex::new("(?i)incident")?) .await?; expect(&msg.thread()) .to_have_replies_from(&slack.app(), 1) .await?; expect(&channel) .not_to_have_channel_message_from("my-agent") .await?; ``` The test never touches your app. Ana's message goes into a fake Slack workspace, which delivers the event to your app the way Slack would. Your app answers through the Slack SDK it already uses, pointed at the fake. The matchers then read the thread. 1. The test acts as Ana: she mentions the app in a channel. 2. The fake Slack delivers the event to your app, signed, the way Slack does. 3. Your app answers through the Slack API it already uses, which now points at the fake. 4. The matcher reads the thread as Ana would see it, and passes. ## What you get - **Fakes of seven platforms** on localhost: Slack, GitHub, Linear, Notion, Resend, Google (Gmail) and Discord, with their real APIs, webhooks, signatures, ids and error codes. Your app runs unchanged; one environment variable per platform points it at the fake. - **A fake model for AI agents.** OpenAI's API at `openai.localhost`, scripted per test: text, streams, tool calls, errors and a slow first token, images, audio, files and OpenAI's built-in tools. Anything that takes an OpenAI base URL works, from the `openai` SDKs and the AI SDK to OpenRouter and Azure OpenAI. See [OpenAI](https://channelstack.dev/docs/platforms/openai). - **Tests that read like the conversation.** Every action belongs to the person who takes it (`ana.say(…)`, `ben.click("Approve", …)`, `mo.comment(…)`), and every check is about what a person would see. - **Checks that wait for your app.** Replies arrive when they arrive. Positive checks wait until they hold; negative and exact-count checks wait until the app has gone quiet. A test never sleeps. - **The failures that matter, on demand.** Slack's 3-second retry, redelivered webhooks, bad signatures, rate limits and dropped sockets, so you can test what happens on a bad day. - **The same test against the real platforms.** With sandbox credentials in the environment, a test acts on a real workspace and reads the result back. It runs on the fakes for every pull request and live at night. - **Vitest and pytest.** channelstack plugs into the test framework you already use, with fixtures and matchers. There are SDKs for TypeScript, Python and Rust, an attach CLI and an MCP server for coding agents. ## What it doesn't do - **It doesn't run your app.** You start the app as usual. `channelstack env` prints the variables it needs. - **It doesn't write your model's answers.** The fake OpenAI says what each test scripted, and never judges an answer. An agent that doesn't use it keeps its framework's fake model (the AI SDK's `MockLanguageModelV4`, LangChain's `FakeListChatModel`, …) or a real one. The matchers check how the agent behaved, not the exact words. - **It isn't a pixel copy of each product.** The UI shows the conversations people have with your app as the same transcript the matchers read, next to every delivery and API call behind them. ## Where to go next | If you want to | Read | | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Know why this exists, and how it differs from mocking the SDK | [Why channelstack](https://channelstack.dev/docs/why) | | Get a first test passing in ten minutes | [Getting started](https://channelstack.dev/docs/getting-started) | | Understand the pieces | [How it works](https://channelstack.dev/docs/guide/how-it-works) | | Connect your own app | [Connecting your app](https://channelstack.dev/docs/guide/connecting-your-agent) | | Script what your agent's model answers | [OpenAI](https://channelstack.dev/docs/platforms/openai) | | Look something up | [Slack API](https://channelstack.dev/docs/reference/api/slack), [Matchers](https://channelstack.dev/docs/reference/matchers), [CLI](https://channelstack.dev/docs/reference/cli) | # Why channelstack Source: https://channelstack.dev/docs/why A Slack bot, a GitHub App or Probot app, a Linear or Notion integration, a notification bot and an AI agent have one thing in common: they're mostly glue. Events come in, the app decides what to do, and calls go back out. The deciding is the part everyone tests. The glue is where it breaks. channelstack is for anyone who writes that glue: code that talks to these platforms' APIs and reacts to their events, and that should be tested without a real workspace. ## Where the glue breaks The bugs that reach users are rarely in the business logic, or in what a model said. They're about how the app behaved on the platform: - It answers twice, because Slack retried an event the app acknowledged a second too late. - It answers in the channel instead of the thread, or answers its own message and loops. - An agent keeps streaming after someone pressed Stop. - A double click on "Approve" deploys twice. - It runs the same task again when GitHub redelivers a webhook. - It fails on a channel it was never invited to, because it didn't handle `not_in_channel`. - It accepts a webhook with a forged signature. None of these show up in a unit test of your app's logic, and few show up in a manual test on a real workspace, because the real platform rarely misbehaves on cue. ## Why the usual approaches fall short **Mocking the SDK** (`vi.mock("@slack/web-api")`) tests that your code calls a function. It can't tell you that Slack would have refused the call, that the payload you built has the wrong shape, or what happens when an event arrives twice. The mock only knows what you told it, and it agrees with you. **A real sandbox workspace** is honest, but slow and hard to control. Tests share state, need cleanup, depend on the network (and, for an agent, a model), and can't make Slack retry or send a bad signature. You can't run it on every pull request. **Recording and replaying traffic** freezes one conversation. Change a prompt or a code path and the recording no longer matches. ## What channelstack does instead channelstack fakes the platform, not your code. Your app keeps its real SDKs and talks HTTP to fakes that behave like the real thing: the same endpoints, payloads, signatures, ids and error codes, refusing what the platform refuses. The fakes are checked against the platforms' own schemas, and the same tests run against the real platforms at night, so the fakes stay honest. Because the fake is the platform, a test can do what the platform does to your app: retry a delivery, redeliver a webhook, send a stale timestamp, rate-limit a call, drop a socket. And because the fake knows everything that happened, the checks can wait for your app instead of sleeping, and fail with what was there instead of a timeout. ## The design choices - **Act as people, read as people.** A test is a script of people (`ana.say(…)`, `ben.click(…)`) and checks about what they would see. Resources are only read and waited on. That keeps tests close to the bug reports they prevent. - **Every test builds its own world.** People, channels, repositories and pages are created in the test, not in a config file. Tests run in parallel against one server, each in its own session, and clean up after themselves. - **Your app's access is explicit.** A bot only hears channels it's in, a GitHub App only sees repositories it's installed on, a Notion integration only sees pages connected to it, as on the real platforms. Leaving the app out is how you test the uninvited case. - **The model on the wire, never in content.** If your app is an AI agent, channelstack fakes OpenAI's API too, and each test scripts what the model answers: a slow first token, a stream that breaks, a tool call. It never writes or grades the answer. The matchers check behaviour (one reply, in the thread, stopped in time), so they hold with the fake OpenAI, a framework's fake model or a real one. - **Fake by default, live with credentials.** The same test runs against the fakes on every pull request and against real sandboxes nightly. Live mode acts on the real platform and reads back; it never relays or forges events to your app. ## When it isn't the right tool channelstack is for apps and agents that talk to these platforms over their APIs. If you're testing the quality of a model's answers, use an eval tool; channelstack can feed it transcripts, but doesn't grade them. If your app lives in a platform channelstack doesn't fake yet (Teams, for one), it can't help there today. Ready to try it? [Getting started](https://channelstack.dev/docs/getting-started) takes about ten minutes. # Getting started Source: https://channelstack.dev/docs/getting-started In this tutorial you build a tiny Slack bot, run it against channelstack's fake Slack, and write a test that checks it answers once, in the thread. Then you break the bot and watch the test catch it. The same steps work for any app or agent built on Slack's SDKs. It takes about ten minutes. ```bash title="~/hello-agent" $ npm i @slack/bolt && npm i -D channelstack vitest $ CHANNELSTACK_SLACK_WEBHOOK_URL=http://localhost:3000/slack/events npx channelstack start --no-portless --port 4500 channelstack 0.0.0 · in-memory Control http://127.0.0.1:4500/_channelstack slack http://127.0.0.1:4500/slack $ npx channelstack env > .env.local $ node --env-file=.env.local agent.js ⚡️ Bolt app is running $ npx vitest run Test Files 1 passed (1) Tests 1 passed (1) ``` You need Node.js 22 or newer. Nothing else: no Slack workspace, no app, no tunnel. ## 1. Create the project ```bash mkdir hello-agent && cd hello-agent npm init -y npm pkg set type=module npm i @slack/bolt npm i -D channelstack vitest ``` `@slack/bolt` is Slack's own framework; the bot uses it exactly as it would against real Slack. `channelstack` brings the server, the CLI and the Vitest plugin. ## 2. Start channelstack Open a second terminal in the same folder and start the server. It stays in the foreground, so leave it running: ```bash CHANNELSTACK_SLACK_WEBHOOK_URL=http://localhost:3000/slack/events \ npx channelstack start --no-portless --port 4500 ``` ``` {"level":"info","message":"listening","address":"127.0.0.1:4500","control":"http://127.0.0.1:4500/_channelstack","portless":false} channelstack 0.0.0 · in-memory Control http://127.0.0.1:4500/_channelstack echo http://127.0.0.1:4500/echo slack http://127.0.0.1:4500/slack github http://127.0.0.1:4500/github linear http://127.0.0.1:4500/linear notion http://127.0.0.1:4500/notion resend http://127.0.0.1:4500/resend google http://127.0.0.1:4500/google discord http://127.0.0.1:4500/discord openai http://127.0.0.1:4500/openai UI http://127.0.0.1:4500/?login=… `channelstack env` prints tokens and URLs as .env lines ``` The fake Slack now runs at `http://127.0.0.1:4500/slack`, with a workspace and an app called `my-agent` already installed. (`echo` is a tiny chat platform channelstack uses to test itself; you can ignore it.) `CHANNELSTACK_SLACK_WEBHOOK_URL` tells it where your bot will listen for events: `/slack/events` on port 3000 is Bolt's default. > [!NOTE] > `--no-portless` serves everything on one port. Without it, channelstack uses [portless](https://github.com/vercel-labs/portless) to give each fake its own HTTPS name, such as `https://slack.localhost`. That's the default; see [Connecting your app](https://channelstack.dev/docs/guide/connecting-your-agent). ## 3. Point the bot at the fake Back in the first terminal, ask the server for the bot's settings: ```bash npx channelstack env > .env.local ``` `.env.local` now holds what a Slack app needs: a bot token, a signing secret and `SLACK_API_URL`, pointing at the fake. (It also has lines for the other platforms, which this tutorial doesn't use.) The tokens are random, made once for your machine, and stay the same across restarts. ## 4. Write the bot Create `agent.js`. It answers every mention in the thread of the message that mentioned it: ```js title="agent.js" import { App } from "@slack/bolt"; const app = new App({ token: process.env.SLACK_BOT_TOKEN, signingSecret: process.env.SLACK_SIGNING_SECRET, // Unset in production, so the agent talks to Slack itself. clientOptions: process.env.SLACK_API_URL ? { slackApiUrl: process.env.SLACK_API_URL } : {}, }); app.event("app_mention", async ({ event, say }) => { const question = event.text.replace(/<@[^>]+>\s*/, ""); await say({ text: `On it: ${question}`, thread_ts: event.ts }); }); await app.start(3000); console.log("⚡️ Bolt app is running"); ``` Nothing in it knows about channelstack. The only line that matters is `slackApiUrl`, an option Bolt already has. Start it in a third terminal: ```bash node --env-file=.env.local agent.js ``` ## 5. Write the test Add the Vitest plugin: ```ts title="vitest.config.ts" import channelstack from "channelstack/vitest"; import { defineConfig } from "vitest/config"; export default defineConfig({ plugins: [channelstack()], }); ``` And the test: ```ts title="TypeScript" import { expect, test } from "vitest"; test("a mention gets one reply, in the thread", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); const channel = await slack.createChannel({ participants: [ana, slack.app] }); const msg = await ana.say("@my-agent summarize the incidents", { channel }); await expect(msg.thread).toHaveReplyFrom("my-agent", { text: /summarize the incidents/ }); await expect(msg.thread).toHaveRepliesFrom(slack.app, { count: 1 }); await expect(channel).not.toHaveChannelMessageFrom("my-agent"); }); ``` ```python title="Python" import re from channelstack import SlackFixture from pytest_channelstack import expect async def test_a_mention_gets_one_reply_in_the_thread(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") channel = await slack.create_channel(participants=[ana, slack.app]) msg = await ana.say("@my-agent summarize the incidents", channel=channel) await expect(msg.thread).to_have_reply_from("my-agent", text=re.compile("summarize the incidents")) await expect(msg.thread).to_have_replies_from(slack.app, count=1) await expect(channel).not_to_have_channel_message_from("my-agent") ``` ```rust title="Rust" let ana = slack.create_user().name("Ana").await?; let channel = slack .create_channel() .participants(vec![&ana as &dyn Handle, &slack.app()]) .await?; let msg = ana .say("@my-agent summarize the incidents") .channel(&channel) .await?; expect(&msg.thread()) .to_have_reply_from("my-agent") .text(Regex::new("summarize the incidents")?) .await?; expect(&msg.thread()) .to_have_replies_from(&slack.app(), 1) .await?; expect(&channel) .not_to_have_channel_message_from("my-agent") .await?; ``` Read it as a story: Ana exists, she and the app are in a new channel, she mentions the bot, and then three things should be true of what she sees. The `slack` fixture comes from the plugin, and so do the matchers. Run it: ```bash npx vitest run ``` ``` Test Files 1 passed (1) Tests 1 passed (1) ``` Here's what happened. The plugin found the running server and opened a session for the test. Ana's message went into the fake workspace, which sent your bot a signed `app_mention` event. Your bot called `chat.postMessage` on the fake, which put the reply in the thread. The first matcher waited for that reply; the other two waited until the bot had gone quiet, then checked that there was exactly one reply and nothing in the channel itself. ## 6. Break it on purpose A test you have never seen fail isn't proven yet. In `agent.js`, drop `thread_ts`, so the bot answers in the channel instead of the thread: ```diff title="agent.js" - await say({ text: `On it: ${question}`, thread_ts: event.ts }); + await say({ text: `On it: ${question}` }); ``` Restart the bot and run the test again. After ten seconds of waiting for the reply, it fails, and says why: ``` FAIL agent.test.ts > a mention gets one reply, in the thread Error: Expected a reply from my-agent matching /summarize the incidents/. The thread has: (nothing) ``` The reply went to the channel, so the thread is empty. Put `thread_ts` back, restart the bot, and the test passes again. ## Look around While the server runs, you can talk to the bot by hand, as any person: ```bash npx channelstack slack say --as ben --in "#support" "@my-agent are you there?" npx channelstack show ``` ``` ben said it in #support (C043CPD6TPN:1795578175.436386) ben: @my-agent are you there? my-agent: On it: are you there? ``` The UI link the server printed opens the same conversation in a browser, next to every delivery and API call behind it. [The dev loop](https://channelstack.dev/docs/guide/dev-loop) has more. ## Next steps - [How it works](https://channelstack.dev/docs/guide/how-it-works): the server, sessions and the transcript, in one page. - [Connecting your app](https://channelstack.dev/docs/guide/connecting-your-agent): your own app or agent, on any of the seven platforms, and its model on the fake OpenAI, with portless and HTTPS. - [Writing tests](https://channelstack.dev/docs/guide/writing-tests): people, channels, shared fixtures and cleanup. - [Slack](https://channelstack.dev/docs/platforms/slack): everything a Slack test can do, from buttons and modals to Stop. # Chat SDK Source: https://channelstack.dev/docs/quickstarts/chat-sdk In this tutorial you write a Slack bot on the [Chat SDK](https://chat-sdk.dev) (`chat` with `@chat-adapter/slack`), run it against channelstack's fake Slack, and test that it answers a mention and the follow-ups in its thread. Then you break it once and read the failure. It follows the `chat-sdk-slack` reference agent that channelstack's CI runs. If you haven't used channelstack before, [Getting started](https://channelstack.dev/docs/getting-started) explains the server, `channelstack env` and the test in more detail. This page moves faster. ## 1. Create the project You need Node.js 24 or newer, which runs the TypeScript files below as they are. ```bash mkdir chat-agent && cd chat-agent npm init -y npm pkg set type=module npm i chat@4.45.0 @chat-adapter/slack@4.45.0 @chat-adapter/state-memory@4.45.0 npm i -D channelstack vitest ``` These are the versions channelstack's CI runs the reference agent with. ## 2. Start channelstack In a second terminal, start the server and tell it where the bot takes Slack's events: ```bash CHANNELSTACK_SLACK_WEBHOOK_URL=http://127.0.0.1:3000/slack/events \ npx channelstack start --no-portless --port 4500 ``` Back in the first terminal, write the bot's settings to a file: ```bash npx channelstack env > .env.local ``` The Chat SDK's Slack adapter reads three of those lines on its own: `SLACK_BOT_TOKEN`, `SLACK_SIGNING_SECRET` and `SLACK_API_URL`. The last one points it at the fake. In production you leave it unset and the adapter talks to Slack. ## 3. Write the bot The Chat SDK handles web-standard `Request` objects, so the bot needs a small HTTP server around it. This one is the helper the reference agents use: ```ts title="serve.ts" import { createServer } from "node:http"; /** One handler for one path, 404 for everything else. */ export function serve(port: number, path: string, handle: (request: Request) => Promise): void { createServer(async (incoming, outgoing) => { let body = ""; for await (const chunk of incoming) body += chunk; const request = new Request(`http://${incoming.headers.host}${incoming.url}`, { method: incoming.method ?? "GET", headers: incoming.headers as Record, ...(incoming.method === "POST" ? { body } : {}), }); const response = incoming.url === path ? await handle(request) : new Response("not found", { status: 404 }); outgoing.writeHead(response.status, Object.fromEntries(response.headers)); outgoing.end(Buffer.from(await response.arrayBuffer())); }).listen(port, "127.0.0.1"); } ``` The bot answers a mention in its thread, subscribes to that thread, and then answers what people write there without a new mention: ```ts title="agent.ts" import { createSlackAdapter } from "@chat-adapter/slack"; import { createMemoryState } from "@chat-adapter/state-memory"; import { Chat } from "chat"; import { serve } from "./serve.ts"; const bot = new Chat({ userName: "my-agent", adapters: { slack: createSlackAdapter() }, state: createMemoryState(), logger: "warn", }); /** The question without the mention: Slack sends `<@U…>`, the Chat SDK may resolve it to `@name`. */ const question = (text: string) => text.replace(/<@[A-Z0-9]+>|@[\w-]+/g, "").trim(); bot.onNewMention(async (thread, message) => { if (message.author.isBot === true) return; await thread.subscribe(); await thread.post(`On it: ${question(message.text)}`); }); bot.onSubscribedMessage(async (thread, message) => { await thread.post(`On it: ${question(message.text)}`); }); serve(3000, "/slack/events", (request) => bot.webhooks.slack(request)); ``` Nothing in it knows about channelstack. Start it in a third terminal: ```bash node --env-file=.env.local agent.ts ``` ## 4. Write the tests Add the Vitest plugin: ```ts title="vitest.config.ts" import channelstack from "channelstack/vitest"; import { defineConfig } from "vitest/config"; export default defineConfig({ plugins: [channelstack()], }); ``` And two tests, one for the mention and one for the follow-up: ```ts title="TypeScript" import { expect, test } from "vitest"; test("a mention gets one reply, in the thread", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); const channel = await slack.createChannel({ participants: [ana, slack.app] }); const msg = await ana.say("@my-agent summarize the incidents", { channel }); await expect(msg.thread).toHaveReplyFrom("my-agent", { text: /summarize the incidents/ }); await expect(msg.thread).toHaveRepliesFrom(slack.app, { count: 1 }); await expect(channel).not.toHaveChannelMessageFrom("my-agent"); }); test("follow-ups in the thread are answered without a new mention", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); const channel = await slack.createChannel({ participants: [ana, slack.app] }); const msg = await ana.say("@my-agent what's the status of the web deploy?", { channel }); await expect(msg.thread).toHaveReplyFrom("my-agent"); await ana.reply("and the API?", { thread: msg }); await expect(msg.thread).toHaveReplyFrom("my-agent", { text: /and the API/ }); }); ``` ```python title="Python" import re from channelstack import SlackFixture from pytest_channelstack import expect async def test_a_mention_gets_one_reply_in_the_thread(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") channel = await slack.create_channel(participants=[ana, slack.app]) msg = await ana.say("@my-agent summarize the incidents", channel=channel) await expect(msg.thread).to_have_reply_from("my-agent", text=re.compile("summarize the incidents")) await expect(msg.thread).to_have_replies_from(slack.app, count=1) await expect(channel).not_to_have_channel_message_from("my-agent") async def test_follow_ups_in_the_thread_are_answered_without_a_new_mention(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") channel = await slack.create_channel(participants=[ana, slack.app]) msg = await ana.say("@my-agent what's the status of the web deploy?", channel=channel) await expect(msg.thread).to_have_reply_from("my-agent") await ana.reply("and the API?", thread=msg) await expect(msg.thread).to_have_reply_from("my-agent", text=re.compile("and the API")) ``` ```rust title="Rust" #[tokio::test] #[ignore = "needs a running agent"] async fn a_mention_gets_one_reply_in_the_thread() -> Result<()> { let session = fixtures::session().await?; let slack = session.slack().await?; let ana = slack.create_user().name("Ana").await?; let channel = slack .create_channel() .participants(vec![&ana as &dyn Handle, &slack.app()]) .await?; let msg = ana .say("@my-agent summarize the incidents") .channel(&channel) .await?; expect(&msg.thread()) .to_have_reply_from("my-agent") .text(Regex::new("summarize the incidents")?) .await?; expect(&msg.thread()) .to_have_replies_from(&slack.app(), 1) .await?; expect(&channel) .not_to_have_channel_message_from("my-agent") .await?; session.close().await } #[tokio::test] #[ignore = "needs a running agent"] async fn follow_ups_in_the_thread_are_answered_without_a_new_mention() -> Result<()> { let session = fixtures::session().await?; let slack = session.slack().await?; let ana = slack.create_user().name("Ana").await?; let channel = slack .create_channel() .participants(vec![&ana as &dyn Handle, &slack.app()]) .await?; let msg = ana .say("@my-agent what's the status of the web deploy?") .channel(&channel) .await?; expect(&msg.thread()).to_have_reply_from("my-agent").await?; ana.reply("and the API?").thread(&msg).await?; expect(&msg.thread()) .to_have_reply_from("my-agent") .text(Regex::new("and the API")?) .await?; session.close().await } ``` Run them: ```bash npx vitest run ``` ``` Test Files 1 passed (1) Tests 2 passed (2) ``` Ana's follow-up has no mention. The fake sends it to the bot as a plain `message` event, and the Chat SDK hands it to `onSubscribedMessage` because the bot subscribed to that thread. ## 5. Break it on purpose Remove the subscription: ```diff title="agent.ts" bot.onNewMention(async (thread, message) => { if (message.author.isBot === true) return; - await thread.subscribe(); await thread.post(`On it: ${question(message.text)}`); }); ``` Restart the bot and run the tests again. The first still passes; the second fails once its wait runs out: ``` FAIL agent.test.ts > follow-ups in the thread are answered without a new mention Error: Expected a reply from my-agent matching /and the API/. The thread has: my-agent: On it: what's the status of the web deploy? Ana: and the API? ``` The bot still received Ana's follow-up, but without a subscription the Chat SDK has nothing to hand it to. Put `thread.subscribe()` back, restart the bot, and both tests pass. ## Other platforms The Chat SDK's GitHub and Linear adapters work the same way: each reads its API URL from what `channelstack env` prints (`GITHUB_API_URL`, `LINEAR_API_URL`), or takes an `apiUrl` option. Give each adapter its own endpoint and tell the server about it when it starts. These are the paths the `chat-sdk-github` and `chat-sdk-linear` reference agents use: | Adapter | Package | Endpoint | Server setting | | ------- | ----------------------------- | ---------------------- | --------------------------------- | | Slack | `@chat-adapter/slack@4.45.0` | `/slack/events` | `CHANNELSTACK_SLACK_WEBHOOK_URL` | | GitHub | `@chat-adapter/github@4.45.0` | `/api/webhooks/github` | `CHANNELSTACK_GITHUB_WEBHOOK_URL` | | Linear | `@chat-adapter/linear@4.45.0` | `/api/webhooks/linear` | `CHANNELSTACK_LINEAR_WEBHOOK_URL` | The server reads these once, when it starts, so restart it after adding one. ### GitHub The GitHub adapter runs as the GitHub App `channelstack env` describes. `GITHUB_PRIVATE_KEY` comes as one line, with `\n` for its line breaks: ```ts title="github-agent.ts" import { createGitHubAdapter } from "@chat-adapter/github"; import { createMemoryState } from "@chat-adapter/state-memory"; import { Chat } from "chat"; import { serve } from "./serve.ts"; const { GITHUB_APP_ID = "", GITHUB_PRIVATE_KEY = "", GITHUB_WEBHOOK_SECRET = "" } = process.env; const github = createGitHubAdapter({ appId: GITHUB_APP_ID, privateKey: GITHUB_PRIVATE_KEY.replaceAll("\\n", "\n"), webhookSecret: GITHUB_WEBHOOK_SECRET, userName: "my-agent", }); const bot = new Chat({ userName: "my-agent", adapters: { github }, state: createMemoryState(), logger: "warn" }); bot.onNewMention(async (thread) => { await thread.post("Thanks, I'll triage this."); }); serve(3001, "/api/webhooks/github", (request) => bot.webhooks.github(request)); ``` ```ts title="TypeScript" import { expect, test } from "vitest"; test("a mention in an issue gets one comment", async ({ github }) => { const ana = await github.createUser({ login: "ana" }); const repo = await github.createRepo({ collaborators: [ana], apps: [github.app] }); const issue = await ana.openIssue({ title: "Login fails on Safari" }, { repo }); await ana.comment("@my-agent can you triage this?", { issue }); await expect(issue).toHaveCommentFrom(github.app, { text: /triage/i }); await expect(issue).toHaveCommentsFrom(github.app, { count: 1, quietFor: "2s" }); }); ``` ```python title="Python" import re from channelstack import GitHubFixture from pytest_channelstack import expect async def test_a_mention_in_an_issue_gets_one_comment(github: GitHubFixture) -> None: ana = await github.create_user(login="ana") repo = await github.create_repo(collaborators=[ana], apps=[github.app]) issue = await ana.open_issue({"title": "Login fails on Safari"}, repo=repo) await ana.comment("@my-agent can you triage this?", issue=issue) await expect(issue).to_have_comment_from(github.app, text=re.compile("triage", re.I)) await expect(issue).to_have_comments_from(github.app, count=1, quiet_for="2s") ``` ```rust title="Rust" let ana = github.create_user().login("ana").await?; let repo = github .create_repo() .collaborators(vec![&ana as &dyn Handle]) .apps(vec![&github.app()]) .await?; let issue = ana .open_issue(json!({ "title": "Login fails on Safari" })) .repo(&repo) .await?; ana.comment("@my-agent can you triage this?") .issue(&issue) .await?; expect(&issue) .to_have_comment_from(&github.app()) .text(Regex::new("(?i)triage")?) .await?; expect(&issue) .to_have_comments_from(&github.app(), 1) .quiet_for("2s") .await?; ``` Start the server with `CHANNELSTACK_GITHUB_WEBHOOK_URL=http://127.0.0.1:3001/api/webhooks/github`. The [GitHub page](https://channelstack.dev/docs/platforms/github) covers pull requests, reviews and check runs. ### Linear The Linear adapter in `agent-sessions` mode turns a delegation or a mention into a new mention, and a post in that thread into the session's `response` activity. It reads `LINEAR_WEBHOOK_SECRET` and `LINEAR_API_URL` from the environment: ```ts title="linear-agent.ts" import { createLinearAdapter } from "@chat-adapter/linear"; import { createMemoryState } from "@chat-adapter/state-memory"; import { Chat } from "chat"; import { serve } from "./serve.ts"; const linear = createLinearAdapter({ mode: "agent-sessions", accessToken: process.env.LINEAR_ACCESS_TOKEN ?? "", userName: "my-agent", }); const bot = new Chat({ userName: "my-agent", adapters: { linear }, state: createMemoryState(), logger: "warn" }); bot.onNewMention(async (thread) => { await thread.post("I'm on it."); }); serve(3002, "/api/webhooks/linear", (request) => bot.webhooks.linear(request)); ``` ```ts title="TypeScript" import { expect, test } from "vitest"; test("delegating an issue gets a response in its session", async ({ linear }) => { const ana = await linear.createUser({ name: "Ana" }); const team = await linear.createTeam({ members: [ana] }); const issue = await ana.createIssue({ title: "Checkout fails on Safari" }, { team }); const session = await ana.delegate(linear.app, { issue }); await expect(session).toHaveActivity({ type: "response" }); await expect(issue).toBeDelegatedTo(linear.app); }); ``` ```python title="Python" from channelstack import LinearFixture from pytest_channelstack import expect async def test_delegating_an_issue_gets_a_response_in_its_session(linear: LinearFixture) -> None: ana = await linear.create_user(name="Ana") team = await linear.create_team(members=[ana]) issue = await ana.create_issue({"title": "Checkout fails on Safari"}, team=team) session = await ana.delegate(linear.app, issue=issue) await expect(session).to_have_activity(type="response") await expect(issue).to_be_delegated_to(linear.app) ``` ```rust title="Rust" let ana = linear.create_user().name("Ana").await?; let team = linear.create_team().members(vec![&ana]).await?; let issue = ana .create_issue(json!({ "title": "Checkout fails on Safari" })) .team(&team) .await?; let session = ana.delegate(&linear.app()).issue(&issue).await?; expect(&session) .to_have_activity() .r#type("response") .await?; expect(&issue).to_be_delegated_to(&linear.app()).await?; ``` Start the server with `CHANNELSTACK_LINEAR_WEBHOOK_URL=http://127.0.0.1:3002/api/webhooks/linear`. The reference agent also posts thoughts and moves the issue's state through its own `LinearClient`; the [Linear page](https://channelstack.dev/docs/platforms/linear) shows what a test can check of those. ## Next steps - [Connecting your agent](https://channelstack.dev/docs/guide/connecting-your-agent): portless, HTTPS and TLS trust, and the other SDKs' base-URL options. - [Standard checks](https://channelstack.dev/docs/guide/standard-checks): add `slackChecks()` and the others to test retries, bad signatures and Stop without writing those tests yourself. - [Slack](https://channelstack.dev/docs/platforms/slack): buttons, modals, slash commands, streams and Stop, all of which the Chat SDK reference agent handles. - [AI SDK](https://channelstack.dev/docs/quickstarts/ai-sdk): stream a model's answer into Slack and test the stream. # AI SDK Source: https://channelstack.dev/docs/quickstarts/ai-sdk In this tutorial you write a Bolt app that answers a direct message by streaming text from the [AI SDK](https://ai-sdk.dev)'s `streamText` into Slack. Its model is OpenAI, through the AI SDK's OpenAI provider (`@ai-sdk/openai`), and in tests that is channelstack's [fake OpenAI](https://channelstack.dev/docs/platforms/openai): each test scripts what the model streams, so every run streams the same answer and needs no API key. Then you test the status line, the stream and the Stop button, and break the agent once. It's a short version of the `openai-ai-sdk` reference agent that channelstack's CI runs. [Getting started](https://channelstack.dev/docs/getting-started) explains the server, `channelstack env` and a first test in more detail. This page builds on it. ## 1. Create the project You need Node.js 24 or newer, which runs the TypeScript files below as they are. ```bash mkdir streaming-agent && cd streaming-agent npm init -y npm pkg set type=module npm i @slack/bolt@5.1.0 ai@7.0.177 @ai-sdk/openai@4.0.124 npm i -D channelstack vitest ``` These are the versions channelstack's CI runs the reference agent with. ## 2. Start channelstack In a second terminal: ```bash CHANNELSTACK_SLACK_WEBHOOK_URL=http://localhost:3000/slack/events \ npx channelstack start --no-portless --port 4500 ``` In the first terminal: ```bash npx channelstack env > .env.local ``` ## 3. The model Among the lines `channelstack env` printed are two for the model: ```ini title=".env.local" OPENAI_BASE_URL=http://127.0.0.1:4500/openai/v1 OPENAI_API_KEY=sk-proj-… ``` (With portless, the base URL is `https://openai.localhost/v1`.) The AI SDK's `openai` provider reads both by itself, so the agent needs no setting of its own: with them it talks to the fake OpenAI, and in production, without `OPENAI_BASE_URL` and with your real key, to OpenAI. The fake has no default answer. A model call that no test scripted gets a 400 (`channelstack_no_script`), and the test fails, saying which `openai.respond(…)` would have answered it. ## 4. Write the agent The agent answers each direct message in three steps: it sets a status line, streams the model's text into one message with `chat.startStream` and `chat.appendStream`, and ends the stream with `chat.stopStream`. When the person presses Stop, Slack sends `agent_session_stopped`, and the agent aborts the model: ```ts title="agent.ts" import { openai } from "@ai-sdk/openai"; import { App } from "@slack/bolt"; import { streamText } from "ai"; const app = new App({ token: process.env.SLACK_BOT_TOKEN, signingSecret: process.env.SLACK_SIGNING_SECRET, // Unset in production, so the agent talks to Slack itself. clientOptions: process.env.SLACK_API_URL ? { slackApiUrl: process.env.SLACK_API_URL } : {}, }); /** What is being written right now, by thread: Stop aborts it. */ const writing = new Map(); app.event("agent_session_stopped", async ({ event }) => { const { channel, thread_ts: thread } = event as unknown as { channel: string; thread_ts: string }; writing.get(`${channel}:${thread}`)?.abort(); }); app.message(async ({ message, client }) => { // Only what a person newly wrote in a DM: no edits, no bots. if (message.subtype !== undefined || "bot_id" in message || message.channel_type !== "im") return; const { channel } = message; const thread = message.thread_ts ?? message.ts; const prompt = message.text ?? ""; await client.assistant.threads.setStatus({ channel_id: channel, thread_ts: thread, status: "is thinking…" }); const stop = new AbortController(); writing.set(`${channel}:${thread}`, stop); const { textStream } = streamText({ model: openai("gpt-5-mini"), prompt, abortSignal: stop.signal, // The person's Slack id as OpenAI's `user`: it tells channelstack whose question the call answers. providerOptions: { openai: { user: message.user } }, }); let stream: string | undefined; try { for await (const text of textStream) { if (stop.signal.aborted) return; if (stream === undefined) stream = (await client.chat.startStream({ channel, thread_ts: thread, markdown_text: text })).ts; else await client.chat.appendStream({ channel, ts: stream, markdown_text: text }); } if (stream !== undefined && !stop.signal.aborted) await client.chat.stopStream({ channel, ts: stream }); } catch (error) { // After Stop, Slack refuses more text with `stopped_by_user`: that is expected. const stopped = (error as { data?: { error?: string } }).data?.error === "stopped_by_user"; if (!stop.signal.aborted && !stopped) throw error; } finally { writing.delete(`${channel}:${thread}`); } }); await app.start(3000); console.log("⚡️ Bolt app is running"); ``` It streams in a DM because Slack allows a stream there without more arguments. To stream in a thread of a channel, `chat.startStream` also needs `recipient_user_id` and `recipient_team_id`, and the fake refuses it without them, as Slack does. Start it in a third terminal: ```bash node --env-file=.env.local agent.ts ``` ## 5. Write the tests Add the Vitest plugin: ```ts title="vitest.config.ts" import channelstack from "channelstack/vitest"; import { defineConfig } from "vitest/config"; export default defineConfig({ plugins: [channelstack()], }); ``` And two tests. Each first scripts what the model answers with the `openai` fixture: the first streams four pieces of release notes, a little slowly, and watches the answer from the status line to the end of the stream; the second holds a long answer after three pieces, presses Stop, and checks that the agent cancelled its model call: ```ts title="TypeScript" import { expect, test } from "vitest"; /** What the model streams, a piece at a time. */ const notes = [ "# Release notes for 0.10\n\n", "## What changed\n\nThe delivery queue now retries a slow acknowledgement the way the platform does.\n\n", "## What to do\n\nUpdate, run the tests once and read the new failure messages.\n\n", "## Thanks\n\nTo everyone who sent the transcript of a conversation that went wrong.\n", ]; test("streams a reply and shows a status while working", async ({ slack, openai }) => { await openai.respond({ text: notes }, { timing: { firstToken: "700ms", betweenChunks: "250ms" } }); const ana = await slack.createUser({ name: "Ana" }); const msg = await ana.say("write the release notes for 0.10", { to: slack.app }); await expect(msg.thread).toHaveStatus("working"); await expect(msg.thread).toHaveStatusText(/thinking/i); await expect(msg.thread).toHaveStreamingReplyFrom("my-agent"); await expect(msg.thread).toHaveStatus("idle"); const reply = await msg.thread.latestReply({ from: "my-agent" }); const stream = await reply.stream!.ended(); expect(stream.state).toBe("completed"); await expect(openai).toHaveSent(msg); }); test("Stop ends the stream and cancels the model", async ({ slack, openai }) => { const ai = await openai.respond({ text: "More detail, for those who asked. ".repeat(40), pauseAfter: 3 }); const ana = await slack.createUser({ name: "Ana" }); const msg = await ana.say("write a long report on Q3", { to: slack.app }); const call = await ai.waitForPause(); await expect(msg.thread).toHaveStreamingReplyFrom("my-agent"); await ana.stop({ thread: msg }); await expect(msg.thread).toHaveStatus("stopped"); await expect(msg.thread).toHaveRepliesFrom("my-agent", { count: 1 }); await expect(call).toBeAborted(); }); ``` ```python title="Python" import re from channelstack import OpenAIFixture, OpenAITiming, OpenAITurn, SlackFixture from pytest_channelstack import expect # What the model streams, a piece at a time. NOTES = [ "# Release notes for 0.10\n\n", "## What changed\n\nThe delivery queue now retries a slow acknowledgement the way the platform does.\n\n", "## What to do\n\nUpdate, run the tests once and read the new failure messages.\n\n", "## Thanks\n\nTo everyone who sent the transcript of a conversation that went wrong.\n", ] async def test_streams_a_reply_and_shows_a_status_while_working(slack: SlackFixture, openai: OpenAIFixture) -> None: await openai.respond(OpenAITurn(text=NOTES), timing=OpenAITiming(first_token="700ms", between_chunks="250ms")) ana = await slack.create_user(name="Ana") msg = await ana.say("write the release notes for 0.10", to=slack.app) await expect(msg.thread).to_have_status("working") await expect(msg.thread).to_have_status_text(re.compile("thinking", re.I)) await expect(msg.thread).to_have_streaming_reply_from("my-agent") await expect(msg.thread).to_have_status("idle") reply = await msg.thread.latest_reply(from_="my-agent") assert reply.stream stream = await reply.stream.ended() assert stream.state == "completed" await expect(openai).to_have_sent(msg) async def test_stop_ends_the_stream_and_cancels_the_model(slack: SlackFixture, openai: OpenAIFixture) -> None: ai = await openai.respond(OpenAITurn(text="More detail, for those who asked. " * 40, pause_after=3)) ana = await slack.create_user(name="Ana") msg = await ana.say("write a long report on Q3", to=slack.app) call = await ai.wait_for_pause() await expect(msg.thread).to_have_streaming_reply_from("my-agent") await ana.stop(thread=msg) await expect(msg.thread).to_have_status("stopped") await expect(msg.thread).to_have_replies_from("my-agent", count=1) await expect(call).to_be_aborted() ``` ```rust title="Rust" /// What the model streams, a piece at a time. const NOTES: [&str; 4] = [ "# Release notes for 0.10\n\n", "## What changed\n\nThe delivery queue now retries a slow acknowledgement the way the platform does.\n\n", "## What to do\n\nUpdate, run the tests once and read the new failure messages.\n\n", "## Thanks\n\nTo everyone who sent the transcript of a conversation that went wrong.\n", ]; #[tokio::test] #[ignore = "needs a running agent"] async fn streams_a_reply_and_shows_a_status_while_working() -> Result<()> { let session = fixtures::session().await?; let slack = session.slack().await?; let openai = session.openai().await?; openai .respond(json!({ "text": NOTES })) .timing(json!({ "firstToken": "700ms", "betweenChunks": "250ms" })) .await?; let ana = slack.create_user().name("Ana").await?; let msg = ana .say("write the release notes for 0.10") .to(&slack.app()) .await?; expect(&msg.thread()).to_have_status("working").await?; expect(&msg.thread()) .to_have_status_text(Regex::new("(?i)thinking")?) .await?; expect(&msg.thread()) .to_have_streaming_reply_from("my-agent") .await?; expect(&msg.thread()).to_have_status("idle").await?; let reply = msg.thread().latest_reply().from("my-agent").await?; let stream = reply.stream().expect("a streamed reply").ended().await?; assert_eq!(stream.state(), "completed"); expect(&openai).to_have_sent(msg.text()).await?; session.close().await } #[tokio::test] #[ignore = "needs a running agent"] async fn stop_ends_the_stream_and_cancels_the_model() -> Result<()> { let session = fixtures::session().await?; let slack = session.slack().await?; let openai = session.openai().await?; let ai = openai .respond( json!({ "text": "More detail, for those who asked. ".repeat(40), "pauseAfter": 3 }), ) .await?; let ana = slack.create_user().name("Ana").await?; let msg = ana .say("write a long report on Q3") .to(&slack.app()) .await?; let call = ai.wait_for_pause().await?; expect(&msg.thread()) .to_have_streaming_reply_from("my-agent") .await?; ana.stop().thread(&msg).await?; expect(&msg.thread()).to_have_status("stopped").await?; expect(&msg.thread()) .to_have_replies_from("my-agent", 1) .await?; expect(&call).to_be_aborted().await?; session.close().await } ``` Run them: ```bash npx vitest run ``` ``` Test Files 1 passed (1) Tests 2 passed (2) ``` `toHaveStatus` reads what a person sees of the agent in that thread: `working` while the status line is set, `streaming` while a stream is open, `idle` once it has ended, and `stopped` after Stop. Each check waits until it holds, so the first test follows the answer through those states in order, and `reply.stream` says how the stream ended: `completed` here. `toHaveSent(msg)` checks that Ana's message is what the agent asked the model. In the second, `pauseAfter: 3` holds the model's stream after three pieces, `ai.waitForPause()` returns that call, `toHaveRepliesFrom` waits until the agent is quiet and then counts (one message, the stream, and nothing after it), and `toBeAborted` checks that Stop cancelled the model's request instead of leaving it running. ## 6. Break it on purpose Forget to end the stream: ```diff title="agent.ts" - if (stream !== undefined && !stop.signal.aborted) await client.chat.stopStream({ channel, ts: stream }); ``` Restart the agent and run the tests again. The first test fails once its wait runs out: ``` FAIL agent.test.ts > streams a reply and shows a status while working Error: Expected the thread to be idle, it is streaming Still open: a stream my-agent started and never stopped: "# Release notes for 0.10" ``` Every piece of text arrived, so the message looks complete in a test that only reads its text. In Slack it would still show as being written. The `Still open:` line is channelstack telling you what the agent left unfinished, which is often the bug itself. Put `stopStream` back, restart the agent, and both tests pass. ## Next steps - [Slack](https://channelstack.dev/docs/platforms/slack): streams, the status line, Stop and the agent split view, and the errors the fake answers with. - [OpenAI](https://channelstack.dev/docs/platforms/openai): tool calls, a slow first token, a stream that breaks, errors, and what the agent sent. - [Waiting and quiet](https://channelstack.dev/docs/guide/waiting-and-quiet): why `toHaveRepliesFrom` waits for quiet and the other checks don't. - [Standard checks](https://channelstack.dev/docs/guide/standard-checks): `slackChecks({ app: "my-agent", model: "openai" })` adds the model checks to the Slack ones. - [Chat SDK](https://channelstack.dev/docs/quickstarts/chat-sdk): the same kind of agent on the Chat SDK, where `thread.post(textStream)` streams for you. # Pi Source: https://channelstack.dev/docs/quickstarts/pi In this tutorial you put [Pi](https://github.com/earendil-works/pi), the coding agent, in Slack: a Bolt app hands each mention to a Pi session through Pi's SDK and posts Pi's answer in the thread. Pi runs on pi-ai's faux provider, a scripted model, so every run gives the same answer. Then you test it against channelstack's fake Slack and break it once. [Getting started](https://channelstack.dev/docs/getting-started) explains the server, `channelstack env` and a first test in more detail. This page builds on it. > [!NOTE] > channelstack's CI has no Pi reference agent yet. The Bolt side of this page is the one the `bolt-ai-sdk` reference agent runs. The Pi side (`createAgentSession` with the faux provider) follows Pi's SDK and Pi's own tests at version 1.6.0. These steps pass against channelstack as written, but CI doesn't run them, so a newer Pi may need changes. ## 1. Create the project You need Node.js 24 or newer, which runs the TypeScript files below as they are. ```bash mkdir pi-agent && cd pi-agent npm init -y npm pkg set type=module npm i @slack/bolt@5.1.0 @earendil-works/pi-coding-agent@1.6.0 @earendil-works/pi-ai@1.6.0 npm i -D channelstack vitest ``` Pi's packages used to be published as `@mariozechner/pi-coding-agent` and `@mariozechner/pi-ai`. Those names are deprecated; the `@earendil-works` ones are the current releases. ## 2. Start channelstack In a second terminal: ```bash CHANNELSTACK_SLACK_WEBHOOK_URL=http://localhost:3000/slack/events \ npx channelstack start --no-portless --port 4500 ``` In the first terminal: ```bash npx channelstack env > .env.local ``` ## 3. A scripted model pi-ai's faux provider is a model that answers with whatever you queue for it, in order, and streams it like a real one. Pi's own tests register it this way: ```ts title="model.ts" import { fauxAssistantMessage } from "@earendil-works/pi-ai"; import { registerFauxProvider } from "@earendil-works/pi-ai/compat"; import { ModelRuntime } from "@earendil-works/pi-coding-agent"; const faux = registerFauxProvider(); export const model = faux.getModel(); /** Pi's model runtime, with the faux provider as one more provider and a key it accepts. */ export const modelRuntime = await ModelRuntime.create({ modelsPath: null }); modelRuntime.registerProvider(model.provider, { baseUrl: model.baseUrl, api: model.api, models: [ { id: model.id, name: model.name, api: model.api, reasoning: model.reasoning, input: model.input, cost: model.cost, contextWindow: model.contextWindow, maxTokens: model.maxTokens, baseUrl: model.baseUrl, }, ], }); await modelRuntime.setRuntimeApiKey(model.provider, "faux-key"); /** Queue the model's next answer. */ export const answerNext = (text: string) => faux.appendResponses([fauxAssistantMessage(text)]); ``` In production you pick a real model from `ModelRuntime` instead (`modelRuntime.getModel("anthropic", …)`), with its API key, and drop `answerNext`. ## 4. Write the agent The agent keeps one Pi session per Slack thread, so a thread is one conversation with Pi. It turns off Pi's tools (`noTools: "all"`): a bot that answers anyone in a channel shouldn't run shell commands for them. ```ts title="agent.ts" import { App } from "@slack/bolt"; import { type AgentSession, createAgentSession, SessionManager, SettingsManager } from "@earendil-works/pi-coding-agent"; import { answerNext, model, modelRuntime } from "./model.ts"; const app = new App({ token: process.env.SLACK_BOT_TOKEN, signingSecret: process.env.SLACK_SIGNING_SECRET, // Unset in production, so the agent talks to Slack itself. clientOptions: process.env.SLACK_API_URL ? { slackApiUrl: process.env.SLACK_API_URL } : {}, }); /** One Pi session per thread, in memory. */ const sessions = new Map(); async function sessionFor(thread: string): Promise { const existing = sessions.get(thread); if (existing) return existing; const { session } = await createAgentSession({ model, modelRuntime, noTools: "all", sessionManager: SessionManager.inMemory(), settingsManager: SettingsManager.inMemory(), }); sessions.set(thread, session); return session; } app.event("app_mention", async ({ event, say }) => { // Other bots don't get answers. if ("bot_id" in event) return; const thread = event.thread_ts ?? event.ts; const question = event.text.replace(/<@[^>]+>\s*/, ""); const session = await sessionFor(`${event.channel}:${thread}`); answerNext(`On it: ${question}`); await session.prompt(question); await say({ text: session.getLastAssistantText() ?? "", thread_ts: thread }); }); await app.start(3000); console.log("⚡️ Bolt app is running"); ``` `session.prompt` resolves when Pi's run has finished, and `getLastAssistantText` is its answer. Start the agent in a third terminal: ```bash node --env-file=.env.local agent.ts ``` ## 5. Write the tests Add the Vitest plugin: ```ts title="vitest.config.ts" import channelstack from "channelstack/vitest"; import { defineConfig } from "vitest/config"; export default defineConfig({ plugins: [channelstack()], }); ``` And two tests: a person's mention gets one answer in the thread, and another bot's mention gets none: ```ts title="TypeScript" import { expect, test } from "vitest"; test("a mention gets one reply, in the thread", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); const channel = await slack.createChannel({ participants: [ana, slack.app] }); const msg = await ana.say("@my-agent summarize the incidents", { channel }); await expect(msg.thread).toHaveReplyFrom("my-agent", { text: /summarize the incidents/ }); await expect(msg.thread).toHaveRepliesFrom(slack.app, { count: 1 }); await expect(channel).not.toHaveChannelMessageFrom("my-agent"); }); test("it ignores other bots", async ({ slack }) => { const deployBot = await slack.createUser({ name: "deploy-bot", bot: true }); const channel = await slack.createChannel({ participants: [deployBot, slack.app] }); const msg = await deployBot.say("@my-agent build #812 failed", { channel }); await expect(msg.thread).not.toHaveReplyFrom("my-agent"); }); ``` ```python title="Python" import re from channelstack import SlackFixture from pytest_channelstack import expect async def test_a_mention_gets_one_reply_in_the_thread(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") channel = await slack.create_channel(participants=[ana, slack.app]) msg = await ana.say("@my-agent summarize the incidents", channel=channel) await expect(msg.thread).to_have_reply_from("my-agent", text=re.compile("summarize the incidents")) await expect(msg.thread).to_have_replies_from(slack.app, count=1) await expect(channel).not_to_have_channel_message_from("my-agent") async def test_it_ignores_other_bots(slack: SlackFixture) -> None: deploy_bot = await slack.create_user(name="deploy-bot", bot=True) channel = await slack.create_channel(participants=[deploy_bot, slack.app]) msg = await deploy_bot.say("@my-agent build #812 failed", channel=channel) await expect(msg.thread).not_to_have_reply_from("my-agent") ``` ```rust title="Rust" #[tokio::test] #[ignore = "needs a running agent"] async fn a_mention_gets_one_reply_in_the_thread() -> Result<()> { let session = fixtures::session().await?; let slack = session.slack().await?; let ana = slack.create_user().name("Ana").await?; let channel = slack .create_channel() .participants(vec![&ana as &dyn Handle, &slack.app()]) .await?; let msg = ana .say("@my-agent summarize the incidents") .channel(&channel) .await?; expect(&msg.thread()) .to_have_reply_from("my-agent") .text(Regex::new("summarize the incidents")?) .await?; expect(&msg.thread()) .to_have_replies_from(&slack.app(), 1) .await?; expect(&channel) .not_to_have_channel_message_from("my-agent") .await?; session.close().await } #[tokio::test] #[ignore = "needs a running agent"] async fn it_ignores_other_bots() -> Result<()> { let session = fixtures::session().await?; let slack = session.slack().await?; let deploy_bot = slack.create_user().name("deploy-bot").bot(true).await?; let channel = slack .create_channel() .participants(vec![&deploy_bot as &dyn Handle, &slack.app()]) .await?; let msg = deploy_bot .say("@my-agent build #812 failed") .channel(&channel) .await?; expect(&msg.thread()) .not_to_have_reply_from("my-agent") .await?; session.close().await } ``` Run them: ```bash npx vitest run ``` ``` Test Files 1 passed (1) Tests 2 passed (2) ``` The second test is a negative check: it passes only after it has watched the agent stay quiet for a while, not the moment it starts. [Waiting and quiet](https://channelstack.dev/docs/guide/waiting-and-quiet) explains how long, and why. ## 6. Break it on purpose An agent backed by a model that answers other bots can run up a bill, or end up in a loop with another bot. Remove the guard: ```diff title="agent.ts" - // Other bots don't get answers. - if ("bot_id" in event) return; ``` Restart the agent and run the tests again: ``` FAIL agent.test.ts > it ignores other bots Error: Expected no reply from my-agent. The thread has: my-agent: On it: build #812 failed ``` Put the guard back, restart the agent, and both tests pass. ## Next steps - [Slack](https://channelstack.dev/docs/platforms/slack): what else a Slack test can do, from buttons and modals to streams and Stop. - [AI SDK](https://channelstack.dev/docs/quickstarts/ai-sdk): stream a model's answer into Slack and test the stream, the status line and Stop. - [Proxy mode](https://channelstack.dev/docs/guide/proxy-mode): agents that hard-code `slack.com` and take no base URL. - [pytest](https://channelstack.dev/docs/guide/pytest): the same tests from Python. # LangChain Source: https://channelstack.dev/docs/quickstarts/langchain In this tutorial you write a Bolt app that answers a direct message by streaming a [LangChain](https://js.langchain.com) chat model into Slack, and that runs a tool when the model calls one. Its model is OpenAI, through LangChain's `ChatOpenAI` (`@langchain/openai`), and in tests that is channelstack's [fake OpenAI](https://channelstack.dev/docs/platforms/openai): each test scripts what the model answers, so every run gets the same answer and needs no API key. Then you test the stream, the status line and a tool call, and break the agent once. [Getting started](https://channelstack.dev/docs/getting-started) explains the server, `channelstack env` and a first test in more detail. This page builds on it. ## 1. Create the project You need Node.js 24 or newer, which runs the TypeScript files below as they are. ```bash mkdir langchain-agent && cd langchain-agent npm init -y npm pkg set type=module npm i @slack/bolt@5.1.0 @langchain/openai@1.8.5 @langchain/core@1.5.1 npm i -D channelstack vitest ``` These are the versions this page was tested with. ## 2. Start channelstack In a second terminal: ```bash CHANNELSTACK_SLACK_WEBHOOK_URL=http://localhost:3000/slack/events \ npx channelstack start --no-portless --port 4500 ``` In the first terminal: ```bash npx channelstack env > .env.local ``` ## 3. The model Among the lines `channelstack env` printed are two for the model: ```ini title=".env.local" OPENAI_BASE_URL=http://127.0.0.1:4500/openai/v1 OPENAI_API_KEY=sk-proj-… ``` (With portless, the base URL is `https://openai.localhost/v1`.) `ChatOpenAI` reads both by itself, so the agent needs no setting of its own: with them it talks to the fake OpenAI, and in production, without `OPENAI_BASE_URL` and with your real key, to OpenAI. The fake has no default answer. A model call that no test scripted gets a 400 (`channelstack_no_script`), and the test fails, saying which `openai.respond(…)` would have answered it. ## 4. Write the agent The agent answers each direct message: it sets a status line, gives the model a tool that searches the incident log, and streams what the model writes into one message with `chat.startStream` and `chat.appendStream`. When the model calls the tool instead, the agent runs it, sends the result back and asks again, until the model answers. Then it ends the stream with `chat.stopStream`. When the person presses Stop, Slack sends `agent_session_stopped`, and the agent aborts the model: ```ts title="agent.ts" import { type AIMessageChunk, type BaseMessage, HumanMessage, SystemMessage } from "@langchain/core/messages"; import { tool } from "@langchain/core/tools"; import { ChatOpenAI } from "@langchain/openai"; import { App } from "@slack/bolt"; const app = new App({ token: process.env.SLACK_BOT_TOKEN, signingSecret: process.env.SLACK_SIGNING_SECRET, // Unset in production, so the agent talks to Slack itself. clientOptions: process.env.SLACK_API_URL ? { slackApiUrl: process.env.SLACK_API_URL } : {}, }); /** The one tool the model may call: a search of the incident log. */ const searchIncidents = tool( async () => "The web deploy failed at the migration step at 14:02; a DNS blip at 02:10 resolved itself.", { name: "search_incidents", description: "Search the incident log", schema: { type: "object", properties: { since: { type: "string" } } }, }, ); /** What is being written right now, by thread: Stop aborts it. */ const writing = new Map(); app.event("agent_session_stopped", async ({ event }) => { const { channel, thread_ts: thread } = event as unknown as { channel: string; thread_ts: string }; writing.get(`${channel}:${thread}`)?.abort(); }); app.message(async ({ message, client }) => { // Only what a person newly wrote in a DM: no edits, no bots. if (message.subtype !== undefined || "bot_id" in message || message.channel_type !== "im") return; const { channel } = message; const thread = message.thread_ts ?? message.ts; await client.assistant.threads.setStatus({ channel_id: channel, thread_ts: thread, status: "is thinking…" }); const stop = new AbortController(); writing.set(`${channel}:${thread}`, stop); // The person's Slack id as OpenAI's `user`: it tells channelstack whose question the call answers. const model = new ChatOpenAI({ model: "gpt-5-mini", user: message.user }).bindTools([searchIncidents]); const messages: BaseMessage[] = [ new SystemMessage("You are my-agent, the team's assistant in Slack. Answer briefly."), new HumanMessage(message.text ?? ""), ]; let stream: string | undefined; try { // Until the model answers without calling the tool: at most five steps. for (let step = 0; step < 5; step += 1) { let answer: AIMessageChunk | undefined; for await (const chunk of await model.stream(messages, { signal: stop.signal })) { answer = answer === undefined ? chunk : answer.concat(chunk); if (stop.signal.aborted || chunk.text === "") continue; if (stream === undefined) stream = (await client.chat.startStream({ channel, thread_ts: thread, markdown_text: chunk.text })).ts; else await client.chat.appendStream({ channel, ts: stream, markdown_text: chunk.text }); } if (answer === undefined || !answer.tool_calls?.length) break; messages.push(answer); for (const call of answer.tool_calls) messages.push(await searchIncidents.invoke(call)); } if (stream !== undefined && !stop.signal.aborted) await client.chat.stopStream({ channel, ts: stream }); } catch (error) { // After Stop, Slack refuses more text with `stopped_by_user`: that is expected. const stopped = (error as { data?: { error?: string } }).data?.error === "stopped_by_user"; if (!stop.signal.aborted && !stopped) throw error; } finally { writing.delete(`${channel}:${thread}`); } }); await app.start(3000); console.log("⚡️ Bolt app is running"); ``` `answer.concat(chunk)` joins the streamed pieces into one message, so once the stream ends, `answer.tool_calls` holds the tool calls whole. `searchIncidents.invoke(call)` runs the tool with the model's arguments and returns the `ToolMessage` that carries its result back to the model. It streams in a DM because Slack allows a stream there without more arguments. To stream in a thread of a channel, `chat.startStream` also needs `recipient_user_id` and `recipient_team_id`, and the fake refuses it without them, as Slack does. Start it in a third terminal: ```bash node --env-file=.env.local agent.ts ``` ## 5. Write the tests Add the Vitest plugin: ```ts title="vitest.config.ts" import channelstack from "channelstack/vitest"; import { defineConfig } from "vitest/config"; export default defineConfig({ plugins: [channelstack()], }); ``` And two tests. Each first scripts what the model answers with the `openai` fixture: the first streams four pieces of an answer, a little slowly, and watches it from the status line to the end of the stream; the second scripts two turns, a call of `search_incidents` and then the answer, and checks that the agent ran the tool and sent its result back: ```ts title="TypeScript" import { expect, test } from "vitest"; test("streams the answer into the DM, and the status clears", async ({ slack, openai }) => { await openai.respond( { text: ["The web deploy", " failed at", " the migration", " step."] }, { timing: { firstToken: "700ms", betweenChunks: "250ms" } }, ); const ana = await slack.createUser({ name: "Ana" }); const msg = await ana.say("why did the deploy fail?", { to: slack.app }); await expect(msg.thread).toHaveStatus("working"); await expect(msg.thread).toHaveStatusText(/thinking/i); await expect(msg.thread).toHaveStreamingReplyFrom("my-agent"); await expect(msg.thread).toHaveStatus("idle"); await expect(msg.thread).toHaveReplyFrom("my-agent", { text: /failed at the migration step/ }); await expect(openai).toHaveSent(msg); }); test("the agent runs the tool the model calls, and answers from its result", async ({ slack, openai }) => { const ai = await openai.respond([ { toolCalls: [{ name: "search_incidents", arguments: { since: "yesterday" } }] }, "Two incidents yesterday: the web deploy and a DNS blip.", ]); const ana = await slack.createUser({ name: "Ana" }); const msg = await ana.say("what broke yesterday?", { to: slack.app }); await expect(msg.thread).toHaveReplyFrom("my-agent", { text: /DNS blip/ }); await expect(msg.thread).toHaveRepliesFrom("my-agent", { count: 1 }); await expect(ai).toHaveAnswered({ times: 2 }); await expect(ai).toHaveSentToolResult("search_incidents", { text: /migration/ }); }); ``` ```python title="Python" import re from channelstack import OpenAIFixture, OpenAITiming, OpenAIToolCallSpec, OpenAITurn, SlackFixture from pytest_channelstack import expect async def test_streams_the_answer_into_the_dm_and_the_status_clears(slack: SlackFixture, openai: OpenAIFixture) -> None: await openai.respond( OpenAITurn(text=["The web deploy", " failed at", " the migration", " step."]), timing=OpenAITiming(first_token="700ms", between_chunks="250ms"), ) ana = await slack.create_user(name="Ana") msg = await ana.say("why did the deploy fail?", to=slack.app) await expect(msg.thread).to_have_status("working") await expect(msg.thread).to_have_status_text(re.compile("thinking", re.I)) await expect(msg.thread).to_have_streaming_reply_from("my-agent") await expect(msg.thread).to_have_status("idle") await expect(msg.thread).to_have_reply_from("my-agent", text=re.compile("failed at the migration step")) await expect(openai).to_have_sent(msg) async def test_the_agent_runs_the_tool_the_model_calls_and_answers_from_its_result( slack: SlackFixture, openai: OpenAIFixture ) -> None: ai = await openai.respond( [ OpenAITurn(tool_calls=[OpenAIToolCallSpec(name="search_incidents", arguments={"since": "yesterday"})]), "Two incidents yesterday: the web deploy and a DNS blip.", ] ) ana = await slack.create_user(name="Ana") msg = await ana.say("what broke yesterday?", to=slack.app) await expect(msg.thread).to_have_reply_from("my-agent", text=re.compile("DNS blip")) await expect(msg.thread).to_have_replies_from("my-agent", count=1) await expect(ai).to_have_answered(times=2) await expect(ai).to_have_sent_tool_result("search_incidents", text=re.compile("migration")) ``` ```rust title="Rust" #[tokio::test] #[ignore = "needs a running agent"] async fn streams_the_answer_into_the_dm_and_the_status_clears() -> Result<()> { let session = fixtures::session().await?; let slack = session.slack().await?; let openai = session.openai().await?; openai .respond(json!({ "text": ["The web deploy", " failed at", " the migration", " step."] })) .timing(json!({ "firstToken": "700ms", "betweenChunks": "250ms" })) .await?; let ana = slack.create_user().name("Ana").await?; let msg = ana.say("why did the deploy fail?").to(&slack.app()).await?; expect(&msg.thread()).to_have_status("working").await?; expect(&msg.thread()) .to_have_status_text(Regex::new("(?i)thinking")?) .await?; expect(&msg.thread()) .to_have_streaming_reply_from("my-agent") .await?; expect(&msg.thread()).to_have_status("idle").await?; expect(&msg.thread()) .to_have_reply_from("my-agent") .text(Regex::new("failed at the migration step")?) .await?; expect(&openai).to_have_sent(msg.text()).await?; session.close().await } #[tokio::test] #[ignore = "needs a running agent"] async fn the_agent_runs_the_tool_the_model_calls_and_answers_from_its_result() -> Result<()> { let session = fixtures::session().await?; let slack = session.slack().await?; let openai = session.openai().await?; let ai = openai .respond(json!([ { "toolCalls": [{ "name": "search_incidents", "arguments": { "since": "yesterday" } }] }, "Two incidents yesterday: the web deploy and a DNS blip.", ])) .await?; let ana = slack.create_user().name("Ana").await?; let msg = ana.say("what broke yesterday?").to(&slack.app()).await?; expect(&msg.thread()) .to_have_reply_from("my-agent") .text(Regex::new("DNS blip")?) .await?; expect(&msg.thread()) .to_have_replies_from("my-agent", 1) .await?; expect(&ai).to_have_answered().times(2).await?; expect(&ai) .to_have_sent_tool_result("search_incidents") .text(Regex::new("migration")?) .await?; session.close().await } ``` Run them: ```bash npx vitest run ``` ``` Test Files 1 passed (1) Tests 2 passed (2) ``` `toHaveStatus` reads what a person sees of the agent in that thread: `working` while the status line is set, `streaming` while a stream is open, and `idle` once it has ended. Each check waits until it holds, so the first test follows the answer through those states in order. `toHaveSent(msg)` checks that Ana's message is what the agent asked the model. In the second, each scripted turn answers one model call: `toHaveAnswered({ times: 2 })` checks that the agent asked twice, once for the tool call and once with its result, and `toHaveSentToolResult` that the second call carried the tool's result, with what the tool returned. ## 6. Break it on purpose Forget to give the model its tool: ```diff title="agent.ts" - const model = new ChatOpenAI({ model: "gpt-5-mini", user: message.user }).bindTools([searchIncidents]); + const model = new ChatOpenAI({ model: "gpt-5-mini", user: message.user }); ``` Restart the agent and run the tests again. The second test fails at once: ``` FAIL agent.test.ts > the agent runs the tool the model calls, and answers from its result Error: The model calls of this test went wrong: ms_vashkpt1awtp called `search_incidents`, but the request offered no tools ``` A real model can't call a tool the request doesn't offer, so the fake answers that call with a 400 and the test says why, instead of waiting for a reply that never comes. Put `bindTools` back, restart the agent, and both tests pass. ## Next steps - [OpenAI](https://channelstack.dev/docs/platforms/openai): tool calls, a slow first token, a stream that breaks, errors, and what the agent sent. - [Slack](https://channelstack.dev/docs/platforms/slack): streams, the status line, Stop and the agent split view, and the errors the fake answers with. - [Waiting and quiet](https://channelstack.dev/docs/guide/waiting-and-quiet): why `toHaveRepliesFrom` waits for quiet and the other checks don't. - [Standard checks](https://channelstack.dev/docs/guide/standard-checks): `slackChecks({ app: "my-agent", model: "openai" })` adds the model checks to the Slack ones. - [AI SDK](https://channelstack.dev/docs/quickstarts/ai-sdk): the same kind of agent on the AI SDK, with a test of the Stop button. # How it works Source: https://channelstack.dev/docs/guide/how-it-works This page explains the parts of channelstack and how they fit together: the server and its fakes, the control API every client uses, sessions, and the transcript the matchers read. Read it when you want to know why a test behaves the way it does. 1. The test acts as Ana: she mentions the app in a channel. 2. The fake Slack delivers the event to your app, signed, the way Slack does. 3. Your app answers through the Slack API it already uses, which now points at the fake. 4. The matcher reads the thread as Ana would see it, and passes. ## One server, eight fakes channelstack is one server process. It fakes Slack, GitHub, Linear, Notion, Resend, Google (Gmail) and Discord in memory, and OpenAI's API for your agent's model, and serves each fake at a stable local address: | Address | What it is | | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `https://channelstack.localhost` | The UI, and the control API at `/_channelstack` | | `https://slack.localhost` | Slack's Web API and Socket Mode; sends Events API requests and interactivity payloads | | `https://github.localhost` | GitHub's REST API (also at the GHE-style `/api/v3`); sends App webhooks | | `https://linear.localhost` | Linear's GraphQL API at `/graphql`; sends webhooks and Agent Session events | | `https://notion.localhost` | Notion's API; sends integration webhooks | | `https://resend.localhost` | Resend's REST API; sends its webhooks, signed the Svix way | | `https://google.localhost` | Gmail's API, Google's token endpoint and certificates; sends Pub/Sub pushes | | `https://discord.localhost` | Discord's REST API at `/api/v10` and its Gateway; sends interactions, signed with Ed25519 | | `https://openai.localhost` | OpenAI's API at `/v1` for your agent's model: Chat Completions, Responses, Conversations, images, audio and files. It sends nothing; each test scripts what it answers | The `*.localhost` names come from [portless](https://github.com/vercel-labs/portless). Without it, the server listens on one loopback port and puts each fake under a path prefix (`http://127.0.0.1:4500/slack`, `/github`, and so on). The [connecting your app](https://channelstack.dev/docs/guide/connecting-your-agent) page shows both. Your app talks to a fake as if it were the real platform. It uses the platform's own SDK, unchanged, with only the base URL pointed at channelstack. The fakes behave like the platforms in the ways an app notices: - **Ids look real.** A Slack user is `U08B5K2M9QX`, a channel `C08E1F2G3H4`, a message `ts` like `1732101234.567899`. GitHub uses numeric ids and 40-hex commit SHAs from an in-memory git store, Linear, Notion and Resend use UUIDs, Gmail 16 hex characters for messages and threads and decimal history ids (and an email person is their address), Discord snowflakes, and tokens have the platform's prefixes (`xoxb-…`, `ghs_…`, `lin_oauth_…`, `ntn_…`, `re_…`, `ya29.…`, `1//0…`) or form (a Discord bot token's `.<6>.<38>`). Your app's logs and your failing tests read like production. - **Refusals are real.** A fake refuses what the platform refuses, with the same error code: `not_in_channel` when the bot posts where it isn't a member, `missing_scope`, `msg_too_long`. - **Deliveries are real.** Events arrive signed the way each platform signs them, within the same ack windows, and Slack retries the way Slack does. See [delivery and failures](https://channelstack.dev/docs/guide/delivery-and-failures). The fake OpenAI isn't a platform: it has no people, apps or deliveries, and your agent only calls it. It's realistic on the wire, with OpenAI's event shapes, ids, tool calls, errors and rate-limit headers, and never in content: the model says what the test scripted with the `openai` fixture, and a call no script answers fails the test. A model call carries no session, so channelstack gives it to the test whose conversation it answers, from what the call carries. See [OpenAI](https://channelstack.dev/docs/platforms/openai). Each platform's fake has one built-in app, named `my-agent`, that your code acts as. A test can add more apps beside it, each a real app of its platform with its own credentials and endpoint, to test agents that work together; see [several apps](https://channelstack.dev/docs/guide/several-apps). There is one workspace, org or integration per fake, holding all of its apps, and the state lives in memory: a restart starts a fresh world. The fakes are channelstack's own implementation. They follow each platform's documentation, schemas and recorded traffic, and live runs against real sandboxes keep them honest. ## Three kinds of traffic Three flows meet at the server, and it helps to keep them apart: | Flow | What happens | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Test to server | The test calls the control API: "Ana says this in that channel". The server writes it into the fake | | Platform to app | The fake signs and delivers the event the real platform would send (`app_mention`, `issue_comment`, `AgentSessionEvent`), over HTTP or Slack's Socket Mode | | App to platform | The app answers through the provider API it already uses (`chat.postMessage`, `POST /repos/…/comments`, `agentActivityCreate`). The fake serves the call and records it | The server records all three in an event log per session. That log feeds the UI's inspector and `channelstack tail`; the matchers read the platform's state through the read methods instead (below). ## The control API Every client of channelstack uses the same plain-HTTP control API at `/_channelstack`: - the Vitest plugin and the pytest plugin, through the generated TypeScript and Python SDKs (there is a Rust SDK too); - the attach CLI (`channelstack slack say`, `show`, `deliveries`); - `channelstack mcp`, which gives a coding agent the CLI's commands as tools; - the UI in the browser. So anything you can click in the UI, a script can do, and a test can do the same thing a developer did by hand. The API listens on loopback only and needs a bearer token. The server writes the token to `~/.channelstack/server.json` with mode 0600, and the clients find it there on their own. The UI opens through a one-time login link instead, and can only read. The SDKs are generated from the server's routes, so they can't drift from what the server accepts. The matchers are not part of the server: they run in your test process and poll plain read methods (`thread.replies()`, `issue.comments()`) until a condition holds. That keeps assertion logic out of the server and lets each language use its own `expect`. ## Base-URL mode and proxy mode By default the app reaches the fakes because its SDK's base URL points at them (`SLACK_API_URL=https://slack.localhost/api/`). That's base-URL mode, and it needs no change beyond an option the SDK already has. Some apps hard-code `slack.com` or `api.github.com`; for those, `channelstack start --proxy` runs an HTTP proxy that sends the platforms' hosts (and `api.openai.com`) to the fakes and passes every other host through. See [proxy mode](https://channelstack.dev/docs/guide/proxy-mode). ## Sessions: scopes in one shared world Your app is configured once: one bot token and one base URL per platform. So there is only one fake Slack workspace, one GitHub org, one Linear workspace and one Notion workspace per server, and on email one Resend team, one Gmail mailbox and one Discord guild per app. The apps belong to that shared world too, not to a test, so an agent's credentials outlive each test. Tests don't get separate worlds. Each test gets a **session**, a scope inside the shared one. Tests run in parallel against one server. Each test gets its own session: it sees only the people, channels and deliveries it created, and everything goes away when it ends. The CLI, the UI and MCP share one long-lived session called `dev`. A session works like this: - **It owns what it creates.** People, channels, repos, issues and pages belong to the session that made them. Generated names (`test-k3f9`) never collide, so parallel tests don't see each other. - **It reads only its own events.** A session's event log holds the deliveries and API calls caused by its own resources. When the app posts into a channel the session owns, that call belongs to the session. A test's `slack.calls()` never shows another test's traffic. - **It cleans up after itself.** The Vitest and pytest plugins open a session before each test and close it after. Closing removes everything the test created. Three things reach past a session, and the rules for them are fixed: | What | Rule | | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | A name you choose (`createChannel({ name: "support" })`) | Unique per session. Two parallel tests can each have a `#support`; the app sees two channels with different ids. A second `#support` in the same session is refused with `name_taken` | | An id you choose (`createUser({ id: "U0ADMIN01" })`) | Unique in the whole world, because the app can't tell two `U0ADMIN01` apart. While one session holds it, another is refused with `invalid_argument` | | A global action (a fault, `slack.uninstallApp()`) | Applies to everyone until its session closes, then it's undone. Run these tests on their own | The CLI, the UI and MCP share one long-lived session called `dev`. People and channels you create by hand (`channelstack slack say --as ana --in "#support" "…"`) live there until the server stops. See [the dev loop](https://channelstack.dev/docs/guide/dev-loop). ## The transcript Every matcher reads the **transcript**: a resource reduced to what a person would read. Edits are applied, deleted messages are gone, stream chunks are joined, an ephemeral message is visible only to its recipient, and Block Kit text and button labels are pulled out of the blocks. ```ts title="TypeScript" const msg = await ana.say("what's 2 + 2?", { to: slack.app }); await msg.thread.latestReply({ from: "my-agent" }); const transcript = await msg.thread.transcript(); expect(transcript.toString()).toMatchSnapshot(); ``` ```python title="Python" msg = await ana.say("what's 2 + 2?", to=slack.app) await msg.thread.latest_reply(from_="my-agent") transcript = await msg.thread.transcript() # pytest has no snapshots of its own: compare with the conversation as a person reads it. assert str(transcript) == "Ana: what's 2 + 2?\n my-agent: 2 + 2 is 4." ``` ```rust title="Rust" let msg = ana.say("what's 2 + 2?").to(&slack.app()).await?; msg.thread().latest_reply().from("my-agent").await?; let transcript = msg.thread().transcript().await?; // No snapshots in Rust's test harness: compare with the conversation as a person reads it. assert_eq!( transcript["text"], "Ana: what's 2 + 2?\n my-agent: 2 + 2 is 4." ); ``` The UI shows the same view, so it can't show anything a matcher wouldn't see. Reading as a particular person (`transcript({ as: ana })`) includes what only that person can see. This is also why the matchers check behaviour and not wording. `toHaveRepliesFrom("my-agent", { count: 1 })` holds whatever the reply says, so the same test works with a real model and a fake one. When a check fails, its message lists what a person would see instead. ## Waiting instead of sleeping An app answers when it's ready, so every matcher waits. A positive check passes as soon as its condition holds. A negative or exact-count check can't pass early, so it waits until the app has gone quiet, and the server knows when that is: no stream open, no API call in flight, no delivery about to be retried. [Waiting and quiet](https://channelstack.dev/docs/guide/waiting-and-quiet) explains the rules. ## What channelstack doesn't do - **It doesn't start or wrap your app.** The app is a separate process that you run as usual. `channelstack env` prints the tokens, signing secrets and URLs it needs, and the server delivers to the URL you give it. - **It doesn't write your model's answers.** The fake OpenAI is realistic on the wire, never in content: it says what each test scripted, and it never judges an answer. An agent that doesn't talk to it keeps its own model, its framework's fake (the AI SDK's mock models in `ai/test`, LangChain's `FakeListChatModel`) or a real one, and the matchers work the same. - **It doesn't relay events in live mode.** Against real sandboxes, channelstack acts as people and reads the results back; the platform delivers to your app itself. Retries, bad signatures and other delivery chaos are fake only. See [live mode](https://channelstack.dev/docs/guide/live-mode). - **It doesn't keep state.** Everything is in memory. Restart the server and the world is empty again. # Connecting your app Source: https://channelstack.dev/docs/guide/connecting-your-agent This page gets your app talking to the fakes: start the server, give the app its environment, point its SDK at channelstack, and tell the server where to deliver events. Your app's code doesn't change beyond a base-URL option its SDK already has. ## Start the server ```bash npm i -D channelstack npm i -g portless npx channelstack ``` ``` channelstack 0.0.0 · in-memory Control https://channelstack.localhost/_channelstack echo https://echo.localhost slack https://slack.localhost github https://github.localhost linear https://linear.localhost notion https://notion.localhost resend https://resend.localhost google https://google.localhost discord https://discord.localhost openai https://openai.localhost UI https://channelstack.localhost/?login=… `channelstack env` prints tokens and URLs as .env lines ``` `npx channelstack` is short for `npx channelstack start`. It registers the `*.localhost` names with [portless](https://github.com/vercel-labs/portless), which serves them over HTTPS. The UI line is a one-time link that signs one browser in; `channelstack ui` prints a fresh one. `echo` is an internal driver channelstack uses to test itself; you can ignore it. `openai` is the [fake OpenAI](https://channelstack.dev/docs/platforms/openai), for your agent's model. The server keeps everything in memory. Stop it with Ctrl+C, and the next start begins with an empty world. ### Without portless If portless isn't installed, the server stops with `portless isn't installed. Install it (npm install -g portless) or start with --no-portless.` Without portless, everything is served over plain HTTP on one loopback port, with a path prefix per fake: ```bash npx channelstack start --no-portless --port 4500 ``` The fakes are then at `http://127.0.0.1:4500/slack`, `/github`, `/linear`, `/notion`, `/resend`, `/google` and `/discord`, the fake OpenAI at `/openai/v1`, and `channelstack env` prints those URLs instead. (`googleapis` keeps Gmail's paths at the root of whatever host it is given, so without portless Gmail's API is served at the server's root too, and `GOOGLE_API_URL` is `http://127.0.0.1:4500/`.) `--port` defaults to 4500 without portless; `--port 0` picks a free port. Plain HTTP on loopback needs no certificate, so this is also the simplest way around [TLS trust](#tls-trust-per-runtime) problems. ## Give the app its environment `channelstack env` asks the running server for the lines your app needs and prints them in `.env` format: ```bash npx channelstack env >> .env.local ``` ```ini title=".env.local" SLACK_API_URL=https://slack.localhost/api/ SLACK_BOT_TOKEN=xoxb-… SLACK_APP_TOKEN=xapp-… SLACK_SIGNING_SECRET=… GITHUB_API_URL=https://github.localhost GITHUB_APP_ID=… … ``` What it prints, per platform: | Platform | Variables | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Slack | `SLACK_API_URL` (ends in `/api/`), `SLACK_BOT_TOKEN` (`xoxb-…`), `SLACK_APP_TOKEN` (`xapp-…`, for Socket Mode), `SLACK_SIGNING_SECRET` | | GitHub | `GITHUB_API_URL`, `GITHUB_APP_ID`, `GITHUB_APP_SLUG` (`my-agent`), `GITHUB_INSTALLATION_ID`, `GITHUB_BOT_USER_ID`, `GITHUB_PRIVATE_KEY`, `GITHUB_WEBHOOK_SECRET` | | Linear | `LINEAR_API_URL` (ends in `/graphql`), `LINEAR_ACCESS_TOKEN` (`lin_oauth_…`), `LINEAR_WEBHOOK_SECRET`, `LINEAR_CLIENT_ID`, `LINEAR_CLIENT_SECRET` | | Notion | `NOTION_BASE_URL`, `NOTION_TOKEN` (`ntn_…`), `NOTION_VERIFICATION_TOKEN` | | Resend | `RESEND_BASE_URL`, `RESEND_API_KEY` (`re_…`), `RESEND_WEBHOOK_SECRET` (`whsec_…`), `RESEND_FROM` (`my-agent `, the address it sends from) | | Google | `GOOGLE_API_URL` (the root for `googleapis`), `GOOGLE_TOKEN_URL`, `GOOGLE_CERTS_URL`, `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` (`GOCSPX-…`), `GOOGLE_REFRESH_TOKEN` (`1//0…`), `GMAIL_ADDRESS`, `GOOGLE_PUBSUB_TOPIC`, `GOOGLE_PUSH_SERVICE_ACCOUNT`, `GOOGLE_PUSH_AUDIENCE` | | Discord | `DISCORD_API_URL` (discord.js's `rest.api`), `DISCORD_TOKEN`, `DISCORD_APPLICATION_ID`, `DISCORD_PUBLIC_KEY`, `DISCORD_GUILD_ID` | | The model | `OPENAI_BASE_URL` (ends in `/v1`), `OPENAI_API_KEY` (`sk-proj-…`), for the [fake OpenAI](https://channelstack.dev/docs/platforms/openai) | It also prints three `ECHO_*` lines for the internal driver. A platform that runs [live](https://channelstack.dev/docs/guide/live-mode) prints nothing: there, the app uses its own real configuration. `GITHUB_PRIVATE_KEY` is a PEM on one line, with `\n` for its line breaks, because an `.env` line is one line. Turn it back into a PEM in your app: `GITHUB_PRIVATE_KEY.replaceAll("\\n", "\n")`. Probot, Octokit's App auth and most deploy targets take the key this way. Write the app so it uses an API URL only when the variable is set. Then the same code talks to the fake in tests and to the real platform in production. ## Point each SDK at the fake Every platform SDK already has a base-URL option. These are the ones the [reference agents](https://github.com/christian-bromann/channelstack/tree/main/examples/agents) use: | SDK | Option | Variable | | --------------------------------------------------------------- | --------------------------------------------- | --------------------------------------------------- | | Bolt for JavaScript | `clientOptions: { slackApiUrl }` | `SLACK_API_URL` | | Bolt for Python, `slack_sdk` | `WebClient(base_url=…)` | `SLACK_API_URL` | | Octokit, `@octokit/rest` | `baseUrl` | `GITHUB_API_URL` | | Probot | `baseUrl` in `Probot.defaults(…)` | `GITHUB_API_URL` | | `@linear/sdk` | `apiUrl` | `LINEAR_API_URL` | | `@notionhq/client` | `baseUrl` | `NOTION_BASE_URL` | | `resend` | none: it reads the variable itself | `RESEND_BASE_URL` | | `googleapis` | `rootUrl` in `google.gmail({ … })` | `GOOGLE_API_URL` | | `google-auth-library` | `endpoints` in `new OAuth2Client(…)` | `GOOGLE_TOKEN_URL`, `GOOGLE_CERTS_URL` | | Chat SDK adapters (`@chat-adapter/slack`, `/github`, `/linear`) | `apiUrl`, or read from the environment | `SLACK_API_URL`, `GITHUB_API_URL`, `LINEAR_API_URL` | | discord.js | `rest.api` in `new Client({ rest: { api } })` | `DISCORD_API_URL` | | `openai`, `@ai-sdk/openai` | none: they read the variables themselves | `OPENAI_BASE_URL`, `OPENAI_API_KEY` | ### Slack with Bolt ```ts title="agent.ts" import { App } from "@slack/bolt"; const { SLACK_BOT_TOKEN, SLACK_SIGNING_SECRET, SLACK_API_URL } = process.env; const app = new App({ token: SLACK_BOT_TOKEN, signingSecret: SLACK_SIGNING_SECRET, ...(SLACK_API_URL ? { clientOptions: { slackApiUrl: SLACK_API_URL } } : {}), }); await app.start(3000); ``` In Python, give Bolt a `WebClient` with the base URL: ```python title="app.py" import os from slack_bolt import App from slack_sdk import WebClient client = WebClient( token=os.environ["SLACK_BOT_TOKEN"], base_url=os.environ.get("SLACK_API_URL", "https://slack.com/api/"), ) app = App(client=client, signing_secret=os.environ["SLACK_SIGNING_SECRET"]) ``` ### GitHub with Octokit or Probot ```ts title="agent.ts" import { createAppAuth } from "@octokit/auth-app"; import { Octokit } from "@octokit/rest"; const { GITHUB_APP_ID, GITHUB_PRIVATE_KEY, GITHUB_API_URL } = process.env; const privateKey = GITHUB_PRIVATE_KEY!.replaceAll("\\n", "\n"); const octokit = (installationId: number) => new Octokit({ authStrategy: createAppAuth, auth: { appId: GITHUB_APP_ID, privateKey, installationId }, ...(GITHUB_API_URL ? { baseUrl: GITHUB_API_URL } : {}), }); ``` With Probot, pass the same values to `Probot.defaults`: ```ts title="server.ts" import { Probot, Server } from "probot"; const { GITHUB_APP_ID, GITHUB_PRIVATE_KEY, GITHUB_WEBHOOK_SECRET, GITHUB_API_URL } = process.env; const server = new Server({ Probot: Probot.defaults({ appId: GITHUB_APP_ID, privateKey: GITHUB_PRIVATE_KEY!.replaceAll("\\n", "\n"), secret: GITHUB_WEBHOOK_SECRET, ...(GITHUB_API_URL ? { baseUrl: GITHUB_API_URL } : {}), }), port: 3000, webhookPath: "/api/github/webhooks", }); ``` The fake serves the API both at the root (like `api.github.com`) and at `/api/v3` (like GitHub Enterprise), because some SDKs assume the Enterprise layout once a host is set. ### Linear and Notion ```ts title="agent.ts" import { LinearClient } from "@linear/sdk"; import notionClient from "@notionhq/client"; // @notionhq/client is CommonJS: Node gives it to an ES module as its default export. const { Client } = notionClient; const { LINEAR_ACCESS_TOKEN, LINEAR_API_URL, NOTION_TOKEN, NOTION_BASE_URL } = process.env; const linear = new LinearClient({ accessToken: LINEAR_ACCESS_TOKEN, ...(LINEAR_API_URL ? { apiUrl: LINEAR_API_URL } : {}), }); const notion = new Client({ auth: NOTION_TOKEN, ...(NOTION_BASE_URL ? { baseUrl: NOTION_BASE_URL } : {}), }); ``` Verify incoming webhooks with the secrets `channelstack env` printed: `LINEAR_WEBHOOK_SECRET` (for `LinearWebhookClient` or your own check of `Linear-Signature`), and `NOTION_VERIFICATION_TOKEN` (for `verifyWebhookSignature` and `X-Notion-Signature`). ### Resend The `resend` SDK reads `RESEND_BASE_URL` on its own, so an agent on it needs no change: create the client with the key, and send from `RESEND_FROM`. ```ts title="agent.ts" import { Resend } from "resend"; const { RESEND_API_KEY, RESEND_WEBHOOK_SECRET, RESEND_FROM } = process.env; const resend = new Resend(RESEND_API_KEY); ``` Verify each webhook with `resend.webhooks.verify` and `RESEND_WEBHOOK_SECRET`: the fake signs the way Svix does, with `svix-id`, `svix-timestamp` and `svix-signature`. An `email.received` event carries the email's metadata only, so read the email with `resend.emails.receiving.get(id)`, and answer with `In-Reply-To` and `References` set ([Resend](https://channelstack.dev/docs/platforms/resend)). ### Google (Gmail) Give `OAuth2Client` the token endpoint and the certificates, and `googleapis` the root, per API: `googleapis` ignores `google.options({ rootUrl })`. ```ts title="agent.ts" import { OAuth2Client } from "google-auth-library"; import { google } from "googleapis"; const env = process.env; const auth = new OAuth2Client({ clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, endpoints: { ...(env.GOOGLE_TOKEN_URL ? { oauth2TokenUrl: env.GOOGLE_TOKEN_URL } : {}), ...(env.GOOGLE_CERTS_URL ? { oauth2FederatedSignonPemCertsUrl: env.GOOGLE_CERTS_URL } : {}), }, }); auth.setCredentials({ refresh_token: env.GOOGLE_REFRESH_TOKEN }); const gmail = google.gmail({ version: "v1", auth, ...(env.GOOGLE_API_URL ? { rootUrl: env.GOOGLE_API_URL } : {}) }); ``` Watch the inbox with `users.watch` and `GOOGLE_PUBSUB_TOPIC`, check each push's token with `auth.verifyIdToken({ idToken, audience: GOOGLE_PUSH_AUDIENCE })` and its `email` against `GOOGLE_PUSH_SERVICE_ACCOUNT`, and send with `requestBody: { raw, threadId }`: a media upload goes to Google's own host whatever `rootUrl` says ([Google](https://channelstack.dev/docs/platforms/google)). ### Discord with discord.js discord.js takes the REST API's base as `rest.api`; it finds the Gateway itself, from `GET /gateway/bot`, so the WebSocket goes to the fake too. Leave `rest.api` unset in production, where discord.js falls back to `https://discord.com/api`. ```ts title="agent.ts" import { Client, GatewayIntentBits, Partials } from "discord.js"; const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.DirectMessages], partials: [Partials.Channel], ...(process.env.DISCORD_API_URL ? { rest: { api: process.env.DISCORD_API_URL } } : {}), }); await client.login(process.env.DISCORD_TOKEN); ``` Register slash commands in `DISCORD_GUILD_ID` with `DISCORD_APPLICATION_ID`, and, for interactions over HTTP, check each request's `X-Signature-Ed25519` against `DISCORD_PUBLIC_KEY` with `verifyKey` from `discord-interactions`. discord.js's Gateway client doesn't go through `HTTPS_PROXY`, so a discord.js bot uses `rest.api`, not proxy mode ([Discord](https://channelstack.dev/docs/platforms/discord)). ### Chat SDK The Chat SDK's Slack, GitHub and Linear adapters read `SLACK_API_URL`, `GITHUB_API_URL` and `LINEAR_API_URL` from the environment on their own, or take an `apiUrl` option. With the lines from `channelstack env` in the app's environment, an app on the Chat SDK needs no change at all. ## Tell the server where the app listens The server delivers each platform's events to one URL, which it reads from `CHANNELSTACK__WEBHOOK_URL` when it starts: ```bash CHANNELSTACK_SLACK_WEBHOOK_URL=http://localhost:3000/slack/events \ CHANNELSTACK_GITHUB_WEBHOOK_URL=http://localhost:3001/api/github/webhooks \ CHANNELSTACK_LINEAR_WEBHOOK_URL=http://localhost:3002/webhooks/linear \ CHANNELSTACK_NOTION_WEBHOOK_URL=http://localhost:3003/webhooks/notion \ CHANNELSTACK_RESEND_WEBHOOK_URL=http://localhost:3004/webhooks/resend \ CHANNELSTACK_GOOGLE_WEBHOOK_URL=http://localhost:3005/webhooks/google \ npx channelstack ``` | Variable | What arrives there | | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `CHANNELSTACK_SLACK_WEBHOOK_URL` | Events API requests, interactivity (`block_actions`, `view_submission`, `view_closed`), shortcuts and slash commands. Bolt handles all of them at `/slack/events` | | `CHANNELSTACK_GITHUB_WEBHOOK_URL` | App webhooks, signed with `X-Hub-Signature-256` | | `CHANNELSTACK_LINEAR_WEBHOOK_URL` | Webhooks and `AgentSessionEvent`s, signed with `Linear-Signature` | | `CHANNELSTACK_NOTION_WEBHOOK_URL` | Integration webhooks, signed with `X-Notion-Signature` | | `CHANNELSTACK_RESEND_WEBHOOK_URL` | `email.received` for mail to the agent, and `email.sent`, `email.delivered` and what else became of the mail it sent, signed the Svix way (`svix-signature`) | | `CHANNELSTACK_GOOGLE_WEBHOOK_URL` | Pub/Sub pushes of Gmail's notifications, once the agent has called `users.watch`, each with an OIDC token for this URL in `Authorization` | Set only the ones your app uses. Any URL the server can reach works; a loopback URL is the simplest. The server reads these variables once, at start, so restart it to change one. Without a URL (and, for Slack, without a Socket Mode connection), a fake sends nothing. People can still act, but nothing reaches the app, and `msg.delivery` is `undefined`. If a test sees no reply at all, check this first. ## Slack in Socket Mode An app in Socket Mode connects out to Slack over a WebSocket and needs no URL at all. Leave `CHANNELSTACK_SLACK_WEBHOOK_URL` unset and give the app the app token: ```ts title="agent.ts" const app = new App({ token: process.env.SLACK_BOT_TOKEN, appToken: process.env.SLACK_APP_TOKEN, socketMode: true, ...(process.env.SLACK_API_URL ? { clientOptions: { slackApiUrl: process.env.SLACK_API_URL } } : {}), }); await app.start(); ``` The app calls `apps.connections.open` with its `xapp-…` token, as it does against Slack, and the fake answers with a WebSocket URL of its own (`wss://slack.localhost/link?…`). Events, interactivity and slash commands then arrive over that connection, wrapped in Socket Mode envelopes that the app acknowledges. A few things differ from HTTP delivery, as they do on Slack: - There is no signature to check: the connection is the app's own. The standard `slack.bad-signature` check passes without sending anything. - A retry carries `retry_attempt` and `retry_reason` in the envelope instead of headers. - `slack.socketConnections` tells a test how many connections the app had open when the test's `slack` fixture was made (a snapshot, not refreshed), and `slack.fault({ type: "drop_socket" })` drops them to test reconnecting. See [delivery and failures](https://channelstack.dev/docs/guide/delivery-and-failures#faults). ## TLS trust per runtime With portless, the fakes are served over HTTPS with a certificate from portless's local CA. `portless trust` adds that CA to the system trust store, but not every runtime reads the system store. If your app fails with a certificate error, set what its runtime needs: | Runtime | What to set in the app's environment | | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | | Node 24 and later | `NODE_USE_SYSTEM_CA=1`, so Node reads the system store | | Python with certifi (`requests`, `httpx`, `slack_sdk`) | `SSL_CERT_FILE` and `REQUESTS_CA_BUNDLE`, pointing at a bundle of certifi's roots plus portless's CA | | Go | Nothing on macOS (Go reads the keychain); `SSL_CERT_FILE` on Linux | | Anything else | Start the server with `--no-portless` and use plain HTTP on loopback | In base-URL mode, `channelstack env` doesn't print these: set them yourself. `portless doctor` checks portless's own setup. [Proxy mode](https://channelstack.dev/docs/guide/proxy-mode) is different: there, `channelstack env --proxy` prints the CA settings for channelstack's own proxy CA. ## Secrets The fake tokens and signing secrets are random. The server generates them once per install and keeps them in `~/.channelstack/secrets.json` (mode 0600), or under `CHANNELSTACK_HOME` if you set it. They stay the same across restarts, so the `.env.local` you wrote once keeps working. To replace them all: ```bash npx channelstack secrets rotate ``` Then restart the server and run `channelstack env` again, because the app's copy is now stale. None of these values works anywhere but on your channelstack server. Still, keep `.env.local` out of version control, like any `.env` file. The control API's own bearer token is a separate secret in `~/.channelstack/server.json`; `channelstack env` never prints it, so it never ends up in the app's environment. ## Check the connection With the server and the app running, post as a person and read what came back: ```bash npx channelstack slack say --as ana --in "#support" "@my-agent hi" npx channelstack show npx channelstack deliveries slack ``` `show` prints the latest conversation as a person would read it, and `deliveries` lists what the server sent the app and how the app answered each attempt. If the app answered, you're connected: go on to [writing tests](https://channelstack.dev/docs/guide/writing-tests). If not, [the dev loop](https://channelstack.dev/docs/guide/dev-loop) and [troubleshooting](https://channelstack.dev/docs/guide/troubleshooting) cover what to look at. # Writing tests Source: https://channelstack.dev/docs/guide/writing-tests This page shows how to write channelstack tests in Vitest: the plugin, the fixtures each test gets, how people act, how the app gets access, and how tests clean up. It assumes the server and your app are running and connected, as in [connecting your app](https://channelstack.dev/docs/guide/connecting-your-agent). ## Add the plugin ```bash npm i -D channelstack vitest ``` ```ts title="vitest.config.ts" import channelstack from "channelstack/vitest"; import { defineConfig } from "vitest/config"; export default defineConfig({ plugins: [channelstack()], }); ``` The plugin adds a global setup that finds the server, a setup file that gives each test its session and fixtures and registers the matchers on `expect`, and the types for both. You keep importing `test` and `expect` from `vitest`. | Option | Default | What it does | | ---------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `mode` | `"auto"` | `"attach"` fails when no server is running. `"start"` always starts a private one. `"auto"` attaches if it can, and starts one otherwise | | `server` | from `~/.channelstack/server.json` | The server to attach to. Also `CHANNELSTACK_URL`, with `CHANNELSTACK_TOKEN` | | `timeout` | `"10s"` | How long a matcher, `channelstack.quiet()` and every SDK wait (`waitForReply`, `latestReply`, `settled`, …) give up after. A project without its own `testTimeout` gets one above it: 30s, or three times `timeout` | | `quietFor` | `"750ms"` | How long the app must be quiet before a negative or exact-count matcher checks, or a `latest…` read reads | Your app is configured from the server you started yourself (`npx channelstack`), so attaching to that server is the usual setup. A server the plugin starts on its own has no app connected to it. In CI, `mode: "attach"` makes a missing server fail at once instead of later. The [plugin reference](https://channelstack.dev/docs/reference/vitest-plugin) lists every option. ## A first test ```ts title="TypeScript" import { expect, test } from "vitest"; test("a mention gets exactly one reply, in the thread", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); const channel = await slack.createChannel({ participants: [ana, slack.app] }); const msg = await ana.say("@my-agent summarize yesterday's incidents", { channel }); await expect(msg.thread).toHaveReplyFrom("my-agent", { text: /incident/i }); await expect(msg.thread).toHaveRepliesFrom(slack.app, { count: 1 }); await expect(channel).not.toHaveChannelMessageFrom("my-agent"); }); ``` ```python title="Python" import re from channelstack import SlackFixture from pytest_channelstack import expect async def test_a_mention_gets_exactly_one_reply_in_the_thread(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") channel = await slack.create_channel(participants=[ana, slack.app]) msg = await ana.say("@my-agent summarize yesterday's incidents", channel=channel) await expect(msg.thread).to_have_reply_from("my-agent", text=re.compile("incident", re.I)) await expect(msg.thread).to_have_replies_from(slack.app, count=1) await expect(channel).not_to_have_channel_message_from("my-agent") ``` ```rust title="Rust" let ana = slack.create_user().name("Ana").await?; let channel = slack .create_channel() .participants(vec![&ana as &dyn Handle, &slack.app()]) .await?; let msg = ana .say("@my-agent summarize yesterday's incidents") .channel(&channel) .await?; expect(&msg.thread()) .to_have_reply_from("my-agent") .text(Regex::new("(?i)incident")?) .await?; expect(&msg.thread()) .to_have_replies_from(&slack.app(), 1) .await?; expect(&channel) .not_to_have_channel_message_from("my-agent") .await?; ``` The test creates a person and a channel, has the person mention the app, and checks three things a person would notice: there is an answer, there is only one, and it's in the thread rather than in the channel. Each matcher waits for the app; nothing in the test sleeps. The Python version runs under [pytest](https://channelstack.dev/docs/guide/pytest); the Rust version opens its own session, since Rust's test harness has no fixtures ([SDKs](https://channelstack.dev/docs/reference/sdks)). The prose on this page names the TypeScript API. ## The fixtures Every test gets these fixtures from its context: | Fixture | What it is | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slack` | The fake Slack workspace: `createUser`, `createChannel`, the built-in `app`, `calls`, `deliveries`, `fault` | | `github` | The fake GitHub org: `createUser`, `createRepo`, the built-in `app` (a GitHub App) | | `linear` | The fake Linear workspace: `createUser`, `createTeam`, the built-in `app` | | `notion` | The fake Notion workspace: `createUser`, `createPage`, `createDatabase`, the built-in integration as `app` | | `resend` | The fake Resend team: `createUser` (a mailbox outside it), the built-in team's address as `app` | | `google` | The fake Gmail mailbox: `createUser` (a mailbox outside it), the agent's own mailbox as `app` | | `discord` | The fake guild: `createUser`, `createChannel`, the agent's bot as `app`, faults and `verifyEndpoint` | | `openai` | The fake OpenAI, your agent's model: `respond` (what the model answers), `calls`, `latestCall`, `waitForCall`, `toolCalls`, `rateLimit`. Not a platform: no people or `app`. See [OpenAI](https://channelstack.dev/docs/platforms/openai) | | `channelstack` | The server itself: `url`, `env()` (what `channelstack env` prints), `quiet()` (resolves when the app is quiet in this test's session), `reset()` | The fixtures are scoped to the test's own [session](https://channelstack.dev/docs/guide/how-it-works#sessions-scopes-in-one-shared-world), which opens before the test's hooks and closes after them, whether the test names a fixture or not. Two tests that run at the same moment never see each other's people, channels, deliveries or model scripts. Each fixture's `app` is the built-in app your code acts as on that platform, named `my-agent`. Matchers take it, or its name as a string, wherever they take an author: `toHaveReplyFrom(slack.app)` and `toHaveReplyFrom("my-agent")` mean the same. Every fixture also has `createApp({ name })` and `apps()`, for a test that needs another app beside `my-agent`: a second agent, or a bot to talk to. A name in a matcher then means that app too (`toHaveReplyFrom("coder")`). See [several apps](https://channelstack.dev/docs/guide/several-apps). ## People act, resources are read Every action is a method on the person who takes it. The content comes first, and where it happens is an option named after the resource: ```ts title="TypeScript" await ana.say("@my-agent deploy web", { channel }); await ben.click("Approve", { message: reply }); await cara.comment("@my-agent fix this", { issue: pr }); await dev.delegate(linear.app, { issue }); await eve.reply("thanks!", { discussion }); ``` ```python title="Python" await ana.say("@my-agent deploy web", channel=channel) await ben.click("Approve", message=reply) await cara.comment("@my-agent fix this", issue=pr) await dev.delegate(linear.app, issue=issue) await eve.reply("thanks!", discussion=discussion) ``` ```rust title="Rust" ana.say("@my-agent deploy web").channel(&channel).await?; ben.click("Approve").message(&reply).await?; cara.comment("@my-agent fix this").issue(&pr).await?; dev.delegate(&linear.app()).issue(&issue).await?; eve.reply("thanks!").discussion(&discussion).await?; ``` The people of each platform have that platform's actions, and only those: a Slack user can `say`, `reply`, `react`, `click` and `stop`; a GitHub user can `openIssue`, `openPullRequest`, `comment`, `review` and `push`; a Linear user can `createIssue`, `delegate`, `prompt` and `stop`; a Notion user can `comment`, `reply`, `edit` and `setProperty`; a Resend or Google person can `send`, `reply` and read their `inbox`; a Discord user can `say`, `reply`, `react`, `startThread`, `runCommand` and `click`. A Slack user has no `comment`, so mixing them up is a type error. The [platform pages](https://channelstack.dev/docs/platforms/slack) list every action. Every action resolves to what it created, so the next step needs no lookup. `say` gives you the message, with its `thread`, its `conversation` and the `delivery` it caused; `comment` on Linear gives you the comment and the agent `session` it opened. Text is rich: `@name` becomes a real mention of that person or app on the platform (`<@U…>` in Slack, `@login` on GitHub, a mention node in Linear and Notion). Write `@@` for a literal `@`. Actions with no person behind them live on the fixture or the object they concern: `slack.createChannel(…)`, `repo.installApp(github.app)`, `msg.delivery.retry()`, `modal.submit(…)`. ## Give the app access explicitly Nothing grants your app access behind your back. Each platform's real rule applies, and you state the access in the test: | Platform | The platform's rule | In a test | | -------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | Slack | A bot gets events from, and can post in, only the channels it's a member of (`not_in_channel` otherwise) | `createChannel({ participants: [ana, slack.app] })`, or later `ana.invite(slack.app, { channel })` | | GitHub | An App gets webhooks only for repositories it's installed on | `createRepo({ apps: [github.app] })`, or later `repo.installApp(github.app)` | | Notion | An integration sees only pages connected to it, and their children | `createPage({ connections: [notion.app] })`, or later `ana.connect(notion.app, { page })` | | Linear | An app is installed for the whole workspace | Nothing to do | | Resend | A team gets only the mail sent to its own address | `ana.send({ to: [resend.app], … })`; email between people never reaches it | | Google | A mailbox gets only the mail sent to it, and pushes only once the agent watches it | `ana.send({ to: [google.app], … })`; the agent calls `users.watch` itself | | Discord | Only the participants see a channel; the bot hears it only with `discord.app` among them | `discord.createChannel({ participants: [ana, discord.app] })`, or `ana.invite(discord.app, { channel })` | Leaving the app out is how you test the uninvited case: ```ts title="TypeScript" test("a channel the app isn't in stays silent until it's invited", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana", admin: true }); const channel = await slack.createChannel({ participants: [ana] }); const first = await ana.say("@my-agent are you here?", { channel }); await expect(first.thread).not.toHaveReplyFrom("my-agent"); await ana.invite(slack.app, { channel }); const second = await ana.say("@my-agent now?", { channel }); await expect(second.thread).toHaveReplyFrom("my-agent"); }); ``` ```python title="Python" async def test_a_channel_the_app_isnt_in_stays_silent_until_its_invited(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana", admin=True) channel = await slack.create_channel(participants=[ana]) first = await ana.say("@my-agent are you here?", channel=channel) await expect(first.thread).not_to_have_reply_from("my-agent") await ana.invite(slack.app, channel=channel) second = await ana.say("@my-agent now?", channel=channel) await expect(second.thread).to_have_reply_from("my-agent") ``` ```rust title="Rust" let ana = slack.create_user().name("Ana").admin(true).await?; let channel = slack .create_channel() .participants(vec![&ana as &dyn Handle]) .await?; let first = ana.say("@my-agent are you here?").channel(&channel).await?; expect(&first.thread()) .not_to_have_reply_from("my-agent") .await?; ana.invite(&slack.app()).channel(&channel).await?; let second = ana.say("@my-agent now?").channel(&channel).await?; expect(&second.thread()) .to_have_reply_from("my-agent") .await?; ``` On GitHub, Notion, Resend, Google and Discord, an action that reaches no app causes no delivery, so `comment.delivery` is `undefined` there. ## Read what happened Resources are only read and waited on. For a check, use a matcher; when you need a value to work with, read it: ```ts title="TypeScript" const msg = await ana.say("@my-agent what's the status of the web deploy?", { channel }); await msg.thread.waitForReply({ from: "my-agent" }); await ana.reply("and the API?", { thread: msg }); const answer = await msg.thread.waitForReply({ from: "my-agent" }); expect(answer.text).toMatch(/api/i); ``` ```python title="Python" msg = await ana.say("@my-agent what's the status of the web deploy?", channel=channel) await msg.thread.wait_for_reply(from_="my-agent") await ana.reply("and the API?", thread=msg) answer = await msg.thread.wait_for_reply(from_="my-agent") assert re.search("api", answer.text, re.I) ``` ```rust title="Rust" let msg = ana .say("@my-agent what's the status of the web deploy?") .channel(&channel) .await?; msg.thread().wait_for_reply().from("my-agent").await?; ana.reply("and the API?").thread(&msg).await?; let answer = msg.thread().wait_for_reply().from("my-agent").await?; assert!(Regex::new("(?i)api")?.is_match(&answer.text())); ``` | To get | Use | | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | The next new message from someone | `thread.waitForReply({ from })`, `conversation.waitForMessage({ from })`, `issue.waitForComment({ from })`, `discussion.waitForComment({ from })`, `session.waitForActivity({ type })` | | The latest one, once the app is quiet | `thread.latestReply({ from })`, `issue.latestComment({ from })`, `discussion.latestComment({ from })` | | Everything so far | `thread.replies()`, `conversation.messages()`, `issue.comments()`, `session.activities()`, `page.markdown()` | | What a person would read | `transcript()`, with `toString()` for snapshots | | What the app called | `slack.calls({ operation, error })`, `slack.waitForCall({ operation })` | | What the server sent the app | `msg.delivery`, `github.deliveries({ type, resource })` | [Waiting and quiet](https://channelstack.dev/docs/guide/waiting-and-quiet) explains how the `waitFor…` and `latest…` methods differ, and the API reference ([Slack](https://channelstack.dev/docs/reference/api/slack), [GitHub](https://channelstack.dev/docs/reference/api/github), [Linear](https://channelstack.dev/docs/reference/api/linear), [Notion](https://channelstack.dev/docs/reference/api/notion), [Resend](https://channelstack.dev/docs/reference/api/resend), [Google](https://channelstack.dev/docs/reference/api/google), [Discord](https://channelstack.dev/docs/reference/api/discord), [OpenAI](https://channelstack.dev/docs/reference/api/openai)) lists every read. ## Shared people with `test.extend` People and places you use in many tests belong in a fixtures file of your own (`test/fixtures.ts`, which the tests import `test` from). That's plain Vitest `test.extend`, built on channelstack's fixtures; in pytest it's fixtures in `conftest.py`, and in Rust, helper functions: ```ts title="TypeScript" import type { SlackConversation, SlackUser } from "channelstack"; import { expect, test as base } from "vitest"; // In a project, this goes in test/fixtures.ts, exported, and the tests import `test` from there. const test = base.extend<{ ana: SlackUser; ben: SlackUser; support: SlackConversation }>({ ana: async ({ slack }, use) => use(await slack.createUser({ name: "Ana" })), ben: async ({ slack }, use) => use(await slack.createUser({ name: "Ben", admin: true })), support: async ({ slack, ana, ben }, use) => use(await slack.createChannel({ name: "support", participants: [ana, ben, slack.app] })), }); test("an admin and a regular member see the same answer", async ({ support, ana, ben }) => { const question = await ana.say("@my-agent who's on call?", { channel: support }); await ben.reply("+1, also need this", { thread: question }); await expect(question.thread).toHaveRepliesFrom("my-agent", { count: 1 }); }); ``` ```python title="Python" import pytest_asyncio from channelstack import SlackConversation, SlackFixture, SlackUser from pytest_channelstack import expect # In a project, these fixtures go in conftest.py, where every test file finds them. @pytest_asyncio.fixture(loop_scope="session") async def ana(slack: SlackFixture) -> SlackUser: return await slack.create_user(name="Ana") @pytest_asyncio.fixture(loop_scope="session") async def ben(slack: SlackFixture) -> SlackUser: return await slack.create_user(name="Ben", admin=True) @pytest_asyncio.fixture(loop_scope="session") async def support(slack: SlackFixture, ana: SlackUser, ben: SlackUser) -> SlackConversation: return await slack.create_channel(name="support", participants=[ana, ben, slack.app]) async def test_an_admin_and_a_regular_member_see_the_same_answer( support: SlackConversation, ana: SlackUser, ben: SlackUser ) -> None: question = await ana.say("@my-agent who's on call?", channel=support) await ben.reply("+1, also need this", thread=question) await expect(question.thread).to_have_replies_from("my-agent", count=1) ``` ```rust title="Rust" // Rust has no test.extend: shared people and places are helpers each test calls. async fn ana(slack: &SlackFixture) -> Result { slack.create_user().name("Ana").await } async fn ben(slack: &SlackFixture) -> Result { slack.create_user().name("Ben").admin(true).await } async fn support( slack: &SlackFixture, ana: &SlackUser, ben: &SlackUser, ) -> Result { slack .create_channel() .name("support") .participants(vec![ana as &dyn Handle, ben, &slack.app()]) .await } #[tokio::test] #[ignore = "needs a running agent"] async fn an_admin_and_a_regular_member_see_the_same_answer() -> Result<()> { let session = fixtures::session().await?; let slack = session.slack().await?; let (ana, ben) = (ana(&slack).await?, ben(&slack).await?); let support = support(&slack, &ana, &ben).await?; let question = ana .say("@my-agent who's on call?") .channel(&support) .await?; ben.reply("+1, also need this").thread(&question).await?; expect(&question.thread()) .to_have_replies_from("my-agent", 1) .await?; session.close().await } ``` Each test still gets a fresh Ana, Ben and `#support`, because Vitest creates fixtures per test. The name `support` is unique per session, so parallel tests can all have their own `#support`. Fixtures compose: `support` depends on `ana` and `ben`. People are never declared in a config file. Every test states the world it needs, and nothing is shared between tests by accident. ## Fixed ids Generated ids are realistic and unique. When your app allowlists people by id, fix one: ```ts title="TypeScript" test("allowlisted people by fixed id", async ({ slack }) => { const admin = await slack.createUser({ name: "Cara", id: "U0ADMIN01" }); const stranger = await slack.createUser({ name: "Dev" }); const channel = await slack.createChannel({ participants: [admin, stranger, slack.app] }); const allowed = await admin.say("@my-agent rotate the API keys", { channel }); const refused = await stranger.say("@my-agent rotate the API keys", { channel }); await expect(allowed.thread).toHaveReplyFrom("my-agent", { text: /rotating/i }); await expect(refused.thread).toHaveReplyFrom("my-agent", { text: /not allowed/i }); }); ``` ```python title="Python" async def test_allowlisted_people_by_fixed_id(slack: SlackFixture) -> None: admin = await slack.create_user(name="Cara", id="U0ADMIN01") stranger = await slack.create_user(name="Dev") channel = await slack.create_channel(participants=[admin, stranger, slack.app]) allowed = await admin.say("@my-agent rotate the API keys", channel=channel) refused = await stranger.say("@my-agent rotate the API keys", channel=channel) await expect(allowed.thread).to_have_reply_from("my-agent", text=re.compile("rotating", re.I)) await expect(refused.thread).to_have_reply_from("my-agent", text=re.compile("not allowed", re.I)) ``` ```rust title="Rust" let admin = slack.create_user().name("Cara").id("U0ADMIN01").await?; let stranger = slack.create_user().name("Dev").await?; let channel = slack .create_channel() .participants(vec![&admin as &dyn Handle, &stranger, &slack.app()]) .await?; let allowed = admin .say("@my-agent rotate the API keys") .channel(&channel) .await?; let refused = stranger .say("@my-agent rotate the API keys") .channel(&channel) .await?; expect(&allowed.thread()) .to_have_reply_from("my-agent") .text(Regex::new("(?i)rotating")?) .await?; expect(&refused.thread()) .to_have_reply_from("my-agent") .text(Regex::new("(?i)not allowed")?) .await?; ``` GitHub takes a numeric `id`, Linear and Notion take a UUID, and Discord a snowflake. The id must have the platform's format. A Resend or Google person's id is their address, so fix one with `address`. A fixed id is unique in the whole world, not only in the test, because the app can't tell two `U0ADMIN01` apart. While one session holds it, another session that asks for it is refused with `invalid_argument`, and the id is free again when the first session closes. Tests that fix the same id must not run at the same time. ## Files and fixture directories A GitHub repository can start from a directory of files, and a Notion page from a Markdown file. Relative paths start from the test file, like an import. In Rust, which can't know where the test file is, they start from the working directory, which `cargo test` sets to the crate's directory (`channelstack::runtime::files::set_files_root` changes that): ```ts title="TypeScript" const repo = await github.createRepo({ files: "./fixtures/web", collaborators: [ana], apps: [github.app], }); const pr = await ana.openPullRequest( { from: "fix-login", title: "Fix login redirect", changes: { "src/login.ts": "export const redirect = '/home';\n" }, }, { repo }, ); const spec = await notion.createPage({ title: "Spec", content: { path: "./fixtures/spec.md" }, connections: [notion.app], }); ``` ```python title="Python" repo = await github.create_repo( files="./fixtures/web", collaborators=[ana], apps=[github.app], ) pr = await ana.open_pull_request( { "from": "fix-login", "title": "Fix login redirect", "changes": {"src/login.ts": "export const redirect = '/home';\n"}, }, repo=repo, ) spec = await notion.create_page( title="Spec", content={"path": "./fixtures/spec.md"}, connections=[notion.app], ) ``` ```rust title="Rust" let repo = github .create_repo() .files("./fixtures/web") .collaborators(vec![&ana as &dyn Handle]) .apps(vec![&github.app()]) .await?; let pr = ana .open_pull_request(json!({ "from": "fix-login", "title": "Fix login redirect", "changes": { "src/login.ts": "export const redirect = '/home';\n" }, })) .repo(&repo) .await?; let spec = notion .create_page() .title("Spec") .content(json!({ "path": "./fixtures/spec.md" })) .connections(vec![¬ion.app()]) .await?; ``` A Slack person shares files with a message the same way: `ana.say("here's the log", { channel, files: [{ path: "./fixtures/crash.log" }] })`, and the agent reads each from its `url_private` with the bot token. `files` takes a directory path or a list of files. Each file is either inline, `{ name, content }`, or on disk, `{ path }`. `changes` on a pull request or a push maps paths to new contents, and `null` deletes a file. ## Cleanup You don't clean up. When a test ends, the plugin closes its session, and closing removes everything the test created: people, channels, repositories, issues, pages. A fault the test injected is undone with it, and an app the test uninstalled is installed again. Cleanup never fails a test. Inside a test, `await using` ends something early. A fault, for example, lasts until the end of its scope: ```ts title="TypeScript" test("still answers when Slack refuses a message as too long", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); const channel = await slack.createChannel({ participants: [ana, slack.app] }); await using _fault = await slack.fault({ type: "error", operation: "chat.postMessage", error: "msg_too_long", times: 1, }); const msg = await ana.say("@my-agent hello", { channel }); await expect(msg.thread).toHaveRepliesFrom("my-agent", { count: 1 }); }); ``` ```python title="Python" async def test_still_answers_when_slack_refuses_a_message_as_too_long(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") channel = await slack.create_channel(participants=[ana, slack.app]) async with await slack.fault(type="error", operation="chat.postMessage", error="msg_too_long", times=1): msg = await ana.say("@my-agent hello", channel=channel) await expect(msg.thread).to_have_replies_from("my-agent", count=1) ``` ```rust title="Rust" let ana = slack.create_user().name("Ana").await?; let channel = slack .create_channel() .participants(vec![&ana as &dyn Handle, &slack.app()]) .await?; let fault = slack .fault() .r#type("error") .operation("chat.postMessage") .error("msg_too_long") .times(1) .await?; let msg = ana.say("@my-agent hello").channel(&channel).await?; expect(&msg.thread()) .to_have_replies_from("my-agent", 1) .await?; // Rust has no async drop: undo the fault where its scope ends. fault.undo().await?; ``` Outside Vitest, in a script or a `beforeAll` that needs its own scope, connect to the server and open a session yourself. Both are disposable: ```ts title="TypeScript" import { connect } from "channelstack/client"; await using client = await connect({ mode: "attach" }); await using session = await client.openSession(); const slack = await session.slack(); const ana = await slack.createUser({ name: "Ana" }); const msg = await ana.say("hi", { to: slack.app }); const reply = await msg.thread.waitForReply({ from: "my-agent" }); console.log(reply.text); // The session closes here, and removes Ana and the DM. ``` ```python title="Python" import asyncio from channelstack import connect async def main() -> None: async with await connect(mode="attach") as client: async with await client.open_session() as session: slack = await session.slack() ana = await slack.create_user(name="Ana") msg = await ana.say("hi", to=slack.app) reply = await msg.thread.wait_for_reply(from_="my-agent") print(reply.text) # The session closes here, and removes Ana and the DM. if __name__ == "__main__": asyncio.run(main()) ``` ```rust title="Rust" use channelstack::{Mode, connect}; #[tokio::main] async fn main() -> channelstack::Result<()> { let client = connect(Mode::Attach).await?; let session = client.open_session().send().await?; let slack = session.slack().await?; let ana = slack.create_user().name("Ana").await?; let msg = ana.say("hi").to(&slack.app()).await?; let reply = msg.thread().wait_for_reply().from("my-agent").await?; println!("{}", reply.text()); // Closing the session removes Ana and the DM. session.close().await?; client.close().await; Ok(()) } ``` `await using` needs TypeScript 5.2 or later with the `esnext.disposable` lib, or a runtime that supports it natively. Avoid `channelstack.reset()` in tests. It drops the whole world, including every other test's session, so it breaks a parallel suite. Fresh resources per test do the same job without the side effects. # Waiting and quiet Source: https://channelstack.dev/docs/guide/waiting-and-quiet This page explains how channelstack's matchers wait for an app, and why a negative check takes at least 750 ms. Read it when a check is slower than you expected, or passes when you think it shouldn't. ## Why matchers wait An app answers when it's ready. Between a person's message and the app's reply there is a signed delivery, the app's own work (for an agent, often a model call), and one or more API calls back. A test that reads the thread right after `say` sees nothing, and a test that sleeps for a fixed time is either slow or flaky. So every matcher waits, the way Playwright's web-first assertions do. A test never needs `sleep`: ```ts title="TypeScript" const msg = await ana.say("@my-agent summarize yesterday's incidents", { channel }); await expect(msg.thread).toHaveReplyFrom("my-agent"); // waits for a reply await expect(msg.thread).toHaveRepliesFrom("my-agent", { count: 1 }); // waits for quiet, then counts await expect(channel).not.toHaveChannelMessageFrom("my-agent"); // waits for quiet, then checks ``` ```python title="Python" msg = await ana.say("@my-agent summarize yesterday's incidents", channel=channel) await expect(msg.thread).to_have_reply_from("my-agent") # waits for a reply await expect(msg.thread).to_have_replies_from("my-agent", count=1) # waits for quiet, then counts await expect(channel).not_to_have_channel_message_from("my-agent") # waits for quiet, then checks ``` ```rust title="Rust" let msg = ana .say("@my-agent summarize yesterday's incidents") .channel(&channel) .await?; // waits for a reply expect(&msg.thread()).to_have_reply_from("my-agent").await?; // waits for quiet, then counts expect(&msg.thread()) .to_have_replies_from("my-agent", 1) .await?; // waits for quiet, then checks expect(&channel) .not_to_have_channel_message_from("my-agent") .await?; ``` The three lines wait in two different ways, and the difference is the subject of this page. ## Positive, negative and exact-count checks A **positive** check asks whether something has happened. It polls the read method behind it (`thread.replies()` for `toHaveReplyFrom`) and passes as soon as the condition holds. If the condition never holds, it fails after the timeout, 10 seconds by default. A **negative** check asks whether something has *not* happened. Polling can't answer that: "no reply yet" is true right up to the moment the reply arrives. The only honest answer is "no reply, and the app is done". So a negative check waits until the app is quiet, then checks once. An **exact-count** check has the same problem. "Exactly one reply" is true after the first reply and false after a duplicate that arrives a second later, which is exactly the bug a retry causes. So exact-count checks also wait for quiet and check once. | Kind | Examples | Waits for | Then | | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | -------------------------- | | Positive | `toHaveReplyFrom`, `toHaveCommentFrom`, `toHaveActivity`, `toHaveBlock`, `toBeAccepted` | The condition | Passes the moment it holds | | Negative | `.not.toHaveReplyFrom`, `.not.toHaveChannelMessageFrom`, any `.not.…` | The app to be quiet | Checks once | | Exact count | `toHaveRepliesFrom({ count })`, `toHaveCommentsFrom({ count })`, `toContainText(text, { count })`, `toHaveReceivedCall(op, { times })`, `toBeRetried({ times })` | The app to be quiet | Checks once | Positive checks are fast when the app is fast. Negative and exact-count checks always take at least the quiet window, because that's what it costs to know nothing more is coming. ## The quiet window 1. The check starts watching. The app is still busy: a delivery is in flight, then its API calls, then a stream. 2. Once nothing is open, the quiet window starts. Anything the app does now restarts it. 3. After 750 ms of quiet, watched from start to end, the check reads the thread once. The server knows what the app is doing, because every delivery and every API call goes through it. A session counts as **busy** while any of these is true: - **A provider API call is in flight.** The app called `chat.postMessage` and the fake hasn't answered yet. A call isn't tied to a session until it finishes, so a call in flight keeps every session busy. - **A delivery is in flight, or about to be retried.** The fake is waiting for the app to acknowledge an event, or the platform's next retry is due within 5 seconds. - **A Gmail push is held.** Gmail pushes at most once a second; a change within the second is pushed when it's over, and the session is busy until then. - **The app was told to come back.** After a rate limit (a 429 with `Retry-After`), the session stays busy until the app calls that method again, or until `Retry-After` plus 3 seconds of grace has passed. Slack's own client adds 1 to 2 seconds of backoff, so the grace covers it. - **Something the app started is still open.** Each platform says what that means: a Slack stream the app started and hasn't stopped, a GitHub check run that hasn't completed, a Linear agent session still `pending`, `active` or `stopping`, a Notion `page.content_updated` event the platform is still batching, a Discord interaction the app deferred and hasn't answered yet. On Resend, nothing stays open: an email is sent or it isn't. Once nothing is busy, the quiet window starts. Anything the app does restarts it. When the session has been quiet for `quietFor`, 750 ms by default, the check reads once and passes or fails. Slack's later retries, a minute and five minutes after a failed delivery, don't count as busy. Otherwise one unacknowledged event would hold every negative check in the session for six minutes. The retries still happen; a test that wants one now asks for it with `delivery.retry()`. ## Watched from start to end A negative check doesn't only need a quiet session. It needs to have **watched** the session be quiet for the whole window ([decision 0009](https://github.com/christian-bromann/channelstack/blob/main/docs/decisions/0009-quiet-means-watched.md)). The reason is that a thinking agent makes no sound. Suppose an agent acknowledged a delivery and is now waiting for its model. Nothing is in flight, so the session has been quiet for a while. A check that only asked "has it been quiet for 750 ms?" would pass at once, and the reply that arrives 500 ms later would go unseen. So the window counts from the moment the check starts at the earliest, and anything that arrives while the check is watching counts. The cost is that every negative and exact-count check takes at least `quietFor`, even when the session went quiet long before. A suite with many negative checks pays it per check. If that adds up, lower `quietFor` where your app is reliably quick, rather than dropping the checks. Read methods that need quiet, such as `thread.latestReply()`, don't watch for the whole window. They wait for at least one match and for the session to be quiet, and then return: something has already happened, and the question is only whether more of it is on the way. ## "Still open:" in failures When a check fails, or a wait gives up, the message says what was expected, what was there instead, and what the app left open: ``` Expected the thread to be idle, it is streaming Still open: a stream my-agent started and never stopped: "Thinking…" ``` ``` Timed out after 10000ms waiting for the agent to be quiet for 750ms. Still open: an agent session on ENG-12 that is still active ``` The first is a positive check that failed after its timeout. The second is a negative or exact-count check whose session never went quiet, so it never got to check. The "Still open" line is often the bug itself. An agent that starts a stream and crashes before stopping it leaves the person looking at "Thinking…" forever. A Linear agent that never ends its turn leaves the session `active`. A GitHub App that creates a check run and never completes it leaves a pull request waiting. Without the line, the test would only say it timed out. Each platform describes its own open work: | Platform | Open work | | -------- | ---------------------------------------------------------------------------- | | Slack | `a stream my-agent started and never stopped: "…"` | | GitHub | `a check run "my-agent" on 1a2b3c4 that never completed` | | Linear | `an agent session on ENG-12 that is still active` (or `pending`, `stopping`) | | Notion | `a page.content_updated for "Roadmap" that Notion is still batching` | ## Timeouts and `quietFor` Both values have defaults per run, and every matcher and wait takes its own: ```ts title="vitest.config.ts" export default defineConfig({ plugins: [channelstack({ timeout: "20s", quietFor: "1s" })], }); ``` ```ts title="TypeScript" await expect(issue).toHaveCommentsFrom(github.app, { count: 1, quietFor: "2s" }); await expect(msg.thread).toHaveReplyFrom("my-agent", { timeout: "30s" }); ``` ```python title="Python" await expect(issue).to_have_comments_from(github.app, count=1, quiet_for="2s") await expect(msg.thread).to_have_reply_from("my-agent", timeout="30s") ``` ```rust title="Rust" expect(&issue) .to_have_comments_from(&github.app(), 1) .quiet_for("2s") .await?; expect(&msg.thread()) .to_have_reply_from("my-agent") .timeout("30s") .await?; ``` | Setting | Default | Meaning | | ---------- | --------- | -------------------------------------------------------------------------------------------------------------------------------- | | `timeout` | `"10s"` | How long a positive check polls before it fails, and how long a negative or exact-count check waits for quiet before it gives up | | `quietFor` | `"750ms"` | How long the session must be quiet, watched, before a negative or exact-count check reads | Durations are milliseconds as a number, or a string: `"250ms"`, `"3s"`, `"1m"`. In pytest, the run's defaults are the `channelstack_timeout` and `channelstack_quiet_for` ini settings, and each check takes `timeout=` and `quiet_for=` ([pytest](https://channelstack.dev/docs/guide/pytest)). Raise `quietFor` when your app pauses between steps longer than 750 ms without anything open, for example a model call between two messages that it makes after acknowledging the event. A pause like that looks like quiet, and a negative check can end inside it. GitHub apps that comment, then label, then comment again often need `quietFor: "2s"`. Raise `timeout` for slow work, and for live runs, where real platforms take seconds to deliver. The test runner's own timeout has to stay above the longest wait in the test. The Vitest plugin sees to that: a project that sets no `testTimeout` gets 30 seconds, or three times `timeout` if that's longer, instead of Vitest's 5. A project's own `testTimeout` always wins, so if you set one, keep it above your waits. ## `waitFor…` and `latest…` Matchers check. When a test needs the value, to read its text or act on it, it uses a read method that waits. There are two kinds: ```ts title="TypeScript" // The next new reply from the agent: returns as soon as one arrives. const answer = await msg.thread.waitForReply({ from: "my-agent" }); // The agent's last reply, once it's done: waits for at least one, then for quiet. const ask = await msg.thread.latestReply({ from: "my-agent" }); await ben.click("Approve", { message: ask }); ``` ```python title="Python" # The next new reply from the agent: returns as soon as one arrives. answer = await msg.thread.wait_for_reply(from_="my-agent") # The agent's last reply, once it's done: waits for at least one, then for quiet. ask = await msg.thread.latest_reply(from_="my-agent") await ben.click("Approve", message=ask) ``` ```rust title="Rust" // The next new reply from the agent: returns as soon as one arrives. let answer = msg.thread().wait_for_reply().from("my-agent").await?; // The agent's last reply, once it's done: waits for at least one, then for quiet. let ask = msg.thread().latest_reply().from("my-agent").await?; ben.click("Approve").message(&ask).await?; ``` | Method | Returns | Use it when | | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `waitFor…` (`waitForReply`, `waitForMessage`, `waitForComment`, `waitForActivity`, `waitForModal`, `waitForCall`) | The next new item that matches, after the last one this handle returned | You expect one more thing, and want it the moment it arrives. A second call waits for the one after | | `latest…` (`latestReply`, `latestComment`) | The last item that matches, once the session is quiet | The app may write several messages, and you want the final one: the one with the button, the finished answer | | `session.waitForState(states)`, `stream.ended()`, `delivery.settled()` | The object, once it reaches one of the given states | You want a state, not a message | `waitFor…` keeps its place per handle. `waitForCall` keeps one per filter too, so two `waitForCall` waits with different operations each find their own call, even if both calls were already there. The others keep one place per handle, whatever their `from`, `body`, `title` or `type`: a `waitForReply({ from: ana })` after a `waitForReply({ from: app })` looks only past the reply the first one returned. Each of these takes `timeout`, and `latest…` takes `quietFor` too. A wait that gives up throws with what it was waiting for, and with the "Still open" line when there is one. # Delivery and failures Source: https://channelstack.dev/docs/guide/delivery-and-failures This page shows how to test the parts of a platform apps most often get wrong: retried and redelivered events, forged requests, rate limits, dropped connections and an uninstall. Everything here works against the fakes only. In [live mode](https://channelstack.dev/docs/guide/live-mode) an action has no delivery to test, so these tests need a guard to skip there: see [Fake only](#fake-only). ## What the fakes send Each fake delivers events the way its platform does: signed over the exact bytes it sends, within the platform's ack window, and retried on the platform's schedule. | Platform | Signature | Replay protection | Ack window | Retries | Same event, again | | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | | Slack | `X-Slack-Signature: v0=…`, an HMAC-SHA256 of `v0::` with the signing secret | `X-Slack-Request-Timestamp`; receivers refuse one more than 5 minutes old | 3 s | Right after a failed attempt, then after 1 and 5 minutes, with `X-Slack-Retry-Num` and `X-Slack-Retry-Reason`. An answer with `X-Slack-No-Retry: 1` ends them | Same `event_id` | | GitHub | `X-Hub-Signature-256: sha256=…` with the webhook secret, and the older `X-Hub-Signature` | None | 10 s | None; redelivery comes from the App's delivery log | Same `X-GitHub-Delivery` GUID | | Linear | `Linear-Signature`, a hex HMAC-SHA256 of the body | `webhookTimestamp` in the body; receivers refuse one more than a minute old | 5 s | After 1 minute, 1 hour and 6 hours, stamped and signed again | Same `Linear-Delivery` id | | Notion | `X-Notion-Signature: sha256=…` with the verification token | None | 5 s | Up to 8 times over about a day, with `attempt_number` in the body | Same event id | | Resend | Svix's: `svix-signature: v1,…`, a base64 HMAC-SHA256 of `..` with the `whsec_` secret | `svix-timestamp`; receivers refuse one more than 5 minutes old | 15 s | After 5 seconds, 5 and 30 minutes, 2, 5, 10 and 10 hours, signed again each time | Same `svix-id` | | Google | `Authorization: Bearer `, RS256, from Pub/Sub's push service account, for the push endpoint as audience; checked with `verifyIdToken` against `GOOGLE_CERTS_URL` | The token's `exp`: an hour after it was issued, with 5 minutes' skew | 10 s | Pub/Sub's push backoff, from 100 ms up to a minute. Gmail pushes at most once a second per mailbox ([Google](https://channelstack.dev/docs/platforms/google#one-push-a-second)) | Same Pub/Sub message id | Over Slack's Socket Mode there is no signature, because the connection is the app's own, and a retry carries `retry_attempt` and `retry_reason` in the envelope. ## Deliveries in a test An action that reaches the app gives you the delivery it caused: ```ts title="TypeScript" const msg = await ana.say("@my-agent hi", { channel }); msg.delivery; // the app_mention event_callback const comment = await ben.comment("@my-agent investigate", { issue }); comment.delivery; // the issue_comment webhook const session = await mo.delegate(linear.app, { issue: ticket }); session.delivery; // the AgentSessionEvent that opened the session const command = await ana.runCommand("/deploy web staging", { channel }); // a slash command, click, shortcut or modal submission resolves to its delivery ``` ```python title="Python" msg = await ana.say("@my-agent hi", channel=channel) msg.delivery # the app_mention event_callback comment = await ben.comment("@my-agent investigate", issue=issue) comment.delivery # the issue_comment webhook session = await mo.delegate(linear.app, issue=ticket) session.delivery # the AgentSessionEvent that opened the session command = await ana.run_command("/deploy web staging", channel=channel) # a slash command, click, shortcut or modal submission resolves to its delivery ``` ```rust title="Rust" let msg = ana.say("@my-agent hi").channel(&channel).await?; msg.delivery(); // the app_mention event_callback let comment = ben.comment("@my-agent investigate").issue(&issue).await?; comment.delivery(); // the issue_comment webhook let session = mo.delegate(&linear.app()).issue(&ticket).await?; session.delivery(); // the AgentSessionEvent that opened the session let command = ana .run_command("/deploy web staging") .channel(&channel) .await?; // a slash command, click, shortcut or modal submission resolves to its delivery ``` A delivery has its `attempts`, each with the request headers, the app's response status and body, and how long the app took. Its `status` is the latest attempt's: | Status | Meaning | | -------------- | ------------------------------------------- | | `pending` | Queued or in flight | | `acknowledged` | The app answered 2xx in time | | `failed` | The app answered, but not 2xx | | `timed_out` | The app didn't answer within the ack window | | `unreachable` | The app's URL couldn't be reached | `delivery.settled()` waits until the latest attempt has a final status. `msg.delivery` is `undefined` when nothing was sent: the app isn't in the channel, isn't installed or connected, or the server has no URL for the app ([connecting your app](https://channelstack.dev/docs/guide/connecting-your-agent#tell-the-server-where-the-app-listens)). ## Slack's retry 1. Slack delivers the event. Without an answer within 3 seconds it counts the delivery as failed. 2. It sends the same event again, with the attempt number and the reason in its retry headers. 3. An app that remembers the event id acknowledges the retry and does nothing else. 4. The thread gets one reply. An app that doesn't check answers twice. Slack expects an acknowledgement within 3 seconds. An app that does its work before answering the HTTP request misses that window, and Slack sends the same event again. An app that doesn't notice answers twice. ```ts title="TypeScript" test("survives Slack's 3s retry without answering twice", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); const channel = await slack.createChannel({ participants: [ana, slack.app] }); const msg = await ana.say("@my-agent hi", { channel }); await msg.delivery!.retry({ after: "3s", reason: "http_timeout" }); await expect(msg.thread).toHaveRepliesFrom("my-agent", { count: 1 }); }); ``` ```python title="Python" async def test_survives_slacks_3s_retry_without_answering_twice(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") channel = await slack.create_channel(participants=[ana, slack.app]) msg = await ana.say("@my-agent hi", channel=channel) assert msg.delivery await msg.delivery.retry(after="3s", reason="http_timeout") await expect(msg.thread).to_have_replies_from("my-agent", count=1) ``` ```rust title="Rust" let ana = slack.create_user().name("Ana").await?; let channel = slack .create_channel() .participants(vec![&ana as &dyn Handle, &slack.app()]) .await?; let msg = ana.say("@my-agent hi").channel(&channel).await?; let delivery = msg.delivery().expect("the fake delivered the message"); delivery.retry().after("3s").reason("http_timeout").await?; expect(&msg.thread()) .to_have_replies_from("my-agent", 1) .await?; ``` `retry()` sends the event again the way Slack does: the same payload and `event_id`, with `X-Slack-Retry-Num` and `X-Slack-Retry-Reason`. `after` defaults to 3 seconds, Slack's first retry, and `reason` to `http_timeout` (`http_error` and `too_many_redirects` are the others). The exact-count check then waits for the app to be quiet, so a second answer has time to show up. The test proves the app is idempotent on `event_id`. The usual fix is to acknowledge at once and remember the event ids already handled. Bolt for JavaScript acknowledges events as they arrive unless `processBeforeResponse` is on, which is common on serverless hosts; with it on, a slow handler misses the window. ## Redelivery A redelivery is the same event again, without anything that marks it as a retry. GitHub sends one when someone clicks Redeliver in the App's settings, Linear, Notion and Resend when the first delivery failed, Pub/Sub when a push wasn't acknowledged, and Discord's Gateway when a bot resumes a dropped connection and is sent what it missed: ```ts title="TypeScript" test("a redelivered comment doesn't produce a second answer", async ({ github }) => { const ana = await github.createUser({ login: "ana" }); const repo = await github.createRepo({ collaborators: [ana], apps: [github.app] }); const issue = await ana.openIssue({ title: "Flaky test" }, { repo }); const comment = await ana.comment("@my-agent investigate", { issue }); await expect(issue).toHaveCommentFrom(github.app); await comment.delivery!.redeliver(); await expect(issue).toHaveCommentsFrom(github.app, { count: 1, quietFor: "2s" }); }); ``` ```python title="Python" async def test_a_redelivered_comment_doesnt_produce_a_second_answer(github: GitHubFixture) -> None: ana = await github.create_user(login="ana") repo = await github.create_repo(collaborators=[ana], apps=[github.app]) issue = await ana.open_issue({"title": "Flaky test"}, repo=repo) comment = await ana.comment("@my-agent investigate", issue=issue) await expect(issue).to_have_comment_from(github.app) assert comment.delivery await comment.delivery.redeliver() await expect(issue).to_have_comments_from(github.app, count=1, quiet_for="2s") ``` ```rust title="Rust" let ana = github.create_user().login("ana").await?; let repo = github .create_repo() .collaborators(vec![&ana as &dyn Handle]) .apps(vec![&github.app()]) .await?; let issue = ana .open_issue(json!({ "title": "Flaky test" })) .repo(&repo) .await?; let comment = ana.comment("@my-agent investigate").issue(&issue).await?; expect(&issue).to_have_comment_from(&github.app()).await?; let delivery = comment.delivery().expect("the fake delivered the comment"); delivery.redeliver().await?; expect(&issue) .to_have_comments_from(&github.app(), 1) .quiet_for("2s") .await?; ``` | Platform | Call | What the app gets | | -------- | ---------------------- | --------------------------------------------------------------------------------- | | Slack | `delivery.resend()` | The same event, same `event_id`, no retry headers | | GitHub | `delivery.redeliver()` | The same webhook with the same `X-GitHub-Delivery` GUID, as from the delivery log | | Linear | `delivery.redeliver()` | The same webhook, stamped with a new `webhookTimestamp` and signed again | | Notion | `delivery.redeliver()` | The same event again | | Resend | `delivery.redeliver()` | The same webhook with the same `svix-id`, signed again at its own time | | Google | `delivery.redeliver()` | The same push with the same message id, with a fresh token | For Linear, check that the work doesn't start over: ```ts title="TypeScript" test("a redelivered webhook doesn't duplicate activities", async ({ linear }) => { const ana = await linear.createUser({ name: "Ana" }); const team = await linear.createTeam({ members: [ana] }); const issue = await ana.createIssue({ title: "Anything" }, { team }); const session = await ana.delegate(linear.app, { issue }); await expect(session).toHaveActivity({ type: "thought" }); const before = (await session.activities()).length; await session.delivery!.redeliver(); await expect(issue).toHaveSessionState("complete"); const thoughts = (await session.activities()).filter((a) => a.type === "thought"); expect(thoughts.length).toBeLessThanOrEqual(before); }); ``` ```python title="Python" async def test_a_redelivered_webhook_doesnt_duplicate_activities(linear: LinearFixture) -> None: ana = await linear.create_user(name="Ana") team = await linear.create_team(members=[ana]) issue = await ana.create_issue({"title": "Anything"}, team=team) session = await ana.delegate(linear.app, issue=issue) await expect(session).to_have_activity(type="thought") before = len(await session.activities()) assert session.delivery await session.delivery.redeliver() await expect(issue).to_have_session_state("complete") thoughts = [a for a in await session.activities() if a.type == "thought"] assert len(thoughts) <= before ``` ```rust title="Rust" let ana = linear.create_user().name("Ana").await?; let team = linear.create_team().members(vec![&ana]).await?; let issue = ana .create_issue(json!({ "title": "Anything" })) .team(&team) .await?; let session = ana.delegate(&linear.app()).issue(&issue).await?; expect(&session) .to_have_activity() .r#type("thought") .await?; // The Rust SDK returns the activities as JSON. let before = session.activities().await?.as_array().map_or(0, Vec::len); let delivery = session.delivery().expect("the fake delivered the webhook"); delivery.redeliver().await?; expect(&issue).to_have_session_state("complete").await?; let activities = session.activities().await?; let thoughts = activities .as_array() .into_iter() .flatten() .filter(|a| a["type"] == "thought") .count(); assert!(thoughts <= before); ``` ## Bad signatures and stale timestamps An app must refuse a request it can't verify. `resend` sends the delivery again with a twist, and `toBeRejected` checks that the app answered it with a 4xx: ```ts title="TypeScript" test("rejects a bad signature and a stale timestamp", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); const msg = await ana.say("hi", { to: slack.app }); await msg.delivery!.resend({ badSignature: true }); await expect(msg.delivery!).toBeRejected(); await msg.delivery!.resend({ stale: true }); await expect(msg.delivery!).toBeRejected(); }); ``` ```python title="Python" async def test_rejects_a_bad_signature_and_a_stale_timestamp(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") msg = await ana.say("hi", to=slack.app) assert msg.delivery await msg.delivery.resend(bad_signature=True) await expect(msg.delivery).to_be_rejected() await msg.delivery.resend(stale=True) await expect(msg.delivery).to_be_rejected() ``` ```rust title="Rust" let ana = slack.create_user().name("Ana").await?; let msg = ana.say("hi").to(&slack.app()).await?; let delivery = msg.delivery().expect("the fake delivered the message"); delivery.resend().bad_signature(true).await?; expect(&delivery).to_be_rejected().await?; delivery.resend().stale(true).await?; expect(&delivery).to_be_rejected().await?; ``` | Option | What it sends | Platforms | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `badSignature: true` | The same body, signed with a secret that isn't the app's | Slack, GitHub, Linear, Notion, Resend, Google (a token another key signed), Discord (an interaction over HTTP, signed with another Ed25519 key) | | `stale: true` | Signed correctly, but with a time outside the replay window: 6 minutes old on Slack and Resend, 2 minutes on Linear; on Google, a token that has expired | Slack, Linear, Resend, Google | | `wrongAudience: true` | Signed correctly, but a token for another endpoint than the app's | Google | | `headers` | Extra or replaced headers for this attempt | Slack | `toBeRejected` reads the latest forged attempt. It fails when the app answered 2xx, and it tells you to call `resend` first when no forged attempt was sent. A forged attempt never counts toward `toBeAccepted` or `toBeRetried`. Most SDKs verify signatures for you (Bolt, Probot, `@octokit/webhooks`, `LinearWebhookClient`), so these tests mostly catch an app that turned verification off, or one that reads the body before the SDK can check it. ## Acknowledging in time `toBeAccepted` checks that the app answered 2xx, and with `within`, that it did so that fast: ```ts title="TypeScript" test("a slash command is acknowledged within 3 seconds", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); const channel = await slack.createChannel({ participants: [ana, slack.app] }); const command = await ana.runCommand("/deploy web staging", { channel }); await expect(command).toBeAccepted({ within: "3s" }); await expect(channel).toContainText(/deploying web to staging/i); }); ``` ```python title="Python" async def test_a_slash_command_is_acknowledged_within_3_seconds(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") channel = await slack.create_channel(participants=[ana, slack.app]) command = await ana.run_command("/deploy web staging", channel=channel) await expect(command).to_be_accepted(within="3s") await expect(channel).to_contain_text(re.compile("deploying web to staging", re.I)) ``` ```rust title="Rust" let ana = slack.create_user().name("Ana").await?; let channel = slack .create_channel() .participants(vec![&ana as &dyn Handle, &slack.app()]) .await?; let command = ana .run_command("/deploy web staging") .channel(&channel) .await?; expect(&command).to_be_accepted().within("3s").await?; expect(&channel) .to_contain_text(Regex::new("(?i)deploying web to staging")?) .await?; ``` It reads the first real attempt. Without `within`, the platform's ack window is the limit, because an attempt answered after it is `timed_out`, not `acknowledged`. The same check works on a modal submission (`await modal.submit(…)`), a click and a shortcut. `toBeRetried` is the other side: the delivery needed more than one attempt, because the app didn't acknowledge the first in time. `{ times }` makes it exact, and an exact check waits for quiet. `.not.toBeRetried()` is a short way to say the app was fast enough that the platform never retried. Retries you sent yourself with `retry()` count as attempts too. ## Faults `slack.fault` makes the fake Slack Web API misbehave in a way the app has to handle: ```ts title="TypeScript" test("backs off on rate limits and still answers", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); const fault = await slack.fault({ type: "rate_limit", operation: "chat.postMessage", retryAfter: "1s", times: 1 }); const msg = await ana.say("hi", { to: slack.app }); await expect(msg.thread).toHaveRepliesFrom("my-agent", { count: 1 }); await expect(slack).toHaveReceivedCall("chat.postMessage", { times: 2 }); await fault.undo(); }); ``` ```python title="Python" async def test_backs_off_on_rate_limits_and_still_answers(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") fault = await slack.fault(type="rate_limit", operation="chat.postMessage", retry_after="1s", times=1) msg = await ana.say("hi", to=slack.app) await expect(msg.thread).to_have_replies_from("my-agent", count=1) await expect(slack).to_have_received_call("chat.postMessage", times=2) await fault.undo() ``` ```rust title="Rust" let ana = slack.create_user().name("Ana").await?; let fault = slack .fault() .r#type("rate_limit") .operation("chat.postMessage") .retry_after("1s") .times(1) .await?; let msg = ana.say("hi").to(&slack.app()).await?; expect(&msg.thread()) .to_have_replies_from("my-agent", 1) .await?; expect(&slack) .to_have_received_call("chat.postMessage") .times(2) .await?; fault.undo().await?; ``` | Fault | Options | What the app sees | | ------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `rate_limit` | `operation`, `retryAfter` (default 1 s), `times` | HTTP 429 with `Retry-After`. The session stays busy until the app retries, so the checks wait for it ([waiting and quiet](https://channelstack.dev/docs/guide/waiting-and-quiet#the-quiet-window)) | | `error` | `operation` (required), `error` (default `internal_error`), `times` | The call fails with that Slack error code, for example `msg_too_long` | | `latency` | `operation`, `delay` | Each call takes `delay` longer | | `drop_socket` | `after` (default: now) | The Socket Mode connection drops once. A Socket Mode app should reconnect | Without `operation`, a fault applies to every Web API method; without `times`, to every call until it's undone. ```ts title="TypeScript" test("reconnects after the Socket Mode connection drops", async ({ slack }) => { const ana = await slack.createUser({ name: "Ana" }); await slack.fault({ type: "drop_socket" }); const msg = await ana.say("still there?", { to: slack.app }); await expect(msg.thread).toHaveReplyFrom("my-agent", { timeout: "20s" }); }); ``` ```python title="Python" async def test_reconnects_after_the_socket_mode_connection_drops(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") await slack.fault(type="drop_socket") msg = await ana.say("still there?", to=slack.app) await expect(msg.thread).to_have_reply_from("my-agent", timeout="20s") ``` ```rust title="Rust" let ana = slack.create_user().name("Ana").await?; slack.fault().r#type("drop_socket").await?; let msg = ana.say("still there?").to(&slack.app()).await?; expect(&msg.thread()) .to_have_reply_from("my-agent") .timeout("20s") .await?; ``` A fault lasts until `fault.undo()`, the end of an `await using` scope, or the end of the test's session, whichever comes first. > [!WARNING] > A fault applies to the whole workspace, not only to the test that set it: it hits every app's calls, `my-agent`'s and those of any app a test made, and an app's calls belong to no session until they finish. While a fault is in effect, other tests running at the same time see it too. Put fault tests in a file of their own and run it in a separate `vitest run`, so nothing else runs alongside. ## The uninstall When a workspace removes the app, Slack sends `app_uninstalled` and `tokens_revoked`. The app should acknowledge both and drop what it stored for the workspace: ```ts title="TypeScript" test("the uninstall is handled", async ({ slack }) => { const deliveries = await slack.uninstallApp(); for (const delivery of deliveries) await expect(delivery).toBeAccepted(); }); ``` ```python title="Python" async def test_the_uninstall_is_handled(slack: SlackFixture) -> None: deliveries = await slack.uninstall_app() for delivery in deliveries: await expect(delivery).to_be_accepted() ``` ```rust title="Rust" // The Rust SDK returns the deliveries as JSON: make them handles to check them. let deliveries = SlackDelivery::wrap_vec(slack.ctx(), slack.uninstall_app().await?)?; for delivery in &deliveries { expect(delivery).to_be_accepted().await?; } ``` The app is installed again, with the same tokens, when the test's session closes. Like a fault, the uninstall affects every test running at the same moment, so run it on its own. On GitHub, `repo.uninstallApp(github.app)` removes the App from one repository and resolves to the `installation_repositories` delivery. ## Fake only Live, the real platform delivers to your app and channelstack isn't in the path. An action has no delivery: `msg.delivery`, `comment.delivery` and `session.delivery` are `undefined`, so nothing is refused and nothing skips on its own. The `!` in the examples above throws a `TypeError` live. A test that must also run live checks first, and skips: ```ts title="TypeScript" test("survives Slack's retry", async ({ slack, skip }) => { const ana = await slack.createUser({ name: "Ana" }); const msg = await ana.say("@my-agent hello", { to: slack.app }); const delivery = msg.delivery ?? skip("live: the platform delivers to the agent itself"); await delivery.retry({ after: "3s", reason: "http_timeout" }); await expect(msg.thread).toHaveRepliesFrom(slack.app, { count: 1 }); }); ``` ```python title="Python" async def test_survives_slacks_retry(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") msg = await ana.say("@my-agent hello", to=slack.app) if msg.delivery is None: pytest.skip("live: the platform delivers to the agent itself") await msg.delivery.retry(after="3s", reason="http_timeout") await expect(msg.thread).to_have_replies_from(slack.app, count=1) ``` ```rust title="Rust" let ana = slack.create_user().name("Ana").await?; let msg = ana.say("@my-agent hello").to(&slack.app()).await?; // Rust's test harness can't skip at run time: the test says why and passes. let Some(delivery) = msg.delivery() else { eprintln!("skipped: live: the platform delivers to the agent itself"); return Ok(()); }; delivery.retry().after("3s").reason("http_timeout").await?; expect(&msg.thread()) .to_have_replies_from(&slack.app(), 1) .await?; ``` The rest is refused, and Vitest and pytest skip the test with the reason: - `slack.fault()` and `fault.undo()` with `action_requires`: a fault needs proxy mode, which live doesn't read the app's calls back yet ([#24](https://github.com/christian-bromann/channelstack/issues/24)). - `slack.uninstallApp()`, and reading or resending deliveries (`slack.deliveries()`, `linear.deliveries()`, `notion.deliveries()`, `resend.deliveries()`, `google.deliveries()`, `discord.deliveries()`, `delivery.retry()`, `delivery.resend()`), with `unsupported_in_live`. The same test runs in full against the fake on every pull request. GitHub is the exception, because its App delivery log has an API: live, `github.deliveries()`, `toBeAccepted` and `delivery.redeliver()` work on the deliveries it lists, against a real test org, a few seconds after GitHub delivered. A comment's own `comment.delivery` is still `undefined` live. See [live mode](https://channelstack.dev/docs/guide/live-mode). # Standard checks Source: https://channelstack.dev/docs/guide/standard-checks The standard checks are a set of tests for the bugs apps and agents commonly have on each platform: answering twice, answering in the wrong place, answering themselves, mishandling a retry. This page shows how to add them to your suite, what each check catches, and how to leave one out. ## Add the checks ```ts title="test/checks.test.ts" import { discordChecks, githubChecks, googleChecks, linearChecks, notionChecks, resendChecks, slackChecks, } from "channelstack/checks"; slackChecks({ app: "my-agent", streamPrompt: "write a long report on Q3", approval: { prompt: "@my-agent deploy web to staging", button: "Approve" }, }); githubChecks({ app: "my-agent" }); linearChecks({ app: "my-agent" }); notionChecks({ app: "my-agent", prompt: "@my-agent summarize this page" }); resendChecks({ app: "my-agent", prompt: "Where is my refund?" }); googleChecks({ app: "my-agent", prompt: "Where is my refund?" }); discordChecks({ app: "my-agent", command: "/deploy web", longPrompt: "write a long report on Q3" }); ``` Each call registers ordinary Vitest tests in the file it's called from, on the fixtures and matchers of `channelstack/vitest`, so the [plugin](https://channelstack.dev/docs/guide/writing-tests#add-the-plugin) must be set up. The tests are grouped in a `describe` named after the platform and the app (`slack checks: my-agent`), and each test name ends in the check's id: ``` ✓ slack checks: my-agent > replies once to a DM [slack.dm-once] ✓ slack checks: my-agent > survives Slack's retry after 3 seconds [slack.retry] ✓ github checks: my-agent > every check run it starts reaches a conclusion [github.check-run] ``` A check you skip, or one whose option you didn't give, isn't registered at all, so it doesn't show up in the report. Call only the functions for the platforms your app is on. The checks are written against the public test API, the same one your own tests use, so a failing check reads like one of your tests failing: the matcher's message says what a person would have seen. ## Options | Option | Default | What it's for | | -------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `app` | required | The app's name as people mention it: `my-agent`, or any app's. For another name the checks make that app (`createApp({ name })`) and run against the agent driving it, so `slackChecks({ app: "coder" })` checks a second agent ([several apps](https://channelstack.dev/docs/guide/several-apps)) | | `prompt` | `@ hello` | Text that makes the app answer. For Linear it's the title of the issue that gets delegated, default `Look into this` | | `streamPrompt` | none | Text that makes the app stream a longer answer in a DM. Without it, the two stream checks are left out | | `approval` | none | `{ prompt, button }`: text that makes the app ask for an approval, and the label of the button it shows. Only a workspace admin may press it. Without it, the two click checks are left out | | `command` | none | Discord: a slash command the app answers, as a person types it (`/deploy web`). Without it, the two interaction checks are left out | | `longPrompt` | none | Discord: text that makes the app answer with more than one message may hold (2000 characters). Without it, the long-answer check is left out | | `model` | none | `"openai"`: the app's model is the [fake OpenAI](https://channelstack.dev/docs/platforms/openai). Every check that scripts nothing itself answers each model call with a plain answer, the stream and Stop checks script a long stream and need no `streamPrompt`, and the Slack model checks are added (below) | | `skip` | `[]` | Check ids to leave out, for example `["slack.stream-stop"]`. An id that no check has throws, with the list of ids | | `timeout` | the plugin's `timeout` | How long each check waits for the app | | `loopTurns` | `3` | How many times the app may answer another app that answers everything, with no person between them, before `.no-reply-loop` fails. An app built to hand off to another sets it higher, or skips the check | Pick prompts your app answers quickly and in a single message. With a real model, a short, plain prompt keeps the checks fast. With a framework's fake model, use one your script already handles. On the fake OpenAI, pass `model: "openai"` and the checks script the model themselves. ## Slack checks | Id | What the test does | What it catches | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slack.dm-once` | Ana DMs the prompt; expects exactly one reply | Two answers to one DM | | `slack.mention-once` | Ana mentions the app in a channel; expects exactly one reply | Answering both the `app_mention` and the `message` event for the same message | | `slack.in-thread` | A mention in a channel; expects a reply in the thread, and no message in the channel itself | Answers that land in the channel instead of the thread | | `slack.retry` | Retries the mention's event after 3 seconds, as Slack does; expects one reply | Answering again on Slack's retry | | `slack.redelivery` | After the reply, sends the same event again, unchanged; expects one reply | An app that only checks the retry headers, not the `event_id` | | `slack.ignores-bots` | Another bot mentions the app; expects no reply | Bot-to-bot loops | | `slack.bad-signature` | Resends a DM's event with a wrong signature; expects a 4xx | Turned-off or broken signature checks. Over Socket Mode there's no signature, and the check passes without sending anything | | `slack.ack` | A DM; expects the delivery acknowledged within 3 seconds | Work done before the acknowledgement | | `slack.msg-too-long` | Slack refuses the app's next `chat.postMessage` once with `msg_too_long`; expects exactly one reply in the end | An app that gives up, or crashes, when a message is too long | | `slack.stream-stop` | Needs `streamPrompt`. Expects a streaming reply that ends `completed`, and the thread `idle` | A stream that is never stopped, leaving "Thinking…" up | | `slack.stop` | Needs `streamPrompt`. Ana presses Stop during the stream; expects the thread `stopped` and exactly one reply | Writing on after Stop | | `slack.click-unauthorized` | Needs `approval`. A non-admin presses the button; expects the thread to still hold only the ask | Acting on, or answering publicly, a click from someone who may not act | | `slack.double-click` | Needs `approval`. An admin presses the button twice at once; expects exactly one new message in the thread | Acting twice on a double click | | `slack.no-reply-loop` | Another app in the channel answers every reply of the app's, mentioning it; expects the thread to go quiet, the app answering it at most `loopTurns` times | Two agents answering each other without end. Ignoring bot messages only by `subtype: "bot_message"` misses a modern app's, which carry `bot_id` and no subtype | `slack.double-click` counts messages: the app should answer one approval with exactly one new message in the thread. Replacing the question as well is fine, and so is removing the button once it has acted. An app that answers only by editing the question, or with several messages, should skip this check. `slack.msg-too-long` injects a [fault](https://channelstack.dev/docs/guide/delivery-and-failures#faults), which applies to the whole workspace while it lasts. Run the Slack checks where no other test posts at the same moment, or skip that check in a parallel suite. ### On the fake OpenAI With `model: "openai"`, `slackChecks` adds one check for each bug a model's timing and failures cause. Each scripts the model itself: ```ts title="test/checks.test.ts" slackChecks({ app: "my-agent", model: "openai" }); ``` | Id | What the test does | What it catches | | --------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | `slack.slow-model` | The model's first token takes 5 seconds, and Slack retries the DM's event after 3; expects exactly one reply | A slow model that makes the app answer Slack's retry too | | `slack.model-error` | Every model call fails with `overloaded`; expects a reply, no stream left open, and the thread `idle` | An app that says nothing, or leaves "Thinking…" up, when the model fails | | `slack.model-retry` | The first two calls fail with `overloaded`, the third answers; expects that answer, once | A retried model call that posts twice, or not at all | | `slack.stream-breaks` | The model's stream is cut after three chunks; expects a reply, no stream left open, and the thread `idle` | A stream that breaks halfway and is never stopped | | `slack.stop-cancels-model` | The model's stream is held after three chunks and Ana presses Stop; expects the thread `stopped` and the model call aborted | An app that stops posting but leaves the model running | | `slack.no-secrets-to-model` | A DM; expects no token, signing secret or key in anything the app sent the model | A token, signing secret or key in the prompt | The ids are exported as `SLACK_MODEL_CHECKS`. Only Slack has model checks so far; the other platforms' are [#120](https://github.com/christian-bromann/channelstack/issues/120). With `model: "openai"`, their checks still answer each model call, so an agent on the fake OpenAI passes them. ## GitHub checks Each check works in a fresh repository with the App installed and Ana as a collaborator. | Id | What the test does | What it catches | | ----------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `github.ignores-own-comments` | Ana mentions the app in an issue; expects exactly one comment from it | An app that answers its own comment, again and again | | `github.one-comment` | Ana mentions it twice, waiting for each answer; expects exactly two comments | More than one comment per trigger | | `github.review-thread` | Ana mentions the app in a comment on a pull request's diff; expects one reply, from the app, in that thread | Answers that go to the pull request's conversation instead of the review thread, or nowhere | | `github.redelivery` | Redelivers the comment's webhook with the same GUID; expects one comment | Handling a redelivery from the App's settings as a new event | | `github.check-run` | Opens a pull request; once the app is quiet, expects every check run to be completed | Check runs left `queued` or `in_progress`, which block merging | | `github.bad-signature` | Resends the webhook with a wrong signature; expects a 4xx | Turned-off webhook verification | | `github.no-reply-loop` | Another App on the repository mentions the app after each of its comments; expects at most `loopTurns` answers to it | An App that answers every `issue_comment`, a bot's included: GitHub sends an App the other Apps' comments, and nothing stops the loop | `github.check-run` passes for an app that creates no check runs. Skip it if your App doesn't use them, to keep the report honest. ## Linear checks Each check creates an issue titled with `prompt` and delegates it to the app, which opens an agent session. | Id | What the test does | What it catches | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | `linear.first-activity` | Expects some activity from the app within 10 seconds | A slow first response; Linear shows the session as unresponsive after that | | `linear.ends-turn` | Expects the session to reach `complete`, `awaitingInput` or `error` | A session left `active` after the work is done | | `linear.stop` | After the first activity, Ana presses Stop; expects `complete` or `error` | Ignoring the stop signal | | `linear.redelivery` | After the turn ends, redelivers the webhook that opened the session; expects at most one `response` activity | Starting the work over on a redelivery | | `linear.stale` | Resends that webhook with a `webhookTimestamp` two minutes old; expects a 4xx | Missing replay protection: Linear's receivers should refuse webhooks more than a minute old | | `linear.bad-signature` | Resends it with a wrong signature; expects a 4xx | Turned-off webhook verification | | `linear.no-reply-loop` | After the turn ends, another app comments on the issue after each of the app's comments; expects at most `loopTurns` answers | An app that answers every `Comment` webhook, another app's included | ## Notion checks Each check has Ana post `prompt` as a comment on a page connected to the integration. | Id | What the test does | What it catches | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | | `notion.reply-in-discussion` | Expects a reply in Ana's discussion, and no other discussion on the page | Answers posted as a new page comment, which the person doesn't see where they asked | | `notion.ignores-own-comments` | Expects exactly one comment from the integration | An integration that answers its own comment | | `notion.redelivery` | Sends the comment's webhook again; expects one comment | Handling Notion's retry as a new comment | | `notion.bad-signature` | Resends the webhook with a wrong signature; expects a 4xx | Turned-off `X-Notion-Signature` checks | | `notion.no-reply-loop` | Another integration on the page replies in the discussion after each of the integration's comments; expects at most `loopTurns` answers | An integration that answers every `comment.created`, another integration's included | ## Resend checks Each check has Ana email `prompt` (default `hello`) to the agent's address. | Id | What the test does | What it catches | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `resend.reply-in-thread` | Expects the answer in Ana's mailbox, in the thread her email started | An answer without `In-Reply-To` and `References`, which starts a new thread | | `resend.redelivery` | Sends the `email.received` webhook again, as Resend retries; expects one answer | Handling Resend's retry (the same `svix-id`) as a new email | | `resend.bad-signature` | Resends the webhook with a wrong signature; expects a 4xx | Turned-off `resend.webhooks.verify` | | `resend.stale` | Resends it signed more than five minutes ago; expects a 4xx | Missing replay protection on `svix-timestamp` | | `resend.no-reply-loop` | Another app emails the agent, marked `Auto-Submitted: auto-replied`, and answers each answer the same way; expects at most `loopTurns` answers | An agent that answers mail a program sent on its own: the oldest email loop. Mark answers with `Auto-Submitted` (RFC 3834) and leave mail so marked unanswered | ## Google checks Each check has Ana email `prompt` (default `hello`) to the agent's Gmail address. The agent must be watching its inbox (`users.watch`) for a push to reach it. | Id | What the test does | What it catches | | ------------------------ | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | `google.reply-in-thread` | Expects the answer in Ana's mailbox, in the thread her email started | An answer without `In-Reply-To` and `References`, which starts a new thread | | `google.history` | Ana sends two emails at once, which one push tells of; expects one answer to each | An agent that answers only the newest message instead of listing its history | | `google.redelivery` | Pushes the same Pub/Sub message again, as Pub/Sub delivers at least once; expects one answer | An agent that reads history from the start again, or answers a message twice | | `google.bad-signature` | Pushes it again with a token another key signed; expects a 4xx | Turned-off `verifyIdToken` | | `google.wrong-audience` | Pushes it again with a token for another endpoint; expects a 4xx | `verifyIdToken` without an `audience` | | `google.stale` | Pushes it again with a token that has expired; expects a 4xx | A signature check that skips the token's `exp` | | `google.no-reply-loop` | As `resend.no-reply-loop`, to the agent's Gmail address | Answering mail marked `Auto-Submitted` | ## Discord checks Each check has Ana mention the app with `prompt` in a channel with the bot, or DM it, as the check says. With `app: "coder"`, the checks run against the bot of the app `coder`, and `command` is that app's command. | Id | What the test does | What it catches | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `discord.mention-once` | Ana mentions the app in a channel; expects exactly one reply | Answering both a mention and the message it is in, or answering twice | | `discord.dm-once` | Ana DMs the prompt; expects exactly one reply | Two answers to one DM | | `discord.ignores-bots` | Another bot writes the prompt; expects no reply | A bot that answers bots (`author.bot`), and the loops that follow | | `discord.no-reply-loop` | Another app in the channel replies to each of the app's answers, mentioning it; expects at most `loopTurns` answers to it | Two bots answering each other without end: Discord sends a bot the other bots' messages, mentions included, with `author.bot` | | `discord.resume` | Drops the Gateway connection just before Ana's DM; expects one reply once the bot resumes | A bot that identifies anew instead of resuming, and loses or repeats what it missed | | `discord.long-answer` | Ana sends `longPrompt`; expects the answer split over several messages, and no 50035 refusal | An answer over 2000 characters, which Discord refuses, or one cut short | | `discord.interaction-3s` | Ana runs `command`; expects the answer within 3 seconds, and no "This interaction failed" | An interaction answered late, after Discord has given up on it | | `discord.bad-signature` | Over HTTP, sends the interaction again signed with another key; expects a 401 | An interactions endpoint that doesn't check `X-Signature-Ed25519` | ## Skipping a check List the ids in `skip`: ```ts slackChecks({ app: "my-agent", skip: ["slack.msg-too-long"] }); githubChecks({ app: "my-agent", skip: ["github.check-run"] }); ``` A check that needs an option you didn't give (`streamPrompt`, `approval`) is left out on its own, as if it were in `skip`. Leave a check out only when it doesn't apply to your app; when a check fails for a real bug, fix the app. To run a single check while you work on its bug, filter by its id, which is part of the test name: ```bash npx vitest run test/checks.test.ts -t "slack.retry" ``` The id lists are exported too, as `SLACK_CHECKS`, `SLACK_MODEL_CHECKS`, `GITHUB_CHECKS`, `LINEAR_CHECKS`, `NOTION_CHECKS`, `RESEND_CHECKS`, `GOOGLE_CHECKS` and `DISCORD_CHECKS`, for a script that builds `skip` from them. ## In live mode Most checks are about delivery: retries, redeliveries, forged signatures, acknowledgement times. Live, the real platform delivers to your app, so a message or comment has no delivery to retry or forge. Every check that needs one skips, before it waits for anything, with the reason in the report (`live: Slack delivers to the agent itself, so delivery checks are fake-only`). Nothing needs to go in `skip` for a live run. A fake run whose agent has no webhook URL (`CHANNELSTACK__WEBHOOK_URL`) has no deliveries either, so these checks skip there too, with the same note. That run is still red: every check that waits for a reply fails. | Checks | Live | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slack.retry`, `slack.redelivery`, `slack.bad-signature`, `slack.ack`, `slack.slow-model`; `github.redelivery`, `github.bad-signature`; `linear.redelivery`, `linear.stale`, `linear.bad-signature`; `notion.redelivery`, `notion.bad-signature`; `resend.redelivery`, `resend.bad-signature`, `resend.stale`; `google.redelivery`, `google.bad-signature`, `google.wrong-audience`, `google.stale` | Skip, with the delivery reason | | `google.history` | Skips at its exact count, because waiting for quiet needs proxy mode live ([Live mode](https://channelstack.dev/docs/guide/live-mode#what-skips-and-what-fails)) | | `slack.msg-too-long`, `slack.stop` and the others that use a fault, Stop or an exact count | Skip, with the reason | | `slack.in-thread`, `slack.ignores-bots`, `slack.stream-stop` | Skip, with the reason: they wait for quiet, read the status line or create a bot user, which live mode can't do yet | | `github.review-thread`, `github.check-run` | Skip, with the reason: they open a pull request, and pull requests aren't built live yet | | `.no-reply-loop` | Skip, with the reason: they make a second app, or wait for quiet, which live mode can't do yet | | `discord.dm-once`, `discord.resume`, `discord.long-answer`, `discord.ignores-bots`, `discord.interaction-3s`, `discord.bad-signature` | Skip, with the reason: live, a person is a bot of their own, and Discord lets no bot DM another bot or run another app's command; another bot to ignore isn't built live; and the dropped connection is a fault | Six run against the real platform: `linear.first-activity`, `linear.ends-turn`, `notion.reply-in-discussion`, `resend.reply-in-thread`, `google.reply-in-thread` and `discord.mention-once`. The fake run on every pull request runs them all. # Several apps Source: https://channelstack.dev/docs/guide/several-apps This page shows how to test an agent that shares a channel, a repository, an issue, a page or a mailbox with other agents: a triage agent that hands off to a coding agent, a review App that comments on a coding App's pull request, two vendors' bots in one support channel. It assumes you know how a test is written, as in [writing tests](https://channelstack.dev/docs/guide/writing-tests). ## The built-in app, and the others Every fake comes with one app, `my-agent`, which each fixture's `app` is (`slack.app`, `github.app`, …), and which your agent acts as. Nothing about it changes when a test adds more. A test adds another app with `createApp({ name })` on the platform's fixture, and puts it where the platform puts apps: ```ts test("the triage agent hands off to the coder", async ({ slack }) => { const coder = await slack.createApp({ name: "coder" }); const ana = await slack.createUser({ name: "Ana" }); const channel = await slack.createChannel({ participants: [ana, slack.app, coder] }); const msg = await ana.say("@coder summarize yesterday's incidents", { channel }); await expect(msg.thread).toHaveRepliesFrom(coder, { count: 1 }); await expect(msg.thread).not.toHaveReplyFrom(slack.app); }); ``` Each app is a real app of its platform, with its own ids, credentials and endpoint, and it hears what the real platform would send it, including what the other apps do: | Platform | An app is | It joins with | | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | | [Slack](https://channelstack.dev/docs/platforms/slack#several-apps) | An app with its own bot user, tokens and signing secret | `participants`, `invite`, `openDM` | | [GitHub](https://channelstack.dev/docs/platforms/github#several-apps) | A GitHub App with its own App id, `[bot]`, key, webhook secret and installation | `createRepo({ apps })`, `repo.installApp(app)` | | [Linear](https://channelstack.dev/docs/platforms/linear#several-apps) | An OAuth app with its own app user, token and webhook secret | A delegation, or a person's mention | | [Notion](https://channelstack.dev/docs/platforms/notion#several-integrations) | An internal integration with its own bot user, token and verification token | `connections` on a page | | [Resend](https://channelstack.dev/docs/platforms/resend#several-apps) | A team of its own, with its key, webhook secret and domain (`.acme.example`) | An email to its address | | [Google](https://channelstack.dev/docs/platforms/google#several-apps) | A mailbox of its own, `@acme.example`, with its OAuth client, refresh token and Pub/Sub topic | An email to its address | | [Discord](https://channelstack.dev/docs/platforms/discord#several-apps) | An application with its own bot user, bot token, Ed25519 key and interactions endpoint, on its own Gateway connection | `participants`, `invite` | `apps()` lists the apps your test used, `my-agent` first, then each it got from `createApp`. An app another test made isn't among them, and its handle is `not_found` in yours until your test asks for it with `createApp` too, which returns the same app. Matchers take an app's handle or its name as the author: `toHaveReplyFrom(coder)` and `toHaveReplyFrom("coder")` mean the same. ## Names, and what an app keeps - **An app is found by its name.** The first `createApp({ name: "coder" })` makes it; later calls with the same settings return the same app, from any test, so parallel tests share it as they share `my-agent`. The same name with other settings is refused with `invalid_argument`. - **A name** is 1 to 32 lower-case letters, digits and hyphens, starting with a letter (`coder`, `code-reviewer`). `my-agent` is taken. A person and an app in one test can't share a name, so a name in a matcher always means one author. - **A channel holds 10 apps** besides `my-agent`. Apps live as long as the server, so a run can't make them without end. - **Its ids** come from `CHANNELSTACK_SEED` and its name, whatever order tests make apps in. **Its secrets** are made once per install and kept in `~/.channelstack/secrets.json` with the rest, so its agent's `.env` stays valid across restarts, and `channelstack secrets rotate` replaces them too. ## Running a second agent channelstack never starts an agent, so each app is driven by an agent process you start, or one process holds several apps. Tell the server where each app takes its events, one variable per app, and start each agent with its own `.env`: ```bash CHANNELSTACK_SLACK_WEBHOOK_URL=http://localhost:3000/slack/events \ CHANNELSTACK_SLACK_APP_CODER_WEBHOOK_URL=http://localhost:3001/slack/events \ npx channelstack npx channelstack env --channel slack > .env.agent npx channelstack env --app coder --channel slack > .env.coder ``` The variable is `CHANNELSTACK__APP__WEBHOOK_URL`, with the name in upper case and `-` as `_` (`code-reviewer` is `CODE_REVIEWER`), read once when the server starts. An app without one receives nothing, unless it opens its own connection: Slack's Socket Mode with its app token, or Discord's Gateway with its bot token (on Discord, the variable is its interactions endpoint). `channelstack env --app coder` prints the app's lines under the same keys `my-agent`'s have (`SLACK_BOT_TOKEN`, `SLACK_SIGNING_SECRET`, …), so the same agent code starts as `coder` from a different `.env`. Asking makes the app if no test has yet, so the agent can start first; without `--channel` it makes it on every channel, so name the one the agent is on. In a test, `channelstack.env({ app: "coder" })` gives the same. The agent also needs to know its own name, to tell a mention of itself from one of the other app's. Every delivery says which app it went to (`delivery.app`). A message's or an email's `delivery` is still the one to `my-agent`; `deliveryFor(coder)` reads another app's, where the platform has one per message: Slack and Discord messages, Linear comments, Resend and Google emails. ## An app the test acts as An app that no agent drives can be played by the test. Its handle has the acting methods a person has on that platform (`say`, `reply`, `react` on Slack and Discord; `comment`, `openIssue`, `review` on GitHub; `send`, `reply` on email), and they go through the fake's own API with the app's token, so what the others receive is exactly what that app's own call would send: `bot_id`, `app_id` and `bot_profile` on Slack, `author.bot` and the bot's id on Discord, `sender.type: "Bot"` on GitHub. ```ts test("another app's mention doesn't set the agent off", async ({ slack }) => { const deployer = await slack.createApp({ name: "deployer" }); const channel = await slack.createChannel({ participants: [slack.app, deployer] }); const msg = await deployer.say("@my-agent the deploy of web finished", { channel }); const delivery = await msg.deliveryFor(slack.app); expect(delivery?.eventType).toBe("app_mention"); await expect(msg.thread).not.toHaveReplyFrom(slack.app); }); ``` Acting as `my-agent` is refused with `invalid_argument`: your agent is that app. Script an app only when no agent drives it; two writers in one app confuse the transcript. Slack's `createUser({ bot: true })` stays the cheapest way to say "a bot wrote this": a user with a `bot_id`, but no app, no credentials and no events. ## Agents that answer each other The bug that only shows with two real apps in one place is the reply loop: two agents that answer each other without end. Bolt's `ignoreSelf` drops only an app's own messages, a discord.js bot that checks only `message.author.id === client.user.id` answers every other bot, and GitHub sends an App the other Apps' comments with nothing to stop them. `toGoQuiet` checks for it. It waits until the conversation is quiet, as the negative matchers do, and fails when that takes longer than `within`, or when the conversation holds more than `maxReplies` app messages since a person last wrote, those before the check included. Its message names the authors in turn: ```ts await expect(msg.thread).toGoQuiet({ within: "10s", maxReplies: 4 }); // Expected the conversation to go quiet within 10s with at most 4 app messages since a person last wrote. // It was still busy with 14 app messages and no person between them: my-agent → coder → my-agent → … ``` In pytest it is `await expect(msg.thread).to_go_quiet(max_replies=4, within="10s")`; in Rust, `expect(&thread).to_go_quiet(4).within("10s").await?`. A test that forgets to check still can't spin until its timeout. The fake counts the app messages in each conversation since a person last wrote there, and after 50 it stops delivering the events of the app messages it counts there, records a `bot_loop` event (in `channelstack tail` and the UI's inspector), and fails the test at teardown, naming the loop. That stop is the fake's, not the platform's: real platforms throttle and never stop, and in live mode nothing stands between the agents. The [standard checks](https://channelstack.dev/docs/guide/standard-checks) cover it for every platform: `.no-reply-loop` scripts a peer app that answers everything your agent says, and expects the agent to stop within `loopTurns` turns (default 3). On email, the peer marks its mail `Auto-Submitted`, and the agent should leave such mail unanswered. Pass `app: "coder"` to run every check against the agent driving `coder` instead of `my-agent`. ## Live mode Extra apps are fake only for now: live, `createApp` and an app's acting aren't built yet. Each extra app will be a real sandbox app, made by hand once, with its own agent deployed at its own public URL, and its credentials in `CHANNELSTACK__APP__…` variables. See [live mode](https://channelstack.dev/docs/guide/live-mode). # pytest Source: https://channelstack.dev/docs/guide/pytest `pytest-channelstack` brings channelstack to pytest: a fixture per platform, one session per test, and `expect(...)` checks with the same waiting rules as the Vitest matchers. This page shows how to set it up and write tests with it. ## Install ```bash pip install pytest-channelstack npm i -g channelstack ``` `pytest-channelstack` needs Python 3.12 or later. It installs the `channelstack` Python SDK, pytest and pytest-asyncio with it, and registers itself as a pytest plugin, so there is nothing to import in `conftest.py`. The server is the same binary for every language, and it comes from npm. Start it, and your app, as in [connecting your app](https://channelstack.dev/docs/guide/connecting-your-agent): ```bash npx channelstack ``` ## Configure pytest The client outlives each test, so every test and fixture must run on one event loop for the whole run. Set that once, with pytest-asyncio's own settings: ```ini title="pytest.ini" [pytest] asyncio_mode = auto asyncio_default_fixture_loop_scope = session asyncio_default_test_loop_scope = session channelstack_mode = attach ``` ```toml title="pyproject.toml" [tool.pytest.ini_options] asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "session" asyncio_default_test_loop_scope = "session" channelstack_mode = "attach" ``` With `asyncio_mode = auto`, every `async def test_…` runs without a marker. Without the two loop-scope settings, the second test fails, because the client was made on the first test's loop. The plugin adds three settings of its own: | Setting | Default | What it does | | ----------------------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------- | | `channelstack_mode`, or `--channelstack-mode` on the command line | `auto` | `attach` fails when no server is running, `start` starts a private one, `auto` attaches if it can and starts one otherwise | | `channelstack_timeout` | `10s` | How long an `expect(...)` check, and every SDK wait, waits | | `channelstack_quiet_for` | `750ms` | How long the app must be quiet before a negative or exact-count check, or a `latest_…` read, reads | The command-line flag wins over the ini file. The client finds the server the way every channelstack client does: `CHANNELSTACK_URL` with `CHANNELSTACK_TOKEN`, or else the `server.json` in `~/.channelstack` (or `CHANNELSTACK_HOME`). In `start` mode it runs `CHANNELSTACK_SERVER_BIN`, or `channelstack` from your `PATH`. A server started that way has no agent connected to it, so `attach` is the usual choice, and in CI it fails at once when the server isn't up. ## The fixtures | Fixture | Scope | What it is | | ---------------------- | -------- | --------------------------------------------------------------------------------- | | `channelstack` | the run | The client: `env()`, `reset()`, `open_session()` | | `channelstack_session` | the test | The test's session. Closing it after the test removes everything the test created | | `slack` | the test | The fake Slack workspace in the test's session | | `github` | the test | The fake GitHub org | | `linear` | the test | The fake Linear workspace | | `notion` | the test | The fake Notion workspace | | `resend` | the test | The fake Resend team | | `google` | the test | The fake Gmail mailbox | | `discord` | the test | The fake Discord guild | | `openai` | the test | The fake OpenAI, your agent's model: its scripts and calls | A test asks for the fixtures it uses by name. Asking for `slack` opens the test's session on the way, so most tests name only the platform. ## A full test ```python title="tests/test_slack.py" import re from channelstack import SlackFixture from pytest_channelstack import expect async def test_a_mention_gets_exactly_one_reply_in_the_thread(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") channel = await slack.create_channel(participants=[ana, slack.app]) msg = await ana.say("@my-agent summarize yesterday's incidents", channel=channel) await expect(msg.thread).to_have_reply_from("my-agent", text=re.compile("incident", re.I)) await expect(msg.thread).to_have_replies_from(slack.app, count=1) await expect(channel).not_to_have_channel_message_from("my-agent") async def test_follow_ups_in_the_thread_are_answered_without_a_new_mention(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") channel = await slack.create_channel(participants=[ana, slack.app]) msg = await ana.say("@my-agent what's the status of the web deploy?", channel=channel) await msg.thread.wait_for_reply(from_="my-agent") await ana.reply("and the API?", thread=msg) answer = await msg.thread.wait_for_reply(from_="my-agent") assert re.search("api", answer.text, re.I) async def test_stop_ends_the_stream_and_the_agent_stays_quiet(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") msg = await ana.say("write a long report on Q3", to=slack.app) await expect(msg.thread).to_have_streaming_reply_from("my-agent") await ana.stop(thread=msg) await expect(msg.thread).to_have_status("stopped") await expect(msg.thread).to_have_replies_from("my-agent", count=1) ``` The API is the same as in TypeScript, in Python's spelling: methods and options in snake case (`create_user`, `wait_for_reply`, `bad_signature=True`), options as keyword arguments, and `from_` where TypeScript says `from`. People act and resources are read, exactly as [writing tests](https://channelstack.dev/docs/guide/writing-tests) describes. ## `expect(...)` and `not_to_…` Each check is an awaitable method on `expect(subject)`. The Vitest matcher `toHaveReplyFrom` is `to_have_reply_from`, and Vitest's `.not.` is a `not_to_…` method of its own: ```python await expect(msg.thread).to_have_reply_from("my-agent") await expect(first.thread).not_to_have_reply_from("my-agent") ``` The checks follow the matchers' rules. A positive check polls until it holds and fails after the timeout. A negative or exact-count check waits until the app has been quiet for the whole window, then checks once. A failure raises `AssertionError` with what was expected, what the thread had, and what the app left open: ``` AssertionError: Expected exactly 1 reply from my-agent, found 2: my-agent: Deploying web to staging my-agent: Deploying web to staging ``` [Waiting and quiet](https://channelstack.dev/docs/guide/waiting-and-quiet) explains why the checks wait the way they do. ## Which checks exist Every Vitest matcher has a Python check, with the same semantics, options and failure messages: | Python | Vitest | Subject | | ----------------------------------------------------- | -------------------------- | --------------------------------------- | | `to_have_reply_from(author, text=)` | `toHaveReplyFrom` | A thread or a DM | | `to_have_replies_from(author, count=, text=)` | `toHaveRepliesFrom` | A thread or a DM | | `to_have_channel_message_from(author)` | `toHaveChannelMessageFrom` | A channel | | `to_have_streaming_reply_from(author)` | `toHaveStreamingReplyFrom` | A thread | | `to_have_status(state)` | `toHaveStatus` | A thread | | `to_have_status_text(text)` | `toHaveStatusText` | A thread | | `to_have_reaction(emoji, by=)` | `toHaveReaction` | A message | | `to_have_button(label)` | `toHaveButton` | A Slack message, thread or conversation | | `to_have_opened_modal(title=None)` | `toHaveOpenedModal` | A Slack person | | `to_be_ephemeral_for(user)` | `toBeEphemeralFor` | A Slack message | | `to_contain_text(text, count=, from_=, as_=)` | `toContainText` | Anything with a transcript | | `to_have_comment_from(author, text=)` | `toHaveCommentFrom` | An issue, a PR, a discussion | | `to_have_comments_from(author, count=)` | `toHaveCommentsFrom` | An issue, a PR, a discussion | | `to_have_review_comment(path=, line=, from_=, text=)` | `toHaveReviewComment` | A GitHub pull request | | `to_have_review_from(author, state=)` | `toHaveReviewFrom` | A GitHub pull request | | `to_have_check_run(name, status=, conclusion=)` | `toHaveCheckRun` | A GitHub pull request or commit | | `to_have_label(name)` | `toHaveLabel` | A GitHub issue or PR, a Linear issue | | `to_be_merged()` | `toBeMerged` | A GitHub pull request | | `to_have_session_state(state)` | `toHaveSessionState` | A Linear session or issue | | `to_have_activity(type=, from_=, text=)` | `toHaveActivity` | A Linear session or issue | | `to_be_delegated_to(app)` | `toBeDelegatedTo` | A Linear issue | | `to_be_assigned_to(user)` | `toBeAssignedTo` | A Linear issue | | `to_have_state(name)` | `toHaveState` | A Linear issue | | `to_have_block(text)` | `toHaveBlock` | A Notion page | | `to_have_property_value(name, value)` | `toHavePropertyValue` | A Notion page (a database row) | | `to_be_accepted(within=)` | `toBeAccepted` | A delivery | | `to_be_rejected()` | `toBeRejected` | A delivery that was resent forged | | `to_be_retried(times=)` | `toBeRetried` | A delivery | | `to_have_received_call(operation, error=, times=)` | `toHaveReceivedCall` | A platform fixture (`slack`) | Each has a `not_to_…` twin. `text` takes a string to look for or a compiled `re.Pattern`, and an author is a handle (`slack.app`, `ana`) or a name. `to_be_delegated_to` and `to_be_assigned_to` take `None` for no one. `to_have_property_value` compares with `==`, so `unittest.mock.ANY` (or any object with its own `__eq__`) stands in where Vitest uses `expect.any(Number)`. A delivery check takes the delivery itself: ```python title="tests/test_signatures.py" from channelstack import SlackFixture from pytest_channelstack import expect async def test_rejects_a_bad_signature(slack: SlackFixture) -> None: ana = await slack.create_user(name="Ana") msg = await ana.say("hi", to=slack.app) assert msg.delivery is not None await msg.delivery.resend(bad_signature=True) await expect(msg.delivery).to_be_rejected() ``` Each check is built on a plain SDK read (`delivery.refresh()`, `pull.reviews()`, `page.property(name)`, …), so a test can also read the value itself and `assert` on it. Unlike `expect(...)`, a plain read doesn't wait for quiet, so use it for positive facts, or call it after a `wait_for_…` or `latest_…` method. ## Options Every check takes `timeout=`, and every negative or exact-count check also takes `quiet_for=`: ```python await expect(msg.thread).to_have_reply_from("my-agent", timeout="30s") await expect(msg.thread).to_have_replies_from("my-agent", count=1, quiet_for="2s") ``` A duration is a string (`"750ms"`, `"3s"`, `"1m"`) or milliseconds as a number. Without them, a check uses `channelstack_timeout` and `channelstack_quiet_for` from the ini file. The SDK's own waiting methods (`wait_for_reply`, `latest_reply`, `settled`, …) take `timeout=` too, and default to the same ini settings. ## Shared people with fixtures People you use in many tests are ordinary pytest fixtures, built on `slack`. They're created per test, like the platform fixtures they depend on: ```python title="tests/conftest.py" import pytest from channelstack import SlackConversation, SlackFixture, SlackUser @pytest.fixture async def ana(slack: SlackFixture) -> SlackUser: return await slack.create_user(name="Ana") @pytest.fixture async def ben(slack: SlackFixture) -> SlackUser: return await slack.create_user(name="Ben", admin=True) @pytest.fixture async def support(slack: SlackFixture, ana: SlackUser, ben: SlackUser) -> SlackConversation: return await slack.create_channel(name="support", participants=[ana, ben, slack.app]) ``` ```python title="tests/test_support.py" from channelstack import SlackConversation, SlackUser from pytest_channelstack import expect async def test_an_admin_and_a_member_see_the_same_answer( support: SlackConversation, ana: SlackUser, ben: SlackUser ) -> None: question = await ana.say("@my-agent who's on call?", channel=support) await ben.reply("+1, also need this", thread=question) await expect(question.thread).to_have_replies_from("my-agent", count=1) ``` A relative fixture path starts from the test file, as in Vitest: `github.create_repo(files="./fixtures/web", …)` reads `tests/fixtures/web`. ## Live mode With live credentials in the environment, the same tests act on real sandbox workspaces ([live mode](https://channelstack.dev/docs/guide/live-mode)). A step live mode can't do is refused with `unsupported_in_live` (`uninstall_app`, reading deliveries), or with `action_requires` when it needs a piece live mode doesn't drive yet (a fault, Slack's Stop, waiting for quiet: see [what skips](https://channelstack.dev/docs/guide/live-mode#what-skips-and-what-fails)). The plugin turns both into `pytest.skip`, with the reason: ``` SKIPPED [1] tests/test_slack.py:88: live: SlackFixture.fault live needs proxy mode: … ``` Live, a message or comment has no delivery: `msg.delivery` is `None`, so a delivery test checks for it and calls `pytest.skip` itself ([delivery and failures](https://channelstack.dev/docs/guide/delivery-and-failures#fake-only)). Any other error still fails the test, so a broken live setup turns the run red. The fake run on every pull request runs every test in full. # The dev loop: CLI and UI Source: https://channelstack.dev/docs/guide/dev-loop While you work on an app, you want to poke it before you write a test: say something as a person, read the answer, change the code, say it again. The attach CLI and the UI do that against the running server, with no seed data and no ids to copy. ## Before you start Start the server, telling it where your app takes events, and point the app at it. This is the same setup the tests use ([Connecting your app](https://channelstack.dev/docs/guide/connecting-your-agent) has the details): ```bash CHANNELSTACK_SLACK_WEBHOOK_URL=http://localhost:3000/slack/events npx channelstack start npx channelstack env > .env.local # in a second terminal; then start the agent with it ``` Every command below attaches to that server. It finds it through `/server.json` (`~/.channelstack/server.json` by default), which the server writes when it starts. To attach to another one, pass `--server ` or set `CHANNELSTACK_URL`, together with `CHANNELSTACK_TOKEN`. ## Talk to the app ```bash npx channelstack slack say --as ana --in "#support" "@my-agent what broke last night?" ``` ``` ana said it in #support (C0A1B2C3D4E:1732451234.000100) ``` Ana didn't exist and neither did `#support`: the CLI created both on first use, with Ana and the app in the channel. The next time you name them, it uses the same ones. A person who isn't in a conversation yet is invited by someone who is, as on Slack. Now read what the app answered: ```bash npx channelstack show ``` ``` ana: @my-agent what broke last night? my-agent: Here's what I found about "what broke last night?". ``` `show` prints the most recently active place, on any channel, the way a person reads it. Replies in a thread are indented. Buttons show as `[Approve]`, and edits and streams are marked. Ephemeral messages aren't shown: `show` reads as no one in particular, and an ephemeral message is for one person only. The app works asynchronously, so if its reply isn't there yet, run `show` again. | Flag | What it does | | ---------------------------- | ---------------------------------------------- | | `--thread last` | Only the thread of the newest message | | `--thread :` | Only that message's thread | | `slack show --in "#support"` | That channel; `show` on a channel is its own | | `--json` | The transcript entries as JSON, with their ids | ## Keep the conversation going ```bash npx channelstack slack reply --as ben --thread last "and the one before?" npx channelstack slack react --as ben :eyes: --on last npx channelstack slack click --as ana "Approve" npx channelstack slack stop --thread last ``` | Command | What the person does | | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- | | `slack say --as --in "#channel" ""` | Posts a message in a channel | | `slack reply --as [--to last] ""` | Replies in a thread (`--thread` works too) | | `slack react --as <:emoji:> [--on last]` | Reacts to a message. `:eyes:` and `eyes` are the same reaction | | `slack click --as "