{"version":3,"file":"use-threads.cjs","names":["useCopilotKit","ɵselectThreads","ɵselectThreadsIsLoading","ɵselectThreadsError","ɵselectHasNextPage","ɵselectIsFetchingNextPage"],"sources":["../../src/hooks/use-threads.tsx"],"sourcesContent":["import { useCopilotKit } from \"@/providers/CopilotKitProvider\";\nimport {\n  ɵcreateThreadStore,\n  ɵselectThreads,\n  ɵselectThreadsError,\n  ɵselectThreadsIsLoading,\n  ɵselectHasNextPage,\n  ɵselectIsFetchingNextPage,\n  type ɵThread as CoreThread,\n  type ɵThreadRuntimeContext,\n  type ɵThreadStore,\n} from \"@copilotkitnext/core\";\nimport {\n  useCallback,\n  useEffect,\n  useMemo,\n  useState,\n  useSyncExternalStore,\n} from \"react\";\n\n/**\n * A conversation thread managed by the Intelligence platform.\n *\n * Each thread has a unique `id`, an optional human-readable `name`, and\n * timestamp fields tracking creation and update times.\n */\nexport interface Thread extends CoreThread {}\n\n/**\n * Configuration for the {@link useThreads} hook.\n *\n * Thread operations are scoped to the runtime-authenticated user and the\n * provided agent on the Intelligence platform.\n */\nexport interface UseThreadsInput {\n  /** The ID of the agent whose threads to list and manage. */\n  agentId: string;\n  /** When `true`, archived threads are included in the list. Defaults to `false`. */\n  includeArchived?: boolean;\n  /** Maximum number of threads to fetch per page. When set, enables cursor-based pagination. */\n  limit?: number;\n}\n\n/**\n * Return value of the {@link useThreads} hook.\n *\n * The `threads` array is kept in sync with the platform via a realtime\n * WebSocket subscription (when available) and is sorted most-recently-updated\n * first. Mutations reject with an `Error` if the platform request fails.\n */\nexport interface UseThreadsResult {\n  /**\n   * Threads for the current user/agent pair, sorted by most recently\n   * updated first. Updated in realtime when the platform pushes metadata\n   * events. Includes archived threads only when `includeArchived` is set.\n   */\n  threads: Thread[];\n  /**\n   * `true` while the initial thread list is being fetched from the platform.\n   * Subsequent realtime updates do not re-enter the loading state.\n   */\n  isLoading: boolean;\n  /**\n   * The most recent error from fetching threads or executing a mutation,\n   * or `null` when there is no error. Reset to `null` on the next\n   * successful fetch.\n   */\n  error: Error | null;\n  /**\n   * `true` when there are more threads available to fetch via\n   * {@link fetchNextPage}. Only meaningful when `limit` is set.\n   */\n  hasNextPage: boolean;\n  /**\n   * `true` while a subsequent page of threads is being fetched.\n   */\n  isFetchingNextPage: boolean;\n  /**\n   * Fetch the next page of threads. No-op when {@link hasNextPage} is\n   * `false` or a page fetch is already in progress.\n   */\n  fetchNextPage: () => void;\n  /**\n   * Rename a thread on the platform.\n   * Resolves when the server confirms the update; rejects on failure.\n   */\n  renameThread: (threadId: string, name: string) => Promise<void>;\n  /**\n   * Archive a thread on the platform.\n   * Archived threads are excluded from subsequent list results.\n   * Resolves when the server confirms the update; rejects on failure.\n   */\n  archiveThread: (threadId: string) => Promise<void>;\n  /**\n   * Permanently delete a thread from the platform.\n   * This is irreversible. Resolves when the server confirms deletion;\n   * rejects on failure.\n   */\n  deleteThread: (threadId: string) => Promise<void>;\n}\n\nfunction useThreadStoreSelector<T>(\n  store: ɵThreadStore,\n  selector: (state: ReturnType<ɵThreadStore[\"getState\"]>) => T,\n): T {\n  return useSyncExternalStore(\n    useCallback(\n      (onStoreChange) => {\n        const subscription = store.select(selector).subscribe(onStoreChange);\n        return () => subscription.unsubscribe();\n      },\n      [store, selector],\n    ),\n    () => selector(store.getState()),\n  );\n}\n\n/**\n * React hook for listing and managing Intelligence platform threads.\n *\n * On mount the hook fetches the thread list for the runtime-authenticated user\n * and the given `agentId`. When the Intelligence platform exposes a WebSocket\n * URL, it also opens a realtime subscription so the `threads` array stays\n * current without polling — thread creates, renames, archives, and deletes\n * from any client are reflected immediately.\n *\n * Mutation methods (`renameThread`, `archiveThread`, `deleteThread`) return\n * promises that resolve once the platform confirms the operation and reject\n * with an `Error` on failure.\n *\n * @param input - Agent identifier and optional list controls.\n * @returns Thread list state and stable mutation callbacks.\n *\n * @example\n * ```tsx\n * import { useThreads } from \"@copilotkitnext/react\";\n *\n * function ThreadList() {\n *   const { threads, isLoading, renameThread, deleteThread } = useThreads({\n *     agentId: \"agent-1\",\n *   });\n *\n *   if (isLoading) return <p>Loading…</p>;\n *\n *   return (\n *     <ul>\n *       {threads.map((t) => (\n *         <li key={t.id}>\n *           {t.name ?? \"Untitled\"}\n *           <button onClick={() => renameThread(t.id, \"New name\")}>Rename</button>\n *           <button onClick={() => deleteThread(t.id)}>Delete</button>\n *         </li>\n *       ))}\n *     </ul>\n *   );\n * }\n * ```\n */\nexport function useThreads({\n  agentId,\n  includeArchived,\n  limit,\n}: UseThreadsInput): UseThreadsResult {\n  const { copilotkit } = useCopilotKit();\n\n  const [store] = useState(() =>\n    ɵcreateThreadStore({\n      fetch: globalThis.fetch,\n    }),\n  );\n\n  const threads = useThreadStoreSelector(store, ɵselectThreads);\n  const storeIsLoading = useThreadStoreSelector(store, ɵselectThreadsIsLoading);\n  const storeError = useThreadStoreSelector(store, ɵselectThreadsError);\n  const hasNextPage = useThreadStoreSelector(store, ɵselectHasNextPage);\n  const isFetchingNextPage = useThreadStoreSelector(\n    store,\n    ɵselectIsFetchingNextPage,\n  );\n  const headersKey = useMemo(() => {\n    return JSON.stringify(\n      Object.entries(copilotkit.headers ?? {}).sort(([left], [right]) =>\n        left.localeCompare(right),\n      ),\n    );\n  }, [copilotkit.headers]);\n  const runtimeError = useMemo(() => {\n    if (copilotkit.runtimeUrl) {\n      return null;\n    }\n\n    return new Error(\"Runtime URL is not configured\");\n  }, [copilotkit.runtimeUrl]);\n  const isLoading = runtimeError ? false : storeIsLoading;\n  const error = runtimeError ?? storeError;\n\n  useEffect(() => {\n    store.start();\n    return () => {\n      store.stop();\n    };\n  }, [store]);\n\n  useEffect(() => {\n    const context: ɵThreadRuntimeContext | null = copilotkit.runtimeUrl\n      ? {\n          runtimeUrl: copilotkit.runtimeUrl,\n          headers: { ...copilotkit.headers },\n          wsUrl: copilotkit.intelligence?.wsUrl,\n          agentId,\n          includeArchived,\n          limit,\n        }\n      : null;\n\n    store.setContext(context);\n  }, [\n    store,\n    copilotkit.runtimeUrl,\n    headersKey,\n    copilotkit.intelligence?.wsUrl,\n    agentId,\n    copilotkit.headers,\n    includeArchived,\n    limit,\n  ]);\n\n  const renameThread = useCallback(\n    (threadId: string, name: string) => store.renameThread(threadId, name),\n    [store],\n  );\n\n  const archiveThread = useCallback(\n    (threadId: string) => store.archiveThread(threadId),\n    [store],\n  );\n\n  const deleteThread = useCallback(\n    (threadId: string) => store.deleteThread(threadId),\n    [store],\n  );\n\n  const fetchNextPage = useCallback(() => store.fetchNextPage(), [store]);\n\n  return {\n    threads,\n    isLoading,\n    error,\n    hasNextPage,\n    isFetchingNextPage,\n    fetchNextPage,\n    renameThread,\n    archiveThread,\n    deleteThread,\n  };\n}\n"],"mappings":";;;;;;AAqGA,SAAS,uBACP,OACA,UACG;AACH,gEAEK,kBAAkB;EACjB,MAAM,eAAe,MAAM,OAAO,SAAS,CAAC,UAAU,cAAc;AACpE,eAAa,aAAa,aAAa;IAEzC,CAAC,OAAO,SAAS,CAClB,QACK,SAAS,MAAM,UAAU,CAAC,CACjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CH,SAAgB,WAAW,EACzB,SACA,iBACA,SACoC;CACpC,MAAM,EAAE,eAAeA,0CAAe;CAEtC,MAAM,CAAC,gFACc,EACjB,OAAO,WAAW,OACnB,CAAC,CACH;CAED,MAAM,UAAU,uBAAuB,OAAOC,oCAAe;CAC7D,MAAM,iBAAiB,uBAAuB,OAAOC,6CAAwB;CAC7E,MAAM,aAAa,uBAAuB,OAAOC,yCAAoB;CACrE,MAAM,cAAc,uBAAuB,OAAOC,wCAAmB;CACrE,MAAM,qBAAqB,uBACzB,OACAC,+CACD;CACD,MAAM,sCAA2B;AAC/B,SAAO,KAAK,UACV,OAAO,QAAQ,WAAW,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,WACtD,KAAK,cAAc,MAAM,CAC1B,CACF;IACA,CAAC,WAAW,QAAQ,CAAC;CACxB,MAAM,wCAA6B;AACjC,MAA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