Back to Copilotkit

useThreads

showcase/shell-docs/src/content/reference/vue/hooks/useThreads.mdx

1.61.18.4 KB
Original Source

<OpsPlatformCTA variant="card" title="useThreads needs an Enterprise Intelligence Platform project" body="Sign up for a free account to get a public license key and start syncing threads." ctaLabel="Create a free account" surface="docs_reference_vue_use_threads" />

Overview

useThreads is a Vue 3 composable for managing conversation threads on the Enterprise Intelligence Platform. It fetches the thread list for a given agent, keeps it synchronized in realtime via the core thread store's realtime channel, and exposes mutation methods for renaming, archiving, and deleting threads.

Threads are sorted by recency — by lastRunAt when present, falling back to updatedAt, then createdAt (most recent first). The composable supports cursor-based pagination when a limit is provided. All inputs accept refs, computeds, or getters (MaybeRefOrGetter), so changing the thread context reactively re-fetches the list.

<Callout type="info"> Return values are Vue refs and computeds. Read them with `.value` in `<script setup>`, or unwrap them automatically in `<template>`. </Callout>

Signature

ts
import { useThreads } from "@copilotkit/vue/v2";

function useThreads(input: UseThreadsInput): UseThreadsResult

Parameters

<PropertyReference name="input" type="UseThreadsInput"> Configuration object for the composable. Each field accepts a plain value, a ref, a computed, or a getter. <PropertyReference name="agentId" type="MaybeRefOrGetter<string>" required> The ID of the agent whose threads to list. Must match an agent configured in your runtime. </PropertyReference> <PropertyReference name="includeArchived" type="MaybeRefOrGetter<boolean | undefined>" default="false"> Whether to include archived threads in the list. </PropertyReference> <PropertyReference name="limit" type="MaybeRefOrGetter<number | undefined>" default="undefined"> Maximum number of threads to fetch per page. When set, enables cursor-based pagination via `fetchMoreThreads()` and `hasMoreThreads`. </PropertyReference> </PropertyReference>

Return Value

<PropertyReference name="result" type="UseThreadsResult">

State

<PropertyReference name="threads" type="Ref<Thread[]>"> Reactive array of threads for the current user and agent, sorted by recency — by `lastRunAt` when present, falling back to `updatedAt`, then `createdAt` (most recent first). Each `Thread` contains: - `id: string` -- unique thread identifier - `agentId: string` -- the agent this thread belongs to - `name: string | null` -- thread name (auto-generated by the LLM on first run, or set manually via `renameThread`) - `archived: boolean` -- whether the thread is archived - `createdAt: string` -- ISO 8601 timestamp - `updatedAt: string` -- ISO 8601 timestamp - `lastRunAt?: string` -- ISO 8601 timestamp of the most recent run on this thread. Only present when the thread has had at least one run. Prefer this over `updatedAt` for user-facing "last activity" displays, since `updatedAt` also bumps on metadata changes like rename or archive. </PropertyReference> <PropertyReference name="isLoading" type="Ref<boolean>"> `true` while the initial thread list is being fetched (including the pre-connect window before the runtime reports Connected). </PropertyReference> <PropertyReference name="error" type="Ref<Error | null>"> The most recent error from fetching or mutating threads, or `null` if no error has occurred. Also reports a configuration error when no runtime URL is set. </PropertyReference> <PropertyReference name="hasMoreThreads" type="Ref<boolean>"> `true` when more threads are available beyond the current page. Only meaningful when `limit` is set. </PropertyReference> <PropertyReference name="isFetchingMoreThreads" type="Ref<boolean>"> `true` while additional threads are being fetched. </PropertyReference>

Methods

