# 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? [#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.

<IntelligenceOnboardingPrompt
  feature="threads"
  surface="docs_threads"
/>

<Callout type="info" title="Prebuilt thread UI: Threads Drawer">
  If your app came from a CopilotKit CLI starter, it already includes the
  prebuilt **[Threads Drawer](/llamaindex/prebuilt-components/copilot-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).
</Callout>

## When should I use this? [#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 [#prerequisites]

- A CopilotKit application connected to CopilotKit Intelligence
- `@copilotkit/react-core` v1.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](/llamaindex/threads-lifecycle#scope-rich-threads-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](/llamaindex/threads-import).

## Implementation [#implementation]

<Steps>
      <Step>
        ### Configure your Runtime with CopilotKit Intelligence [#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](/llamaindex/intelligence/quickstart).

        ```typescript title="server.ts"
        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. |
      </Step>

      <Step>
        ### List and manage threads with useThreads [#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.

        ```tsx title="ThreadSidebar.tsx"
        import { useThreads } from "@copilotkit/react-core/v2"; // [!code highlight]

        function ThreadSidebar({
          onSelectThread,
        }: {
          onSelectThread: (threadId: string) => void;
        }) {
          const { // [!code highlight:6]
            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.
      </Step>

      <Step>
        ### Switch between threads [#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.

        ```tsx title="App.tsx"
        import { CopilotChat } from "@copilotkit/react-core/v2"; // [!code highlight]
        import { useState } from "react";

        function App() {
          const [activeThreadId, setActiveThreadId] = useState<string | undefined>();

          return (
            <div className="flex">
              <ThreadSidebar onSelectThread={setActiveThreadId} />
              <CopilotChat threadId={activeThreadId} /> {/* [!code highlight] */}
            </div>
          );
        }
        ```

      </Step>

      <Step>
        ### Add pagination for large thread lists [#add-pagination-for-large-thread-lists]

        For users with many conversations, use the `limit` parameter to enable cursor-based pagination.

        ```tsx title="ThreadSidebar.tsx"
        const {
          threads,
          hasMoreThreads,
          isFetchingMoreThreads,
          fetchMoreThreads,
        } = useThreads({
          agentId: "default",
          limit: 20, // [!code highlight]
        });

        // In your JSX:
        {hasMoreThreads && (
          <button
            onClick={fetchMoreThreads}
            disabled={isFetchingMoreThreads}
          >
            {isFetchingMoreThreads ? "Loading..." : "Load more"}
          </button>
        )}
        ```
      </Step>

      <Step>
        ### Check the thread list [#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.
      </Step>
</Steps>

## Driving one agent per thread [#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`:

```tsx
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.

<Callout type="warn">
  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](/reference/hooks/useAgent) for the full rules.
</Callout>

## Next steps [#next-steps]

- **Prebuilt UI:** [Threads Drawer](/llamaindex/prebuilt-components/copilot-threads-drawer): the drop-in thread switcher ([React reference](/reference/components/CopilotThreadsDrawer))
- **Thread architecture:** [AG-UI Streams & Framework Threads](/llamaindex/intelligence/threads-explained): event replay model and WebSocket sync
- **Production self-hosting:** [Self-host CopilotKit Intelligence](/llamaindex/intelligence/self-hosting): run the Threads platform inside your infrastructure with CopilotKit Engineering
- **API reference:** [useThreads](/reference/hooks/useThreads): parameters, return values, types
- **API reference:** [useAgent](/reference/hooks/useAgent): including the thread-scoped shape above
