# Threads and state

> Understand managed conversation identity and history, then persist the SDK state your Slack or Teams workflow owns.

A Slack or Teams workflow often spans several messages, such as an incident
that moves from triage to approval. Each conversation is a Channels `Thread`,
which you use to reply, run the agent, and store workflow data for that
conversation. The SDK passes the `Thread` to `onMessage`, tools, interactions,
and interrupt callbacks.

<Callout type="info" title="A Channels thread is not an Intelligence thread">
  A Channels `Thread` is one conversation inside the SDK. [Threads Drawer](/prebuilt-components/copilot-threads-drawer) provides the application UI for browsing and restoring agent conversations; use [`useThreads`](/reference/hooks/useThreads) to build a custom UI. They share
  a stable thread id. They are different APIs.
</Callout>

## Conversation identity [#conversation-identity]

`thread.conversationKey` is the opaque, stable key Intelligence supplies for
the conversation. Do not parse it or infer workspace, team, channel, or
thread identifiers from its value. The SDK passes this value to your
`agent(threadId)` factory. For a singleton agent, the SDK sets it on the clone.
This is why every quickstart creates a new agent and sets its `threadId`.

```ts title="agent.ts"
export function makeAgent(threadId: string) {
  const agent = createAgentForYourFramework();
  agent.threadId = threadId;
  return agent;
}
```

Prefer an agent **factory** so each turn gets an explicit new instance. You may
also pass a singleton (`agent: shared`); internally the SDK calls
`shared.clone()` per run so concurrent turns do not share one mutable object.
Managed history is loaded onto that per-run agent after isolation.

Managed delivery runs one turn at a time in a conversation. Different
conversations run in parallel. The SDK `store.concurrency` setting
still governs other adapter paths and shared workflow state; it does not raise
the managed same-Thread delivery limit.

The native provider is available on both `message.platform` and
`thread.platform`. Managed turns report `"slack"` or `"teams"`.

<Callout type="info" title="Keep conversation and user identity separate">
  A Thread can contain several provider actors and has no personal owner. See
  [Identity and Memory](/slack/identity-and-memory) before attaching
  application-user data or personal Memory to a turn.
</Callout>

## Welcome a new installation or conversation [#welcome-a-new-installation-or-conversation]

`onWelcome` handles a provider installation or conversation-activation event.
It is a lifecycle event, not a synthetic user message, so it does not run
`onMessage` or add a made-up user turn to the conversation.

```ts title="channel.ts"
channel.onWelcome(async ({ thread, user }) => {
  await thread.post(
    user ? `Welcome, ${user.name}.` : "Welcome. How can I help?",
  );
});
```

The `user` is the nullable application user selected by `identifyUser` for that
event. The provider account that caused the event remains available as `actor`.

## What Intelligence restores [#what-intelligence-restores]

For each new turn, the managed transport reconstructs recent conversation
history for the agent. This history includes the current message and its
attachments, so call `runAgent()` without a `prompt`:

```ts title="channel.ts"
channel.onMessage(async ({ thread }) => {
  await thread.runAgent();
});
```

This history is the conversational record used to seed the agent. It is
separate from application workflow state such as an approval step, selected
environment, or form draft.

## Persist workflow state [#persist-workflow-state]

Use `thread.state()` and `thread.setState()` for JSON-serializable state keyed
by `conversationKey`. A Standard Schema makes reads typed and validates writes:

```bash title="Terminal"
npm install zod
```

```ts title="channel.ts"
import { createChannel } from "@copilotkit/channels";
import { z } from "zod";
import { makeAgent } from "./agent.js";

function required(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing ${name}`);
  return value;
}

const workflowState = z.object({
  incidentId: z.string(),
  stage: z.enum(["triage", "awaiting-approval", "resolved"]),
});

const channel = createChannel({
  name: required("CHANNEL_CODE"),
  identifyUser: "platform",
  agent: makeAgent,
  store: {
    state: workflowState,
  },
});

channel.onMessage(async ({ thread }) => {
  const current = await thread.state();
  await thread.setState({
    incidentId: current?.incidentId ?? "INC-421",
    stage: "triage",
  });
  await thread.runAgent();
});
```

`setState` replaces the stored value; it does not merge a partial patch.

Without `store.adapter`, a managed Channel keeps `thread.state()` in
Intelligence, so it survives a process restart. To decide where the rest of the
SDK state lives across restarts, see
[Persistence and scaling](/slack/persistence-and-scaling).

## Operational checklist [#operational-checklist]

Before you ship:

- Use one fresh agent per `conversationKey`.
- Call `runAgent()` without a `prompt`. Managed history holds the current
  message.
- Store only JSON-serializable workflow data.
- Stop the listener on `SIGINT` and `SIGTERM` so Intelligence can release the
  runtime cleanly.

Good to know:

- Branch on `message.platform` for the current turn; `thread.platform` carries
  the same native provider when only the Thread is available.
- Replace, do not patch, values passed to `setState`.
- Configure your own `StateStore` if locks, lists, or queues must survive a
  restart.

See the [Thread API](/reference/channels/classes/Thread) for methods and
[interactive approvals](/slack/interactive) for the managed resume flow.
