Open History to see the last commit
1import { GenerationClient } from '@tanstack/ai-client'
2import { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import { useCallback, useEffect, useMemo, useRef, useState } from 'octane'
4import type { StreamChunk } from '@tanstack/ai'
5import type {
6 AIDevtoolsDisplayOptions,
7 ConnectConnectionAdapter,
8 GenerationClientOptions,
9 GenerationClientState,
10 GenerationFetcher,
11 InferGenerationOutputFromReturn,
12} from '@tanstack/ai-client'
13
14/**
15 * Options for the useGeneration hook.
16 *
17 * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).
18 *
19 * @template TInput - The input type for the generation request
20 * @template TResult - The result type returned by the generation
21 * @template TOutput - The output type after optional transform (defaults to TResult)
22 */
23export interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
24 /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
25 connection?: ConnectConnectionAdapter
26 /** Direct async function for one-shot generation (no streaming protocol needed) */
27 fetcher?: GenerationFetcher<TInput, TResult>
28 /** Stable scope for this generation. Also the wire and DevTools identity. */
29 threadId: string
30 /** Additional body parameters to send with connect-based adapter requests */
31 body?: Record<string, any>
32 /** Display options for TanStack AI Devtools. */
33 devtools?: AIDevtoolsDisplayOptions
34 /**
35 * Callback when a result is received. Can optionally return a transformed value.
36 *
37 * - Return a non-null value to transform and store it as the result
38 * - Return `null` to keep the previous result unchanged
39 * - Return nothing (`void`) to store the raw result as-is
40 */
41 onResult?: (result: TResult) => TOutput | null | void
42 /** Callback when an error occurs */
43 onError?: (error: Error) => void
44 /** Callback when progress is reported (0-100) */
45 onProgress?: (progress: number, message?: string) => void
46 /** Callback for each stream chunk (connect-based adapter mode only) */
47 onChunk?: (chunk: StreamChunk) => void
48}
49
50/**
51 * Return type for the useGeneration hook.
52 *
53 * @template TInput - The input type accepted by `generate`
54 * @template TOutput - The output type (after optional transform)
55 */
56export interface UseGenerationReturn<TInput, TOutput> {
57 /**
58 * Trigger a generation request.
59 *
60 * Typed as `TInput` rather than `Record<string, any>` so required and narrow
61 * input fields are actually checked at the call site. (Upstream
62 * `@tanstack/ai-react` widens this; see status.json.)
63 */
64 generate: (input: TInput) => Promise<void>
65 /** The generation result, or null if not yet generated */
66 result: TOutput | null
67 /** Whether a generation is currently in progress */
68 isLoading: boolean
69 /** Current error, if any */
70 error: Error | undefined
71 /** Current state of the generation client */
72 status: GenerationClientState
73 /** Abort the current generation */
74 stop: () => void
75 /** Clear result, error, and return to idle */
76 reset: () => void
77}
78
79/**
80 * Generic Octane hook for one-shot generation tasks.
81 *
82 * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,
83 * `useTranscription`, and `useSummarize`. You can also use it directly
84 * for custom generation types.
85 *
86 * @template TInput - The input type for the generation request
87 * @template TResult - The result type returned by the generation
88 *
89 * @example
90 * ```tsx
91 * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({
92 * connection: fetchServerSentEvents('/api/generate/custom'),
93 * })
94 *
95 * await generate({ prompt: 'Hello' })
96 * ```
97 */
98// `TTransformed` infers from the `onResult` return position (a covariant
99// inference site that works even for an optional nested property), which types
100// the callback parameter as `TResult` and narrows `result`. Inferring the
101// whole callback as a defaulted type parameter instead collapses to the
102// default, leaving the parameter `any` — a hard error under `strict`. See
103// issue #848.
104export function useGeneration<
105 TInput extends Record<string, any>,
106 TResult,
107 TTransformed = void,
108>(
109 options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {
110 onResult?: (result: TResult) => TTransformed
111 },
112): UseGenerationReturn<
113 TInput,
114 InferGenerationOutputFromReturn<TResult, TTransformed>
115> {
116 type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>
117 const clientId = options.threadId
118
119 const [result, setResult] = useState<TOutput | null>(null)
120 const [isLoading, setIsLoading] = useState(false)
121 const [error, setError] = useState<Error | undefined>(undefined)
122 const [status, setStatus] = useState<GenerationClientState>('idle')
123
124 const optionsRef = useRef(options)
125 optionsRef.current = options
126
127 const client = useMemo(() => {
128 const opts = optionsRef.current
129
130 // Conditional spread for `body` (strict-optional in target;
131 // local source is `Record<string, any> | undefined`). Callbacks
132 // wrap optional ones in non-returning bodies so `?.()`'s
133 // implicit `undefined` doesn't pollute the function return type.
134 const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {
135 threadId: clientId,
136 body: opts.body,
137 devtoolsBridgeFactory: createGenerationDevtoolsBridge,
138 devtools: {
139 ...opts.devtools,
140 // OCTANE DIVERGENCE: identify this binding as Octane (not 'react') in TanStack AI Devtools.
141 // The spread comes first so a caller-supplied `devtools.framework` can't
142 // silently misidentify the binding — `useGeneration` is public API, and
143 // the sibling hooks (useChat, useGenerateVideo) already order it this way.
144 framework: 'octane',
145 hookName: 'useGeneration',
146 },
147 // The transform's raw return type (`TTransformed`) and the stored output
148 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
149 // the cast bridges the relationship that the conditional type hides.
150 onResult: ((r: TResult) => optionsRef.current.onResult?.(r)) as (
151 result: TResult,
152 ) => TOutput | null | void,
153 onError: (e: Error) => {
154 optionsRef.current.onError?.(e)
155 },
156 onProgress: (p: number, m?: string) => {
157 optionsRef.current.onProgress?.(p, m)
158 },
159 onChunk: (c: StreamChunk) => {
160 optionsRef.current.onChunk?.(c)
161 },
162 }
163
164 if (opts.connection) {
165 return new GenerationClient<TInput, TResult, TOutput>({
166 ...clientOptions,
167 connection: opts.connection,
168 })
169 }
170
171 if (opts.fetcher) {
172 return new GenerationClient<TInput, TResult, TOutput>({
173 ...clientOptions,
174 fetcher: opts.fetcher,
175 })
176 }
177
178 throw new Error(
179 'useGeneration requires either a connection or fetcher option',
180 )
181 }, [clientId])
182
183 useEffect(() => {
184 const applySnapshot = () => {
185 const next = client.getSnapshot()
186 setResult(next.result)
187 setIsLoading(next.isLoading)
188 setError(next.error)
189 setStatus(next.status)
190 }
191 applySnapshot()
192 return client.subscribe(applySnapshot)
193 }, [client])
194
195 // Sync body changes without recreating client
196 useEffect(() => {
197 // Conditional spread: target uses strict-optional `body?: T`.
198 client.updateOptions({
199 ...(options.body !== undefined && { body: options.body }),
200 })
201 }, [client, options.body])
202
203 // Cleanup on unmount
204 useEffect(() => {
205 client.mountDevtools()
206
207 return () => {
208 client.dispose()
209 }
210 }, [client])
211
212 const generate = useCallback(
213 async (input: TInput) => {
214 await client.generate(input)
215 },
216 [client],
217 )
218
219 const stop = useCallback(() => {
220 client.stop()
221 }, [client])
222
223 const reset = useCallback(() => {
224 client.reset()
225 }, [client])
226
227 return {
228 generate,
229 result,
230 isLoading,
231 error,
232 status,
233 stop,
234 reset,
235 }
236}