Open History to see the last commit
1import { GenerationClient } from '@tanstack/ai-client'
2import { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import {
4 batch,
5 createEffect,
6 createSignal,
7 onCleanup,
8 onMount,
9 untrack,
10} from 'solid-js'
11import type { StreamChunk } from '@tanstack/ai'
12import type {
13 AIDevtoolsDisplayOptions,
14 ConnectConnectionAdapter,
15 GenerationClientOptions,
16 GenerationClientState,
17 GenerationFetcher,
18 GenerationRestoredResult,
19 InferGenerationOutputFromReturn,
20} from '@tanstack/ai-client'
21import type { ByokClient } from '@tanstack/ai-client/byok'
22import type { ProviderId } from '@tanstack/ai/byok'
23import type { Accessor } from 'solid-js'
24
25/**
26 * Options for the useGeneration hook.
27 *
28 * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).
29 *
30 * @template TInput - The input type for the generation request
31 * @template TResult - The result type returned by the generation
32 * @template TOutput - The transformed output type (defaults to TResult)
33 */
34export interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
35 /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
36 connection?: ConnectConnectionAdapter
37 /** Direct async function for one-shot generation (no streaming protocol needed) */
38 fetcher?: GenerationFetcher<TInput, TResult>
39 /** Additional body parameters to send with connect-based adapter requests */
40 body?: Record<string, any>
41 /** Optional BYOK keyring. Keys go in `x-byok-*` headers, never the body. */
42 byok?: ByokClient
43 /** Optional provider id. If it returns a slug, only that key is sent. If no slug resolves (`byokProvider`, then `body.provider`), generate throws. */
44 byokProvider?: () => ProviderId | undefined
45 /** Display options for TanStack AI Devtools. */
46 devtools?: AIDevtoolsDisplayOptions
47 /**
48 * How this generation persists across reloads.
49 * - Omit / `false`: ephemeral, in-memory only.
50 * - `true`: server-driven — on mount the client hydrates the last generation
51 * for its `threadId` from the server (needs a connection with a
52 * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
53 */
54 persistence?: boolean
55 /**
56 * The **scope** this generation belongs to: a stable, app-chosen name for the
57 * slot successive runs fill — not a link to a chat conversation.
58 *
59 * The hook starts empty and produces many runs over its life; each gets its
60 * own `runId`, but all belong to one scope. Persistence keys on this, so
61 * derive it from your own domain and keep it identical across reloads (e.g.
62 * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
63 * id on the wire, which the protocol requires.
64 *
65 * Required. A generated id would change on every reload, so persistence
66 * would restore nothing.
67 */
68 threadId: string
69 /**
70 * Server-driven hydration handler for `persistence: true` when the
71 * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
72 * `rpcStream()` adapter built without handlers) — typically a one-line
73 * server-function call. The connection's own handler takes precedence.
74 */
75 hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
76 /**
77 * Re-attach handler that replays a run still generating to completion on
78 * mount, when the connection doesn't carry one. Without it, a restored
79 * `running` snapshot surfaces as an (interrupted) error. The connection's
80 * own handler takes precedence.
81 */
82 joinRun?: ConnectConnectionAdapter['joinRun']
83 /**
84 * Callback when a result is received. Can optionally return a transformed value.
85 *
86 * - Return a non-null value to transform and store it as the result
87 * - Return `null` to keep the previous result unchanged
88 * - Return nothing (`void`) to store the raw result as-is
89 */
90 onResult?: (result: TResult) => TOutput | null | void
91 /** Callback when an error occurs */
92 onError?: (error: Error) => void
93 /** Callback when progress is reported (0-100) */
94 onProgress?: (progress: number, message?: string) => void
95 /** Callback for each stream chunk (connect-based adapter mode only) */
96 onChunk?: (chunk: StreamChunk) => void
97 /**
98 * @internal Rebuild a typed result from a restored snapshot, injected by each
99 * specialized hook (image / speech / audio / transcription / summarize).
100 * Forwarded to the client so a server-hydrate restore repaints `result`.
101 */
102 reconstructResult?: (restored: GenerationRestoredResult) => TResult | null
103}
104
105/**
106 * Return type for the useGeneration hook.
107 *
108 * @template TOutput - The output type (possibly transformed from the raw result)
109 * @template TInput - The input type accepted by `generate` (defaults to any object)
110 */
111export interface UseGenerationReturn<
112 TOutput,
113 TInput extends Record<string, any> = Record<string, any>,
114> {
115 /** Trigger a generation request */
116 generate: (input: TInput) => Promise<void>
117 /** The generation result, or null if not yet generated */
118 result: Accessor<TOutput | null>
119 /** Whether a generation is currently in progress */
120 isLoading: Accessor<boolean>
121 /** Current error, if any */
122 error: Accessor<Error | undefined>
123 /** Current state of the generation client */
124 status: Accessor<GenerationClientState>
125 /** Abort the current generation */
126 stop: () => void
127 /** Clear result, error, and return to idle */
128 reset: () => void
129 /**
130 * The id of the generation job currently running, or `null` when nothing is in
131 * flight. Each call to `generate` is one job with its own id. Pass it to your
132 * own endpoint to cancel or poll the provider job — `stop()` only aborts the
133 * local stream, it does not stop work already running on the provider.
134 */
135 runId: Accessor<string | null>
136}
137
138/**
139 * Generic Solid hook for one-shot generation tasks.
140 *
141 * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,
142 * `useTranscription`, and `useSummarize`. You can also use it directly
143 * for custom generation types.
144 *
145 * @template TInput - The input type for the generation request
146 * @template TResult - The result type returned by the generation
147 * @template TOutput - The transformed output type (defaults to TResult)
148 *
149 * @example
150 * ```tsx
151 * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({
152 * connection: fetchServerSentEvents('/api/generate/custom'),
153 * })
154 *
155 * await generate({ prompt: 'Hello' })
156 * ```
157 */
158// `TTransformed` infers from the `onResult` return position (a covariant
159// inference site that works even for an optional nested property), which types
160// the callback parameter as `TResult` and narrows `result`. Inferring the
161// whole callback as a defaulted type parameter instead collapses to the
162// default, leaving the parameter `any` — a hard error under `strict`. See
163// issue #848.
164export function useGeneration<
165 TInput extends Record<string, any>,
166 TResult,
167 TTransformed = void,
168>(
169 options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {
170 onResult?: (result: TResult) => TTransformed
171 },
172): UseGenerationReturn<
173 InferGenerationOutputFromReturn<TResult, TTransformed>,
174 TInput
175> {
176 type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>
177
178 const [result, setResult] = createSignal<TOutput | null>(null)
179 const [isLoading, setIsLoading] = createSignal(false)
180 const [error, setError] = createSignal<Error | undefined>(undefined)
181 const [status, setStatus] = createSignal<GenerationClientState>('idle')
182 const [runId, setRunId] = createSignal<string | null>(null)
183 let disposed = false
184
185 // Built once. `untrack` keeps the option reads below from subscribing
186 // construction to `options.persistence` / `options.devtools` /
187 // `options.body`: a re-run would build a second client
188 // and orphan the first (only the live one is disposed on cleanup). Later
189 // `options.body` changes are pushed through `updateOptions` instead.
190 const client = untrack((): GenerationClient<TInput, TResult, TOutput> => {
191 // Conditional spread on `body`: `GenerationClientOptions.body` is a
192 // strict optional (`body?: Record<string, any>`) and EOPT forbids
193 // assigning the source `T | undefined` directly.
194 const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {
195 persistence: options.persistence,
196 threadId: options.threadId,
197 body: options.body,
198 ...(options.hydrateGeneration !== undefined && {
199 hydrateGeneration: options.hydrateGeneration,
200 }),
201 ...(options.joinRun !== undefined && { joinRun: options.joinRun }),
202 ...(options.byok !== undefined && { byok: options.byok }),
203 byokProvider: () => options.byokProvider?.(),
204 ...(options.reconstructResult
205 ? { reconstructResult: options.reconstructResult }
206 : {}),
207 devtoolsBridgeFactory: createGenerationDevtoolsBridge,
208 devtools: {
209 ...options.devtools,
210 framework: 'solid',
211 hookName: 'useGeneration',
212 },
213 // The transform's raw return type (`TTransformed`) and the stored output
214 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
215 // the cast bridges the relationship that the conditional type hides.
216 onResult: ((r: TResult) => options.onResult?.(r)) as (
217 result: TResult,
218 ) => TOutput | null | void,
219 onError: (e: Error) => {
220 if (!disposed) options.onError?.(e)
221 },
222 onProgress: (p: number, m?: string) => {
223 if (!disposed) options.onProgress?.(p, m)
224 },
225 onChunk: (c: StreamChunk) => {
226 if (!disposed) options.onChunk?.(c)
227 },
228 }
229
230 if (options.connection) {
231 return new GenerationClient<TInput, TResult, TOutput>({
232 ...clientOptions,
233 connection: options.connection,
234 })
235 }
236
237 if (options.fetcher) {
238 return new GenerationClient<TInput, TResult, TOutput>({
239 ...clientOptions,
240 fetcher: options.fetcher,
241 })
242 }
243
244 throw new Error(
245 'useGeneration requires either a connection or fetcher option',
246 )
247 })
248
249 const applySnapshot = () => {
250 const next = client.getSnapshot()
251 // One batch, so effects never see half of a snapshot.
252 batch(() => {
253 setResult(() => next.result)
254 setIsLoading(next.isLoading)
255 setError(next.error)
256 setStatus(next.status)
257 setRunId(next.runId)
258 })
259 }
260 applySnapshot()
261 onCleanup(client.subscribe(applySnapshot))
262
263 // Sync body changes without recreating client
264 createEffect(() => {
265 const currentBody = options.body
266 client.updateOptions({
267 ...(currentBody !== undefined && { body: currentBody }),
268 })
269 })
270
271 // Mount devtools only. Generation runs are never auto-started on mount — a
272 // persisted snapshot is hydrated for display, never replayed.
273 onMount(() => {
274 client.mountDevtools()
275 })
276
277 // Cleanup on unmount: stop any in-flight requests and unregister devtools
278 onCleanup(() => {
279 disposed = true
280 client.dispose()
281 })
282
283 const generate = async (input: TInput) => {
284 await client.generate(input)
285 }
286
287 const stop = () => {
288 client.stop()
289 }
290
291 const reset = () => {
292 client.reset()
293 }
294
295 return {
296 generate,
297 result,
298 isLoading,
299 error,
300 status,
301 stop,
302 reset,
303 runId,
304 }
305}