@langchain/react 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"suspense-stream.js","names":[],"sources":["../src/suspense-stream.tsx"],"sourcesContent":["/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */\n\n\"use client\";\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport type { ThreadState, BagTemplate } from \"@langchain/langgraph-sdk\";\nimport { Client, getClientConfigHash } from \"@langchain/langgraph-sdk/client\";\nimport type {\n UseStreamThread,\n ResolveStreamOptions,\n ResolveStreamInterface,\n InferBag,\n} from \"@langchain/langgraph-sdk/ui\";\nimport { useStreamLGP } from \"./stream.lgp.js\";\nimport type { WithClassMessages } from \"./stream.js\";\n\n// ---------------------------------------------------------------------------\n// Suspense cache\n// ---------------------------------------------------------------------------\n\nexport type SuspenseCacheEntry<T> =\n | { status: \"pending\"; promise: Promise<void> }\n | { status: \"resolved\"; data: T }\n | { status: \"rejected\"; error: unknown };\n\nexport type SuspenseCache = Map<string, SuspenseCacheEntry<unknown>>;\n\nconst defaultSuspenseCache: SuspenseCache = new Map();\n\nexport function createSuspenseCache(): SuspenseCache {\n return new Map();\n}\n\nfunction getCacheKey(\n client: Client,\n threadId: string,\n limit: boolean | number,\n): string {\n return `suspense:${getClientConfigHash(client)}:${threadId}:${limit}`;\n}\n\nfunction fetchThreadHistory<StateType extends Record<string, unknown>>(\n client: Client,\n threadId: string,\n options?: { limit?: boolean | number },\n): Promise<ThreadState<StateType>[]> {\n if (options?.limit === false) {\n return client.threads.getState<StateType>(threadId).then((state) => {\n if (state.checkpoint == null) return [];\n return [state];\n });\n }\n\n const limit = typeof options?.limit === \"number\" ? options.limit : 10;\n return client.threads.getHistory<StateType>(threadId, { limit });\n}\n\nfunction getOrCreateCacheEntry<StateType extends Record<string, unknown>>(\n cache: SuspenseCache,\n client: Client,\n threadId: string,\n limit: boolean | number,\n): SuspenseCacheEntry<ThreadState<StateType>[]> {\n const key = getCacheKey(client, threadId, limit);\n let entry = cache.get(key) as\n | SuspenseCacheEntry<ThreadState<StateType>[]>\n | undefined;\n\n if (!entry) {\n // Start fetch. The promise always resolves (never rejects) so React\n // Suspense correctly waits for it and then retries the render.\n const promise = fetchThreadHistory<StateType>(client, threadId, { limit })\n .then((data) => {\n cache.set(key, { status: \"resolved\", data });\n })\n .catch((error: unknown) => {\n cache.set(key, { status: \"rejected\", error });\n });\n\n entry = { status: \"pending\", promise };\n cache.set(key, entry);\n }\n\n return entry;\n}\n\n/**\n * Clear the internal Suspense cache used by {@link useSuspenseStream}.\n *\n * Call this from an Error Boundary's `onReset` callback so that a retry\n * triggers a fresh thread-history fetch rather than re-throwing the\n * cached error.\n *\n * @example\n * ```tsx\n * <ErrorBoundary\n * onReset={() => invalidateSuspenseCache()}\n * fallbackRender={({ resetErrorBoundary }) => (\n * <button onClick={resetErrorBoundary}>Retry</button>\n * )}\n * >\n * <Suspense fallback={<Spinner />}>\n * <Chat />\n * </Suspense>\n * </ErrorBoundary>\n * ```\n */\nexport function invalidateSuspenseCache(\n cache: SuspenseCache = defaultSuspenseCache,\n): void {\n cache.clear();\n}\n\n// ---------------------------------------------------------------------------\n// Return-type helper\n// ---------------------------------------------------------------------------\n\ntype WithSuspense<T> = Omit<T, \"isLoading\" | \"error\" | \"isThreadLoading\"> & {\n isStreaming: boolean;\n};\n\ntype UseSuspenseStreamOptions<\n T = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n> = ResolveStreamOptions<T, InferBag<T, Bag>> & {\n /**\n * Optional cache store used by Suspense history prefetching.\n * Provide a custom cache in tests to avoid cross-test cache sharing.\n */\n suspenseCache?: SuspenseCache;\n};\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * A Suspense-compatible variant of {@link useStream} for LangGraph Platform.\n *\n * `useSuspenseStream` suspends the component while the initial thread\n * history is being fetched and throws errors to the nearest React Error\n * Boundary. During active streaming the component stays rendered and\n * `isStreaming` indicates whether tokens are arriving.\n *\n * @example\n * ```tsx\n * <ErrorBoundary fallback={<ErrorDisplay />}>\n * <Suspense fallback={<Spinner />}>\n * <Chat />\n * </Suspense>\n * </ErrorBoundary>\n *\n * function Chat() {\n * const { messages, submit, isStreaming } = useSuspenseStream({\n * assistantId: \"agent\",\n * apiUrl: \"http://localhost:2024\",\n * });\n * return <MessageList messages={messages} />;\n * }\n * ```\n *\n * @template T - Either a ReactAgent / DeepAgent type or a state record type.\n * @template Bag - Type configuration bag (ConfigurableType, InterruptType, …).\n */\nexport function useSuspenseStream<\n T = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(\n options: UseSuspenseStreamOptions<T, InferBag<T, Bag>>,\n): WithClassMessages<WithSuspense<ResolveStreamInterface<T, InferBag<T, Bag>>>>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useSuspenseStream(options: any): any {\n type StateType = Record<string, unknown>;\n const cache: SuspenseCache = options.suspenseCache ?? defaultSuspenseCache;\n\n // ---- client (needed before useStreamLGP for cache key derivation) ----\n const client = useMemo(\n () =>\n options.client ??\n new Client({\n apiUrl: options.apiUrl,\n apiKey: options.apiKey,\n callerOptions: options.callerOptions,\n defaultHeaders: options.defaultHeaders,\n }),\n [\n options.client,\n options.apiKey,\n options.apiUrl,\n options.callerOptions,\n options.defaultHeaders,\n ],\n );\n\n const { threadId } = options;\n\n const historyLimit: boolean | number =\n typeof options.fetchStateHistory === \"object\" &&\n options.fetchStateHistory != null\n ? (options.fetchStateHistory.limit ?? false)\n : (options.fetchStateHistory ?? false);\n\n // Only manage history via the suspense cache when the caller hasn't\n // supplied an external `thread` and there's a threadId to load.\n const needsHistoryFetch = threadId != null && options.thread == null;\n\n // ---- suspense cache lookup (synchronous, may create fetch) ----\n let cacheEntry: SuspenseCacheEntry<ThreadState<StateType>[]> | undefined;\n\n if (needsHistoryFetch) {\n cacheEntry = getOrCreateCacheEntry<StateType>(\n cache,\n client,\n threadId,\n historyLimit,\n );\n }\n\n const cachedData =\n cacheEntry?.status === \"resolved\" ? cacheEntry.data : undefined;\n\n // ---- mutable ref so `mutate` always writes the freshest data ----\n const cachedDataRef = useRef(cachedData);\n if (cachedData != null) {\n cachedDataRef.current = cachedData;\n }\n\n // Re-render trigger after external mutate calls.\n const [, setMutateVersion] = useState(0);\n\n const mutate = useCallback(\n async (\n mutateId?: string,\n ): Promise<ThreadState<StateType>[] | null | undefined> => {\n const fetchId = mutateId ?? threadId;\n if (!fetchId) return undefined;\n try {\n const data = await fetchThreadHistory<StateType>(client, fetchId, {\n limit: historyLimit,\n });\n const key = getCacheKey(client, fetchId, historyLimit);\n cache.set(key, { status: \"resolved\", data });\n cachedDataRef.current = data;\n setMutateVersion((v) => v + 1);\n return data;\n } catch {\n return undefined;\n }\n },\n [cache, client, threadId, historyLimit],\n );\n\n // ---- build thread override for useStreamLGP ----\n const thread: UseStreamThread<StateType> | undefined = useMemo(() => {\n if (!needsHistoryFetch) return options.thread;\n return {\n data: cachedDataRef.current,\n error: undefined,\n isLoading: false,\n mutate,\n };\n // `cachedData` is included so the memo recomputes when the cache\n // transitions from pending → resolved across suspend/retry cycles.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [needsHistoryFetch, options.thread, cachedData, mutate]);\n\n // ---- delegate to useStreamLGP (must always run – Rules of Hooks) ----\n const stream = useStreamLGP({\n ...options,\n client,\n thread,\n });\n\n // ---- post-hook: suspend or throw ----\n\n // Suspend while thread history is loading, but only when the stream\n // itself is idle. If an active stream is running (e.g. the thread was\n // just created during submit), suspending would discard the stream\n // state, so we skip it.\n if (needsHistoryFetch && cacheEntry && !stream.isLoading) {\n if (cacheEntry.status === \"pending\") {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw cacheEntry.promise;\n }\n if (cacheEntry.status === \"rejected\") {\n // Clear cache so a subsequent retry (ErrorBoundary reset) starts\n // a fresh fetch instead of re-throwing the stale error.\n const key = getCacheKey(client, threadId!, historyLimit);\n cache.delete(key);\n // eslint-disable-next-line no-instanceof/no-instanceof\n throw cacheEntry.error instanceof Error\n ? cacheEntry.error\n : new Error(String(cacheEntry.error));\n }\n }\n\n // Throw non-streaming errors to the nearest Error Boundary.\n if (stream.error != null && !stream.isLoading) {\n // eslint-disable-next-line no-instanceof/no-instanceof\n throw stream.error instanceof Error\n ? stream.error\n : new Error(String(stream.error));\n }\n\n // Build return object explicitly to avoid triggering throwing getters\n // (e.g. `history` throws when `fetchStateHistory` is not set).\n return {\n get values() {\n return stream.values;\n },\n get messages() {\n return stream.messages;\n },\n get toolCalls() {\n return stream.toolCalls;\n },\n get toolProgress() {\n return stream.toolProgress;\n },\n getToolCalls: stream.getToolCalls.bind(stream),\n get interrupt() {\n return stream.interrupt;\n },\n get interrupts() {\n return stream.interrupts;\n },\n get subagents() {\n return stream.subagents;\n },\n get activeSubagents() {\n return stream.activeSubagents;\n },\n getSubagent: stream.getSubagent.bind(stream),\n getSubagentsByType: stream.getSubagentsByType.bind(stream),\n getSubagentsByMessage: stream.getSubagentsByMessage.bind(stream),\n getMessagesMetadata: stream.getMessagesMetadata.bind(stream),\n get history() {\n return stream.history;\n },\n get experimental_branchTree() {\n return stream.experimental_branchTree;\n },\n stop: stream.stop,\n submit: stream.submit,\n switchThread: stream.switchThread,\n joinStream: stream.joinStream,\n get branch() {\n return stream.branch;\n },\n setBranch: stream.setBranch,\n get client() {\n return stream.client;\n },\n get assistantId() {\n return stream.assistantId;\n },\n get queue() {\n return stream.queue;\n },\n get isStreaming() {\n return stream.isLoading;\n },\n };\n}\n"],"mappings":";;;;;AA2BA,MAAM,uCAAsC,IAAI,KAAK;AAErD,SAAgB,sBAAqC;AACnD,wBAAO,IAAI,KAAK;;AAGlB,SAAS,YACP,QACA,UACA,OACQ;AACR,QAAO,YAAY,oBAAoB,OAAO,CAAC,GAAG,SAAS,GAAG;;AAGhE,SAAS,mBACP,QACA,UACA,SACmC;AACnC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QACP,IAAI,MAAM,OAAO,OAAO,MAAM,CAAC;AAKrC,QAAO;EACL,IAAI,SAAS;AACX,UAAO,OAAO;;EAEhB,IAAI,WAAW;AACb,UAAO,OAAO;;EAEhB,IAAI,YAAY;AACd,UAAO,OAAO;;EAEhB,IAAI,eAAe;AACjB,UAAO,OAAO;;EAEhB,cAAc,OAAO,aAAa,KAAK,OAAO;EAC9C,IAAI,YAAY;AACd,UAAO,OAAO;;EAEhB,IAAI,aAAa;AACf,UAAO,OAAO;;EAEhB,IAAI,YAAY;AACd,UAAO,OAAO;;EAEhB,IAAI,kBAAkB;AACpB,UAAO,OAAO;;EAEhB,aAAa,OAAO,YAAY,KAAK,OAAO;EAC5C,oBAAoB,OAAO,mBAAmB,KAAK,OAAO;EAC1D,uBAAuB,OAAO,sBAAsB,KAAK,OAAO;EAChE,qBAAqB,OAAO,oBAAoB,KAAK,OAAO;EAC5D,IAAI,UAAU;AACZ,UAAO,OAAO;;EAEhB,IAAI,0BAA0B;AAC5B,UAAO,OAAO;;EAEhB,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,cAAc,OAAO;EACrB,YAAY,OAAO;EACnB,IAAI,SAAS;AACX,UAAO,OAAO;;EAEhB,WAAW,OAAO;EAClB,IAAI,SAAS;AACX,UAAO,OAAO;;EAEhB,IAAI,cAAc;AAChB,UAAO,OAAO;;EAEhB,IAAI,QAAQ;AACV,UAAO,OAAO;;EAEhB,IAAI,cAAc;AAChB,UAAO,OAAO;;EAEjB"}
1
+ {"version":3,"file":"suspense-stream.js","names":[],"sources":["../src/suspense-stream.tsx"],"sourcesContent":["/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */\n\n\"use client\";\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport type { ThreadState, BagTemplate } from \"@langchain/langgraph-sdk\";\nimport { Client, getClientConfigHash } from \"@langchain/langgraph-sdk/client\";\nimport type {\n UseStreamThread,\n ResolveStreamOptions,\n ResolveStreamInterface,\n InferBag,\n} from \"@langchain/langgraph-sdk/ui\";\nimport { useStreamLGP } from \"./stream.lgp.js\";\nimport type { WithClassMessages } from \"./stream.js\";\n\n// ---------------------------------------------------------------------------\n// Suspense cache\n// ---------------------------------------------------------------------------\n\nexport type SuspenseCacheEntry<T> =\n | { status: \"pending\"; promise: Promise<void> }\n | { status: \"resolved\"; data: T }\n | { status: \"rejected\"; error: unknown };\n\nexport type SuspenseCache = Map<string, SuspenseCacheEntry<unknown>>;\n\nconst defaultSuspenseCache: SuspenseCache = new Map();\n\nexport function createSuspenseCache(): SuspenseCache {\n return new Map();\n}\n\nfunction getCacheKey(\n client: Client,\n threadId: string,\n limit: boolean | number\n): string {\n return `suspense:${getClientConfigHash(client)}:${threadId}:${limit}`;\n}\n\nfunction fetchThreadHistory<StateType extends Record<string, unknown>>(\n client: Client,\n threadId: string,\n options?: { limit?: boolean | number }\n): Promise<ThreadState<StateType>[]> {\n if (options?.limit === false) {\n return client.threads.getState<StateType>(threadId).then((state) => {\n if (state.checkpoint == null) return [];\n return [state];\n });\n }\n\n const limit = typeof options?.limit === \"number\" ? options.limit : 10;\n return client.threads.getHistory<StateType>(threadId, { limit });\n}\n\nfunction getOrCreateCacheEntry<StateType extends Record<string, unknown>>(\n cache: SuspenseCache,\n client: Client,\n threadId: string,\n limit: boolean | number\n): SuspenseCacheEntry<ThreadState<StateType>[]> {\n const key = getCacheKey(client, threadId, limit);\n let entry = cache.get(key) as\n | SuspenseCacheEntry<ThreadState<StateType>[]>\n | undefined;\n\n if (!entry) {\n // Start fetch. The promise always resolves (never rejects) so React\n // Suspense correctly waits for it and then retries the render.\n const promise = fetchThreadHistory<StateType>(client, threadId, { limit })\n .then((data) => {\n cache.set(key, { status: \"resolved\", data });\n })\n .catch((error: unknown) => {\n cache.set(key, { status: \"rejected\", error });\n });\n\n entry = { status: \"pending\", promise };\n cache.set(key, entry);\n }\n\n return entry;\n}\n\n/**\n * Clear the internal Suspense cache used by {@link useSuspenseStream}.\n *\n * Call this from an Error Boundary's `onReset` callback so that a retry\n * triggers a fresh thread-history fetch rather than re-throwing the\n * cached error.\n *\n * @example\n * ```tsx\n * <ErrorBoundary\n * onReset={() => invalidateSuspenseCache()}\n * fallbackRender={({ resetErrorBoundary }) => (\n * <button onClick={resetErrorBoundary}>Retry</button>\n * )}\n * >\n * <Suspense fallback={<Spinner />}>\n * <Chat />\n * </Suspense>\n * </ErrorBoundary>\n * ```\n */\nexport function invalidateSuspenseCache(\n cache: SuspenseCache = defaultSuspenseCache\n): void {\n cache.clear();\n}\n\n// ---------------------------------------------------------------------------\n// Return-type helper\n// ---------------------------------------------------------------------------\n\ntype WithSuspense<T> = Omit<T, \"isLoading\" | \"error\" | \"isThreadLoading\"> & {\n isStreaming: boolean;\n};\n\ntype UseSuspenseStreamOptions<\n T = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n> = ResolveStreamOptions<T, InferBag<T, Bag>> & {\n /**\n * Optional cache store used by Suspense history prefetching.\n * Provide a custom cache in tests to avoid cross-test cache sharing.\n */\n suspenseCache?: SuspenseCache;\n};\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * A Suspense-compatible variant of {@link useStream} for LangGraph Platform.\n *\n * `useSuspenseStream` suspends the component while the initial thread\n * history is being fetched and throws errors to the nearest React Error\n * Boundary. During active streaming the component stays rendered and\n * `isStreaming` indicates whether tokens are arriving.\n *\n * @example\n * ```tsx\n * <ErrorBoundary fallback={<ErrorDisplay />}>\n * <Suspense fallback={<Spinner />}>\n * <Chat />\n * </Suspense>\n * </ErrorBoundary>\n *\n * function Chat() {\n * const { messages, submit, isStreaming } = useSuspenseStream({\n * assistantId: \"agent\",\n * apiUrl: \"http://localhost:2024\",\n * });\n * return <MessageList messages={messages} />;\n * }\n * ```\n *\n * @template T - Either a ReactAgent / DeepAgent type or a state record type.\n * @template Bag - Type configuration bag (ConfigurableType, InterruptType, …).\n */\nexport function useSuspenseStream<\n T = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(\n options: UseSuspenseStreamOptions<T, InferBag<T, Bag>>\n): WithClassMessages<WithSuspense<ResolveStreamInterface<T, InferBag<T, Bag>>>>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useSuspenseStream(options: any): any {\n type StateType = Record<string, unknown>;\n const cache: SuspenseCache = options.suspenseCache ?? defaultSuspenseCache;\n\n // ---- client (needed before useStreamLGP for cache key derivation) ----\n const client = useMemo(\n () =>\n options.client ??\n new Client({\n apiUrl: options.apiUrl,\n apiKey: options.apiKey,\n callerOptions: options.callerOptions,\n defaultHeaders: options.defaultHeaders,\n }),\n [\n options.client,\n options.apiKey,\n options.apiUrl,\n options.callerOptions,\n options.defaultHeaders,\n ]\n );\n\n const { threadId } = options;\n\n const historyLimit: boolean | number =\n typeof options.fetchStateHistory === \"object\" &&\n options.fetchStateHistory != null\n ? (options.fetchStateHistory.limit ?? false)\n : (options.fetchStateHistory ?? false);\n\n // Only manage history via the suspense cache when the caller hasn't\n // supplied an external `thread` and there's a threadId to load.\n const needsHistoryFetch = threadId != null && options.thread == null;\n\n // ---- suspense cache lookup (synchronous, may create fetch) ----\n let cacheEntry: SuspenseCacheEntry<ThreadState<StateType>[]> | undefined;\n\n if (needsHistoryFetch) {\n cacheEntry = getOrCreateCacheEntry<StateType>(\n cache,\n client,\n threadId,\n historyLimit\n );\n }\n\n const cachedData =\n cacheEntry?.status === \"resolved\" ? cacheEntry.data : undefined;\n\n // ---- mutable ref so `mutate` always writes the freshest data ----\n const cachedDataRef = useRef(cachedData);\n if (cachedData != null) {\n cachedDataRef.current = cachedData;\n }\n\n // Re-render trigger after external mutate calls.\n const [, setMutateVersion] = useState(0);\n\n const mutate = useCallback(\n async (\n mutateId?: string\n ): Promise<ThreadState<StateType>[] | null | undefined> => {\n const fetchId = mutateId ?? threadId;\n if (!fetchId) return undefined;\n try {\n const data = await fetchThreadHistory<StateType>(client, fetchId, {\n limit: historyLimit,\n });\n const key = getCacheKey(client, fetchId, historyLimit);\n cache.set(key, { status: \"resolved\", data });\n cachedDataRef.current = data;\n setMutateVersion((v) => v + 1);\n return data;\n } catch {\n return undefined;\n }\n },\n [cache, client, threadId, historyLimit]\n );\n\n // ---- build thread override for useStreamLGP ----\n const thread: UseStreamThread<StateType> | undefined = useMemo(() => {\n if (!needsHistoryFetch) return options.thread;\n return {\n data: cachedDataRef.current,\n error: undefined,\n isLoading: false,\n mutate,\n };\n // `cachedData` is included so the memo recomputes when the cache\n // transitions from pending → resolved across suspend/retry cycles.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [needsHistoryFetch, options.thread, cachedData, mutate]);\n\n // ---- delegate to useStreamLGP (must always run – Rules of Hooks) ----\n const stream = useStreamLGP({\n ...options,\n client,\n thread,\n });\n\n // ---- post-hook: suspend or throw ----\n\n // Suspend while thread history is loading, but only when the stream\n // itself is idle. If an active stream is running (e.g. the thread was\n // just created during submit), suspending would discard the stream\n // state, so we skip it.\n if (needsHistoryFetch && cacheEntry && !stream.isLoading) {\n if (cacheEntry.status === \"pending\") {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw cacheEntry.promise;\n }\n if (cacheEntry.status === \"rejected\") {\n // Clear cache so a subsequent retry (ErrorBoundary reset) starts\n // a fresh fetch instead of re-throwing the stale error.\n const key = getCacheKey(client, threadId!, historyLimit);\n cache.delete(key);\n // eslint-disable-next-line no-instanceof/no-instanceof\n throw cacheEntry.error instanceof Error\n ? cacheEntry.error\n : new Error(String(cacheEntry.error));\n }\n }\n\n // Throw non-streaming errors to the nearest Error Boundary.\n if (stream.error != null && !stream.isLoading) {\n // eslint-disable-next-line no-instanceof/no-instanceof\n throw stream.error instanceof Error\n ? stream.error\n : new Error(String(stream.error));\n }\n\n // Build return object explicitly to avoid triggering throwing getters\n // (e.g. `history` throws when `fetchStateHistory` is not set).\n return {\n get values() {\n return stream.values;\n },\n get messages() {\n return stream.messages;\n },\n get toolCalls() {\n return stream.toolCalls;\n },\n get toolProgress() {\n return stream.toolProgress;\n },\n getToolCalls: stream.getToolCalls.bind(stream),\n get interrupt() {\n return stream.interrupt;\n },\n get interrupts() {\n return stream.interrupts;\n },\n get subagents() {\n return stream.subagents;\n },\n get activeSubagents() {\n return stream.activeSubagents;\n },\n getSubagent: stream.getSubagent.bind(stream),\n getSubagentsByType: stream.getSubagentsByType.bind(stream),\n getSubagentsByMessage: stream.getSubagentsByMessage.bind(stream),\n getMessagesMetadata: stream.getMessagesMetadata.bind(stream),\n get history() {\n return stream.history;\n },\n get experimental_branchTree() {\n return stream.experimental_branchTree;\n },\n stop: stream.stop,\n submit: stream.submit,\n switchThread: stream.switchThread,\n joinStream: stream.joinStream,\n get branch() {\n return stream.branch;\n },\n setBranch: stream.setBranch,\n get client() {\n return stream.client;\n },\n get assistantId() {\n return stream.assistantId;\n },\n get queue() {\n return stream.queue;\n },\n get isStreaming() {\n return stream.isLoading;\n },\n };\n}\n"],"mappings":";;;;;AA2BA,MAAM,uCAAsC,IAAI,KAAK;AAErD,SAAgB,sBAAqC;AACnD,wBAAO,IAAI,KAAK;;AAGlB,SAAS,YACP,QACA,UACA,OACQ;AACR,QAAO,YAAY,oBAAoB,OAAO,CAAC,GAAG,SAAS,GAAG;;AAGhE,SAAS,mBACP,QACA,UACA,SACmC;AACnC,KAAI,SAAS,UAAU,MACrB,QAAO,OAAO,QAAQ,SAAoB,SAAS,CAAC,MAAM,UAAU;AAClE,MAAI,MAAM,cAAc,KAAM,QAAO,EAAE;AACvC,SAAO,CAAC,MAAM;GACd;CAGJ,MAAM,QAAQ,OAAO,SAAS,UAAU,WAAW,QAAQ,QAAQ;AACnE,QAAO,OAAO,QAAQ,WAAsB,UAAU,EAAE,OAAO,CAAC;;AAGlE,SAAS,sBACP,OACA,QACA,UACA,OAC8C;CAC9C,MAAM,MAAM,YAAY,QAAQ,UAAU,MAAM;CAChD,IAAI,QAAQ,MAAM,IAAI,IAAI;AAI1B,KAAI,CAAC,OAAO;AAWV,UAAQ;GAAE,QAAQ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oBAAoB,OAAO,mBAAmB,KAAK,OAAO;EAC1D,uBAAuB,OAAO,sBAAsB,KAAK,OAAO;EAChE,qBAAqB,OAAO,oBAAoB,KAAK,OAAO;EAC5D,IAAI,UAAU;AACZ,UAAO,OAAO;;EAEhB,IAAI,0BAA0B;AAC5B,UAAO,OAAO;;EAEhB,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,cAAc,OAAO;EACrB,YAAY,OAAO;EACnB,IAAI,SAAS;AACX,UAAO,OAAO;;EAEhB,WAAW,OAAO;EAClB,IAAI,SAAS;AACX,UAAO,OAAO;;EAEhB,IAAI,cAAc;AAChB,UAAO,OAAO;;EAEhB,IAAI,QAAQ;AACV,UAAO,OAAO;;EAEhB,IAAI,cAAc;AAChB,UAAO,OAAO;;EAEjB"}
@@ -1 +1 @@
1
- {"version":3,"file":"thread.cjs","names":[],"sources":["../src/thread.tsx"],"sourcesContent":["\"use client\";\n\nimport { useState, useRef, useCallback } from \"react\";\n\nexport const useControllableThreadId = (options?: {\n threadId?: string | null;\n onThreadId?: (threadId: string) => void;\n}): [string | null, (threadId: string | null) => void] => {\n const [localThreadId, _setLocalThreadId] = useState<string | null>(\n options?.threadId ?? null,\n );\n\n const onThreadIdRef = useRef(options?.onThreadId);\n onThreadIdRef.current = options?.onThreadId;\n\n const setThreadId = useCallback((threadId: string | null) => {\n _setLocalThreadId(threadId);\n if (threadId != null) onThreadIdRef.current?.(threadId);\n }, []);\n\n if (!options || !(\"threadId\" in options)) {\n return [localThreadId, setThreadId];\n }\n\n return [options.threadId ?? null, setThreadId];\n};\n"],"mappings":";;;AAIA,MAAa,2BAA2B,YAGkB;CACxD,MAAM,CAAC,eAAe,sBAAA,GAAA,MAAA,UACpB,SAAS,YAAY,KACtB;CAED,MAAM,iBAAA,GAAA,MAAA,QAAuB,SAAS,WAAW;AACjD,eAAc,UAAU,SAAS;CAEjC,MAAM,eAAA,GAAA,MAAA,cAA2B,aAA4B;AAC3D,oBAAkB,SAAS;AAC3B,MAAI,YAAY,KAAM,eAAc,UAAU,SAAS;IACtD,EAAE,CAAC;AAEN,KAAI,CAAC,WAAW,EAAE,cAAc,SAC9B,QAAO,CAAC,eAAe,YAAY;AAGrC,QAAO,CAAC,QAAQ,YAAY,MAAM,YAAY"}
1
+ {"version":3,"file":"thread.cjs","names":[],"sources":["../src/thread.tsx"],"sourcesContent":["\"use client\";\n\nimport { useState, useRef, useCallback } from \"react\";\n\nexport const useControllableThreadId = (options?: {\n threadId?: string | null;\n onThreadId?: (threadId: string) => void;\n}): [string | null, (threadId: string | null) => void] => {\n const [localThreadId, _setLocalThreadId] = useState<string | null>(\n options?.threadId ?? null\n );\n\n const onThreadIdRef = useRef(options?.onThreadId);\n onThreadIdRef.current = options?.onThreadId;\n\n const setThreadId = useCallback((threadId: string | null) => {\n _setLocalThreadId(threadId);\n if (threadId != null) onThreadIdRef.current?.(threadId);\n }, []);\n\n if (!options || !(\"threadId\" in options)) {\n return [localThreadId, setThreadId];\n }\n\n return [options.threadId ?? null, setThreadId];\n};\n"],"mappings":";;;AAIA,MAAa,2BAA2B,YAGkB;CACxD,MAAM,CAAC,eAAe,sBAAA,GAAA,MAAA,UACpB,SAAS,YAAY,KACtB;CAED,MAAM,iBAAA,GAAA,MAAA,QAAuB,SAAS,WAAW;AACjD,eAAc,UAAU,SAAS;CAEjC,MAAM,eAAA,GAAA,MAAA,cAA2B,aAA4B;AAC3D,oBAAkB,SAAS;AAC3B,MAAI,YAAY,KAAM,eAAc,UAAU,SAAS;IACtD,EAAE,CAAC;AAEN,KAAI,CAAC,WAAW,EAAE,cAAc,SAC9B,QAAO,CAAC,eAAe,YAAY;AAGrC,QAAO,CAAC,QAAQ,YAAY,MAAM,YAAY"}
@@ -1 +1 @@
1
- {"version":3,"file":"thread.js","names":[],"sources":["../src/thread.tsx"],"sourcesContent":["\"use client\";\n\nimport { useState, useRef, useCallback } from \"react\";\n\nexport const useControllableThreadId = (options?: {\n threadId?: string | null;\n onThreadId?: (threadId: string) => void;\n}): [string | null, (threadId: string | null) => void] => {\n const [localThreadId, _setLocalThreadId] = useState<string | null>(\n options?.threadId ?? null,\n );\n\n const onThreadIdRef = useRef(options?.onThreadId);\n onThreadIdRef.current = options?.onThreadId;\n\n const setThreadId = useCallback((threadId: string | null) => {\n _setLocalThreadId(threadId);\n if (threadId != null) onThreadIdRef.current?.(threadId);\n }, []);\n\n if (!options || !(\"threadId\" in options)) {\n return [localThreadId, setThreadId];\n }\n\n return [options.threadId ?? null, setThreadId];\n};\n"],"mappings":";;;AAIA,MAAa,2BAA2B,YAGkB;CACxD,MAAM,CAAC,eAAe,qBAAqB,SACzC,SAAS,YAAY,KACtB;CAED,MAAM,gBAAgB,OAAO,SAAS,WAAW;AACjD,eAAc,UAAU,SAAS;CAEjC,MAAM,cAAc,aAAa,aAA4B;AAC3D,oBAAkB,SAAS;AAC3B,MAAI,YAAY,KAAM,eAAc,UAAU,SAAS;IACtD,EAAE,CAAC;AAEN,KAAI,CAAC,WAAW,EAAE,cAAc,SAC9B,QAAO,CAAC,eAAe,YAAY;AAGrC,QAAO,CAAC,QAAQ,YAAY,MAAM,YAAY"}
1
+ {"version":3,"file":"thread.js","names":[],"sources":["../src/thread.tsx"],"sourcesContent":["\"use client\";\n\nimport { useState, useRef, useCallback } from \"react\";\n\nexport const useControllableThreadId = (options?: {\n threadId?: string | null;\n onThreadId?: (threadId: string) => void;\n}): [string | null, (threadId: string | null) => void] => {\n const [localThreadId, _setLocalThreadId] = useState<string | null>(\n options?.threadId ?? null\n );\n\n const onThreadIdRef = useRef(options?.onThreadId);\n onThreadIdRef.current = options?.onThreadId;\n\n const setThreadId = useCallback((threadId: string | null) => {\n _setLocalThreadId(threadId);\n if (threadId != null) onThreadIdRef.current?.(threadId);\n }, []);\n\n if (!options || !(\"threadId\" in options)) {\n return [localThreadId, setThreadId];\n }\n\n return [options.threadId ?? null, setThreadId];\n};\n"],"mappings":";;;AAIA,MAAa,2BAA2B,YAGkB;CACxD,MAAM,CAAC,eAAe,qBAAqB,SACzC,SAAS,YAAY,KACtB;CAED,MAAM,gBAAgB,OAAO,SAAS,WAAW;AACjD,eAAc,UAAU,SAAS;CAEjC,MAAM,cAAc,aAAa,aAA4B;AAC3D,oBAAkB,SAAS;AAC3B,MAAI,YAAY,KAAM,eAAc,UAAU,SAAS;IACtD,EAAE,CAAC;AAEN,KAAI,CAAC,WAAW,EAAE,cAAc,SAC9B,QAAO,CAAC,eAAe,YAAY;AAGrC,QAAO,CAAC,QAAQ,YAAY,MAAM,YAAY"}
package/dist/types.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CustomSubmitOptions, DefaultSubagentStates, GetConfigurableType, GetInterruptType, GetToolCallsType, GetUpdateType, MessageMetadata, QueueInterface, Sequence, StreamBase, SubagentStream, SubagentStreamInterface, SubmitOptions, UseStreamCustomOptions as UseStreamCustomOptions$1 } from "@langchain/langgraph-sdk/ui";
2
- import { BaseMessage } from "@langchain/core/messages";
3
2
  import { BagTemplate, Client, StreamEvent, StreamMode, ThreadState, ToolProgress } from "@langchain/langgraph-sdk";
