Headless Threads
Build a custom thread UI with useThreads while CopilotKit handles persistence, replay, synchronization, and lifecycle infrastructure.
Your users want to see their saved conversations in your own layout and switch between them. useThreads gives you the list and the actions on it. Pass the selected threadId to your chat.
What is this?
The useThreads hook lists, creates, renames, archives, and deletes CopilotKit Intelligence threads with realtime synchronization via WebSocket. Threads work with any agent framework. CopilotKit Intelligence stores conversation history server-side, so users can close their browser and pick up where they left off. It does not list or mutate native LangGraph, ADK, or other framework stores unless your backend explicitly bridges those systems. Thread metadata updates (renames, archives, new threads) appear on connected clients without polling.
Conversations that never lose context.
Open your coding agent in your project's folder, or in an empty folder for a new app.This runs in a coding agent on your computer.
CopilotKit Intelligence AG-UI Streams keep messages, generative UI, and tool activity available across sessions and devices. Build a new agent or bring one you already have. Any frontend, any backend.
Prebuilt thread UI: Threads Drawer
If your app came from a CopilotKit CLI starter, it already includes the
prebuilt Threads Drawer.
Keep it for the shortest path to a production thread switcher. Use the
useThreads steps below when adding a custom thread UI to an existing app or
replacing the Drawer with your own layout and interactions (including thread
rename, which the prebuilt Drawer doesn't surface).
When should I use this?
- Your app needs multiple saved conversations per user (like a chat history sidebar)
- Users should be able to resume a prior conversation across sessions or devices
- You want realtime sync so threads created on one tab appear on another
- You need to let users organize conversations by renaming or archiving them
Prerequisites
- A CopilotKit application connected to CopilotKit Intelligence
@copilotkit/react-corev1.56 or later- A model provider key supported by your runtime
For multi-user applications, configure the Runtime to scope AG-UI Streams to the signed-in user before exposing thread lists or lifecycle actions.
Already have threads in LangGraph, ADK, Mastra, or Strands? See Add AG-UI Streams to Existing Threads.
Implementation
Configure your Runtime with CopilotKit Intelligence
The thread UI lists and resumes conversations only when CopilotRuntime is connected to Intelligence. Connect it with the intelligence option. CLI starters already include it. For the full setup, see Connect your runtime to Intelligence.
import {
CopilotKitIntelligence,
CopilotRuntime,
} from "@copilotkit/runtime/v2";
const runtime = new CopilotRuntime({
agents: {
default: agent,
},
// Without `intelligence` the runtime runs in SSE mode and the thread
// UI has nothing to list — chat still works, so this fails quietly.
intelligence: new CopilotKitIntelligence({
apiKey: process.env.CPK_INTELLIGENCE_API_KEY!,
}),
// Required alongside `intelligence`: threads are scoped per user, and
// the runtime throws at startup without it. Resolve the real
// signed-in user — see Thread & History Lifecycle.
identifyUser: async (request) => {
const session = await verifyAppSession(request);
if (!session?.user) throw new Error("Unauthorized");
return { id: session.user.id, name: session.user.name };
},
// Each new thread is named from its first user message.
// For a short title from a model, pass { model: "openai/gpt-5-mini" }.
// Set to false to disable:
// generateThreadNames: false,
// Optional: tune thread lock behavior
// lockTtlSeconds: 20, // Lock TTL (default 20s, max 3600s)
// lockHeartbeatIntervalSeconds: 15, // Heartbeat interval (default 15s, max 3000s)
// lockKeyPrefix: "my-app", // Custom Redis key prefix for the lock
});Keep CPK_INTELLIGENCE_API_KEY on the server.
Thread lock options: When an agent run starts, the runtime acquires a lock on the thread to prevent concurrent runs. You can tune this behavior:
| Option | Default | Max | Description |
|---|---|---|---|
lockTtlSeconds | 20 | 3600 (1 hour) | How long the lock is held before it expires automatically. |
lockHeartbeatIntervalSeconds | 15 | 3000 (50 min) | How often the runtime renews the lock during a run. |
lockKeyPrefix | None | None | Custom Redis key prefix for the thread lock. Useful when multiple apps share a Redis instance. |
List and manage threads with useThreads
Use the useThreads hook to fetch and manage threads for a specific agent. The hook returns the thread list, loading state, and mutation methods.
import { useThreads } from "@copilotkit/react-core/v2";
function ThreadSidebar({
onSelectThread,
}: {
onSelectThread: (threadId: string) => void;
}) {
const {
threads,
isLoading,
renameThread,
archiveThread,
deleteThread,
} = useThreads({ agentId: "default" });
if (isLoading) return <div>Loading...</div>;
return (
<div>
{threads.map((thread) => (
<div key={thread.id}>
<button onClick={() => onSelectThread(thread.id)}>
{thread.name ?? "New conversation"}
</button>
<button onClick={() => renameThread(thread.id, "Renamed")}>
Rename
</button>
<button onClick={() => archiveThread(thread.id)}>
Archive
</button>
</div>
))}
</div>
);
}The threads array is sorted by most recently updated first and stays synchronized in realtime. New threads from other tabs or devices appear automatically.
Archive vs. delete: archiveThread is a soft delete: the thread stays in the database but is hidden from the list by default. Pass includeArchived: true to show archived threads. deleteThread is permanent and irreversible. Neither has a built-in confirmation dialog. If you need one, add your own.
Switch between threads
When a user selects a thread, pass its threadId to your chat component. The chat clears the current messages, fetches the selected thread's history, and replays it. If the agent is still running on that thread, the chat picks up the live stream.
import { CopilotChat } from "@copilotkit/react-core/v2";
import { useState } from "react";
function App() {
const [activeThreadId, setActiveThreadId] = useState<string | undefined>();
return (
<div className="flex">
<ThreadSidebar onSelectThread={setActiveThreadId} />
<CopilotChat threadId={activeThreadId} />
</div>
);
}Add pagination for large thread lists
For users with many conversations, use the limit parameter to enable cursor-based pagination.
const {
threads,
hasMoreThreads,
isFetchingMoreThreads,
fetchMoreThreads,
} = useThreads({
agentId: "default",
limit: 20,
});
// In your JSX:
{hasMoreThreads && (
<button
onClick={fetchMoreThreads}
disabled={isFetchingMoreThreads}
>
{isFetchingMoreThreads ? "Loading..." : "Load more"}
</button>
)}Check the thread list
Open your app in two browser tabs and send a message in one. The new thread appears in the other tab's sidebar. Click it, and the chat loads that conversation.
Driving one agent per thread
useThreads lists and switches threads. To read or run an agent scoped to a
specific thread (for example, one open tab per thread), pass all three of
agentId, runtimeAgentId and threadId to useAgent:
const { agent } = useAgent({
agentId: `chat-${threadId}`, // local id, unique per mounted thread
runtimeAgentId: "default", // the one runtime agent they all route to
threadId, // the thread this instance is pinned to
});This registers a private proxied agent per hook, so several threads can be
mounted at once against a single runtime agent. agent.runAgent() then
addresses that thread.
The three properties are a matched set and partial combinations do not
compile. In particular useAgent({ agentId, threadId }) is a type error: a
runtime agent is a singleton, so pinning a thread directly onto it would let
two hooks sharing an agentId overwrite each other's thread. See the
useAgent reference for the full rules.
Next steps
- Prebuilt UI: Threads Drawer: the drop-in thread switcher (React reference)
- Thread architecture: AG-UI Streams & Framework Threads: event replay model and WebSocket sync
- Production self-hosting: Self-host CopilotKit Intelligence: run the Threads platform inside your infrastructure with CopilotKit Engineering
- API reference: useThreads: parameters, return values, types
- API reference: useAgent: including the thread-scoped shape above
How is this guide?