<PropertyReference name="fetchMoreThreads" type="() => void"> Fetch the next page of threads. No-op when `hasMoreThreads` is `false`. Calling it again while a fetch is in flight cancels and replaces the in-flight request. </PropertyReference> <PropertyReference name="renameThread" type="(threadId: string, name: string) => Promise<void>"> Rename a thread. The promise resolves when the server confirms the operation, or rejects with an `Error` on failure. </PropertyReference> <PropertyReference name="archiveThread" type="(threadId: string) => Promise<void>"> Soft-delete a thread. The thread remains in the database with `archived: true` but is excluded from the list unless `includeArchived` is `true`. The promise resolves on server confirmation, or rejects with an `Error` on failure. There is no built-in confirmation dialog, so implement your own if needed. </PropertyReference> <PropertyReference name="deleteThread" type="(threadId: string) => Promise<void>"> Permanently and irreversibly delete a thread. The thread record is removed from the database entirely. The promise resolves on server confirmation, or rejects with an `Error` on failure. There is no built-in confirmation dialog, so implement your own if needed. </PropertyReference> </PropertyReference>

Usage

vue
<script setup lang="ts">
import { useThreads } from "@copilotkit/vue/v2"; // [!code highlight]

const {
  threads,
  isLoading,
  renameThread,
  archiveThread,
  deleteThread,
} = useThreads({ agentId: "my-agent" }); // [!code highlight]
</script>

<template>
  <div v-if="isLoading">Loading threads...</div>
  <ul v-else>
    <li v-for="thread in threads" :key="thread.id">
      <span>{{ thread.name ?? "Untitled" }}</span>
      <button @click="renameThread(thread.id, 'New name')">Rename</button>
      <button @click="archiveThread(thread.id)">Archive</button>
      <button @click="deleteThread(thread.id)">Delete</button>
    </li>
  </ul>
</template>

Reactive agent context

Because inputs accept refs and getters, you can drive the thread list from reactive state. Switching agentId automatically re-fetches the list.

vue
<script setup lang="ts">
import { ref } from "vue";
import { useThreads } from "@copilotkit/vue/v2";

const agentId = ref("support-agent");
const includeArchived = ref(false);

const { threads, hasMoreThreads, fetchMoreThreads } = useThreads({
  agentId, // ref -- changing it re-fetches threads
  includeArchived,
  limit: 20,
});
</script>

<template>
  <select v-model="agentId">
    <option value="support-agent">Support</option>
    <option value="sales-agent">Sales</option>
  </select>

  <label>
    <input type="checkbox" v-model="includeArchived" />
    Show archived
  </label>

  <ul>
    <li v-for="thread in threads" :key="thread.id">
      {{ thread.name ?? "Untitled" }}
    </li>
  </ul>

  <button v-if="hasMoreThreads" @click="fetchMoreThreads">Load more</button>
</template>

Behavior

  • On mount, fetches the thread list and establishes a realtime subscription via the core thread store.
  • Thread creates, renames, archives, and deletes from any client are reflected immediately without polling.
  • All mutation methods use pessimistic updates: the list updates only after the server confirms the operation, not immediately on dispatch. Promises resolve on confirmation and reject on failure.
  • The composable defers its first fetch until the runtime reports a Connected status, so it issues a single list request plus a single subscribe request rather than refetching once realtime details resolve.
  • While the runtime is connecting (a runtime URL is set but no context has been dispatched yet), isLoading stays true to avoid an empty-list flash.
  • When no runtime URL is configured, error reports a configuration error and the thread store is cleared.
  • The threads array stays sorted by recency descending — by lastRunAt when present, falling back to updatedAt, then createdAt.
  • New threads are automatically named by the LLM after their first run (a 2 to 5 word title). This is configurable via generateThreadNames on the runtime.
  • The composable cleans up its store subscriptions and stops the store automatically when the owning scope is disposed (onScopeDispose).

Next steps

<Cards> <Card title="CopilotKitProvider" href="/reference/vue/components/CopilotKitProvider"> Configure the runtime URL and license key that power thread syncing. </Card> <Card title="useAgent" href="/reference/vue/hooks/useAgent"> Access and run the agent whose threads you are listing. </Card> </Cards>