Thread & History Lifecycle

How a threadId is created, how conversation history is restored, how to switch or start threads, and how CopilotKit threads relate to your agent framework's own persistence.

What is this?

Users leave a chat and come back later, or open an earlier conversation. Each conversation is a thread with its own threadId. This page shows how CopilotKit creates the id, restores history, and switches threads. It also shows where CopilotKit threads end and your agent framework's own persistence (for example, a LangGraph checkpointer) begins.

This page describes the hooks and components imported from @copilotkit/react-core/v2.

The lifecycle at a glance

  1. Mint. When a chat mounts without an explicit threadId, the client generates one (a UUID v4).
  2. Run. Messages and tool calls stream under that threadId. If a server-side store is configured (CopilotKit Intelligence, or a persisting AgentRunner), they are persisted as they happen so the thread can be replayed later. Without one, the runtime's default in-memory runner keeps the history only in the runtime process. A restart or a second server instance loses it. See AG-UI Streams & Framework Threads for the full server-side model.
  3. Hydrate. When a chat mounts with a known threadId, the client connects and replays the persisted history into the UI.
  4. Switch / start. You change the active thread (restoring its history) or start a fresh one (clearing the view).

How the threadId is created

When you don't supply one, CopilotKit mints a threadId on the client, at mount, using a UUID v4. The value is resolved by this precedence (highest first):

  1. An explicit threadId prop on <CopilotChat> / <CopilotChatConfigurationProvider> (this is authoritative: it also drives history replay and disables the welcome screen).
  2. An active-thread override set via setActiveThreadId(...) / a picked thread row / startNewThread().
  3. A threadId inherited from a parent configuration provider.
  4. A non-authoritative threadId seed.
  5. Otherwise, a freshly minted randomUUID().
Explicit threadId (recommended when you own persistence)
import { CopilotChat } from "@copilotkit/react-core/v2";

// You control the id: history replays for it, and it's stable across remounts.
<CopilotChat agentId="my-agent" threadId={myThreadId} />

Auto-minted ids are stable across re-renders, but re-mint on remount. The fallback id comes from useMemo. A remount creates a new id and starts a new conversation. A remount happens when the React key changes, when a parent remounts, or in React StrictMode in development. If you need an id that survives remounts, mint it yourself and pass it as the threadId prop (or persist it and restore it via setActiveThreadId). Don't rely on the auto-mint for continuity.

How history is restored (hydration)

History is restored in one of two ways:

1. Server-side replay. When a chat mounts with an explicit threadId, the client sets agent.threadId and calls connectAgent(), which replays that thread's persisted event history back into the UI, with no manual message wiring:

History replays for a known threadId (given a server-side store)
<CopilotChat agentId="my-agent" threadId={someExistingThreadId} />

Durable replay requires a server-side store to replay from: CopilotKit Intelligence, or a persisting AgentRunner (for example, the SQLite runner). The default in-memory runner replays history only while the same runtime process runs. After a restart, or on another server instance, connectAgent() returns an empty stream and the conversation starts blank. If history isn't restoring, check that a store is configured, not the client code. The Persistence Architecture page covers how replay works server-side.

For a fresh (non-explicit) thread, e.g. after startNewThread(), there's nothing to replay, so connect is skipped and the message view is cleared.

2. Manual hydration. If you're managing messages yourself (for non-platform or custom cases), read them from the agent and set them directly:

Read and set messages via the agent
import { useAgent } from "@copilotkit/react-core/v2";

function MyComponent() {
  const { agent } = useAgent({ agentId: "my-agent" });

  // Read the current conversation
  const messages = agent.messages;

  // Replace it (e.g. hydrate from your own store)
  // agent.setMessages(myPersistedMessages);

  return null;
}

Read messages from useAgent().agent.messages. Change them with agent.setMessages(...) or agent.addMessage(...).

Scope CopilotKit threads to the signed-in user

This section is for multi-user apps on an Intelligence-enabled Runtime. It sets up identifyUser on the server. To switch threads on the client, skip to Switching threads and starting new ones.

