# 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<SlackUser> {
    slack.create_user().name("Ana").await
}

async fn ben(slack: &SlackFixture) -> Result<SlackUser> {
    slack.create_user().name("Ben").admin(true).await
}

async fn support(
    slack: &SlackFixture,
    ana: &SlackUser,
    ben: &SlackUser,
) -> Result<SlackConversation> {
    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![&notion.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.