3
+ import { BaseMessage } from "@langchain/core/messages";
4
4
 
5
5
  //#region src/types.d.ts
6
6
  interface UseStream<StateType extends Record<string, unknown> = Record<string, unknown>, Bag extends BagTemplate = BagTemplate, SubagentStates extends Record<string, unknown> = DefaultSubagentStates> extends Omit<StreamBase<StateType, GetToolCallsType<StateType>, GetInterruptType<Bag>, SubagentStates>, "messages"> {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/react",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "description": "React integration for LangGraph & LangChain",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -10,36 +10,26 @@
10
10
  "directory": "libs/sdk-react"
11
11
  },
12
12
  "dependencies": {
13
- "@langchain/langgraph-sdk": "^1.8.2"
13
+ "@langchain/langgraph-sdk": "^1.8.5"
14
14
  },
15
15
  "devDependencies": {
16
16
  "@hono/node-server": "^1.19.11",
17
- "@langchain/core": "^1.1.31",
17
+ "@langchain/core": "^1.1.38",
18
18
  "@types/node": "^25.4.0",
19
19
  "@types/react": "^19.2.14",
20
- "@typescript-eslint/eslint-plugin": "^6.12.0",
21
- "@typescript-eslint/parser": "^6.12.0",
22
20
  "@vitejs/plugin-react": "^5.1.4",
23
21
  "@vitest/browser": "^4.0.18",
24
22
  "@vitest/browser-webdriverio": "^4.0.18",
25
23
  "deepagents": "^1.8.3",
26
- "eslint": "^8.33.0",
27
- "eslint-config-airbnb-base": "^15.0.0",
28
- "eslint-config-prettier": "^8.6.0",
29
- "eslint-plugin-import": "^2.29.1",
30
- "eslint-plugin-no-instanceof": "^1.0.1",
31
- "eslint-plugin-prettier": "^4.2.1",
32
- "eslint-plugin-react-hooks": "^5.2.0",
33
24
  "hono": "^4.12.7",
34
- "langchain": "^1.2.30",
35
- "prettier": "^3.8.1",
25
+ "langchain": "^1.3.0",
36
26
  "react": "^19.2.4",
37
27
  "typescript": "^5.9.3",
38
28
  "vitest": "^4.0.18",
39
29
  "vitest-browser-react": "^2.0.5",
40
30
  "webdriverio": "^9.25.0",
41
31
  "zod": "^4.3.6",
42
- "@langchain/langgraph": "^1.2.6",
32
+ "@langchain/langgraph": "^1.2.7",
43
33
  "@langchain/langgraph-api": "^1.1.17",
44
34
  "@langchain/langgraph-checkpoint": "^1.0.1"
45
35
  },
@@ -72,11 +62,7 @@
72
62
  "build": "pnpm turbo build:internal --filter=@langchain/react",
73
63
  "build:internal": "pnpm --filter @langchain/build compile @langchain/react",
74
64
  "prepublish": "pnpm build",
75
- "format:check": "prettier --check src",
76
- "format": "prettier --write src",
77
65
  "lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js,.jsx,.tsx src/",
78
- "lint": "pnpm lint:eslint",
79
- "lint:fix": "pnpm lint:eslint --fix",
80
66
  "test": "vitest run"
81
67
  }
82
68
  }