Your application owns end-user authentication. For an Intelligence-enabled Runtime, implement identifyUser(request) with the server-verified session or token from your auth provider and return a stable user id and name:

app/api/copilotkit/[[...slug]]/route.ts
import { CopilotKitIntelligence, CopilotRuntime } from "@copilotkit/runtime/v2";

// `apiKey` is the only required field. The key scopes the project, so there is
// no separate project or organization id to pass. See Connect your runtime.
const intelligence = new CopilotKitIntelligence({
  apiKey: process.env.CPK_INTELLIGENCE_API_KEY!,
});

const runtime = new CopilotRuntime({
  agents: { default: agent },
  intelligence,
  identifyUser: async (request) => {
    const session = await verifyAppSession(request); // Your server-side auth.
    if (!session?.user) throw new Error("Unauthorized");

    return {
      id: session.user.id,
      name: session.user.name,
    };
  },
});

CopilotKit Intelligence combines that application user identity with the selected project when it scopes thread lists, subscriptions, history, rename, archive, unarchive, and delete operations. The project Runtime API key is a separate credential: keep it on the server and do not use the developer who created that key as the application user.

Connect your runtime to Intelligence covers the CopilotKitIntelligence constructor in full: where the project API key comes from, the self-hosted apiUrl / wsUrl override rule, and how to confirm the credential is actually being read rather than silently ignored.

A static identifyUser value is suitable only for a single-user demo. In a multi-user application, every request must resolve the authenticated application user or those users will share the same thread scope.

See Authentication for forwarding and verifying your provider's auth context. identifyUser is the additional Runtime contract that assigns the verified application user to threads.

Switching threads and starting new ones

Set the active thread to restore its history, or start a fresh conversation:

Switch or start a thread
import { useCopilotChatConfiguration } from "@copilotkit/react-core/v2";

function ThreadControls() {
  const config = useCopilotChatConfiguration();

  return (
    <>
      {/* Restore a known conversation (explicit → replays history) */}
      <button onClick={() => config?.setActiveThreadId(existingId, { explicit: true })}>
        Open conversation
      </button>

      {/* Start a fresh, empty conversation (mints a new non-explicit id) */}
      <button onClick={() => config?.startNewThread()}>New chat</button>
    </>
  );
}
  • setActiveThreadId(threadId, { explicit }): explicit: true (the default) treats it as a known thread and replays its history, while explicit: false shows the welcome screen.
  • startNewThread(): resets to a freshly minted, non-explicit id. Also available from useThreads() for thread-sidebar UIs. See Headless Threads for the full useThreads API.

Both setters no-op and log a warning when the threadId is prop-controlled (i.e. you passed an authoritative threadId prop). If you drive threads imperatively with these setters, don't also pass a threadId prop. Pick one source of truth.

Creating a thread with your own API on the first message

A common ask: intercept the user's first message to mint a thread via your own backend (e.g. create a DB row and get its id) before the conversation starts.

On the built-in <CopilotChat> this cannot be done through onSubmitMessage: the component sets its own submit handler internally and discards any you pass. Instead, use one of these approaches.

Recommended: mint up front and drive the id. Create your thread when the user starts a new conversation (e.g. on a "New chat" action, or lazily just before you render the chat), then hand the id to CopilotKit:

Mint your thread, then drive it
async function startConversation() {
  const { id } = await myApi.createThread(); // your backend
  config?.setActiveThreadId(id, { explicit: true });
  // or render <CopilotChat threadId={id} />
}

At submit-time (headless only). If you must intercept exactly when the user hits send, compose the UI yourself with CopilotChatInput / CopilotChatView and pass your own onSubmitMessage. Because the handler is yours, you set the thread on the agent and drive the send:

Headless: set the thread on the agent before sending
import { CopilotChatInput, randomUUID, useAgent } from "@copilotkit/react-core/v2";

function MyInput() {
  const { agent } = useAgent({ agentId: "my-agent" });

  return (
    <CopilotChatInput
      onSubmitMessage={async (text) => {
        const { id } = await myApi.createThread(); // your backend
        agent.threadId = id;                       // set it on the agent directly
        agent.addMessage({ id: randomUUID(), role: "user", content: text });
        // ...then trigger the run with your send logic
      }}
    />
  );
}

For a send you fire in the same handler, set the id on the agent (agent.threadId = id); don't rely on setActiveThreadId(id). setActiveThreadId updates React state. The agent gets the new id on the next render, and only when a <CopilotChat> is mounted. A run that starts in the same handler still uses the old thread. Use setActiveThreadId / startNewThread for switching threads in the UI, and set agent.threadId directly when it must take effect before an imperative send.

CopilotKit threads vs. your framework's checkpointer

These are two different layers, correlated only by the shared threadId:

LayerWhat it storesManaged by
CopilotKit threadsConversation list + full AG-UI event history (messages, tool calls, state), with realtime syncCopilotKit Intelligence, via useThreads
Framework-native persistenceFramework-internal state/checkpointsYour agent, e.g. a LangGraph AsyncPostgresSaver

A LangGraph checkpointer (an AsyncPostgresSaver + compile(checkpointer=...)) creates LangGraph's own checkpoint tables. It does not create a CopilotKit "threads" table, and you won't see a threads table appear just from configuring a checkpointer. Conversely, useThreads rename/archive/delete operate on CopilotKit threads and do not reach into LangGraph (or ADK, etc.) stores unless your backend explicitly bridges them.

The bridge between the two is the threadId: when you pass an explicit CopilotKit threadId, it's forwarded to the backend as the AG-UI threadId, which your framework can use directly as (or map to) its own checkpoint/thread id.

With CrewAI Flows, @persist stores the Flow's own state, and the CopilotKit threadId becomes the CrewAI session_id.

Future runs can remain durable in both places

Once Intelligence is connected, conversations that run through that runtime are recorded automatically in Intelligence. Historical import is optional. If your LangGraph agent continues using a durable checkpointer or LangGraph Platform, those same runs also continue through LangGraph's native persistence. The same applies to an ADK agent that remains connected to a durable session service with retained sessions. This lets you keep native framework storage and analytics while users get replay, generative UI, multimodal history, and realtime continuity through CopilotKit.

This is coordinated persistence during future CopilotKit-mediated runs, not general database replication. CopilotKit lifecycle actions such as rename, archive, and delete apply to the CopilotKit thread; they do not rename, archive, or delete records in the native framework store.

See LangGraph persistence for the framework-native (checkpointer) side, and Importing and synchronizing thread history for bringing existing framework conversations into the platform store. (LangGraph Platform requires thread ids to be UUIDs, which CopilotKit's auto-minted ids already are.)

Example: keep an existing LangGraph conversation

Follow Bring your own thread system for an example that keeps native persistence and continues the same conversation.

MCP Apps activity and history

MCP Apps render through activity messages (activityType: "mcp-apps"), and that rendering is a client-side concern: the registered renderer resolves the referenced UI resource and runs any follow-up in the browser. So the visible MCP App UI is re-derived on the client from the conversation when it loads. It isn't a separately-stored artifact you persist on its own.

Practically, MCP App UI restores the same way the rest of the conversation does: if your server-side store replays the thread's history (see server-side replay above), the tool-call/activity messages come back and the renderers run again on hydration. There's no separate MCP-Apps store to configure.

v1 vs v2

  • v2 (@copilotkit/react-core/v2): useThreads returns the CopilotKit thread list; threadId lives per-chat (on <CopilotChat> / <CopilotChatConfigurationProvider>), not on the provider; read messages via useAgent().agent.messages and mutate via agent.setMessages(...). No initialMessages.
  • v1 (@copilotkit/react-core): useThreads returns { threadId, setThreadId, isThreadIdExplicit } (a single-conversation id manager, not the platform list). Its setThreadId silently no-ops when a threadId prop is present, because the prop shadows internal state. <CopilotKit threadId> sets the id at the provider. (Separately, the setThreadId on the main <CopilotKit> hooks throws if you call it while threadId is prop-supplied.)

How is this guide?