Open History to see the last commit
1import { GenerationClient } from '@tanstack/ai-client'
2import { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import {
4 createEffect,
5 createSignal,
6 onCleanup,
7 onMount,
8 untrack,
9} from 'solid-js'
10import type { StreamChunk } from '@tanstack/ai'
11import type {
12 AIDevtoolsDisplayOptions,
13 ConnectConnectionAdapter,
14 GenerationClientOptions,
15 GenerationClientState,
16 GenerationFetcher,
17 GenerationPersistenceOptions,
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 whenever `persistence` is set** — an app that cannot name the
66 * scope has nothing to restore to. Optional for ephemeral generations. If
67 * omitted, the client mints a wire id after mount.
68 */
69 threadId?: string
70 /**
71 * Server-driven hydration handler for `persistence: true` when the
72 * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
73 * `rpcStream()` adapter built without handlers) — typically a one-line
74 * server-function call. The connection's own handler takes precedence.
75 */
76 hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
77 /**
78 * Re-attach handler that replays a run still generating to completion on
79 * mount, when the connection doesn't carry one. Without it, a restored
80 * `running` snapshot surfaces as an (interrupted) error. The connection's
81 * own handler takes precedence.
82 */
83 joinRun?: ConnectConnectionAdapter['joinRun']
84 /**
85 * Callback when a result is received. Can optionally return a transformed value.
86 *
87 * - Return a non-null value to transform and store it as the result
88 * - Return `null` to keep the previous result unchanged
89 * - Return nothing (`void`) to store the raw result as-is
90 */
91 onResult?: (result: TResult) => TOutput | null | void
92 /** Callback when an error occurs */
93 onError?: (error: Error) => void
94 /** Callback when progress is reported (0-100) */
95 onProgress?: (progress: number, message?: string) => void
96 /** Callback for each stream chunk (connect-based adapter mode only) */
97 onChunk?: (chunk: StreamChunk) => void
98 /**
99 * @internal Rebuild a typed result from a restored snapshot, injected by each
100 * specialized hook (image / speech / audio / transcription / summarize).
101 * Forwarded to the client so a server-hydrate restore repaints `result`.
102 */
103 reconstructResult?: (restored: GenerationRestoredResult) => TResult | null
104}
105
106/**
107 * Return type for the useGeneration hook.
108 *
109 * @template TOutput - The output type (possibly transformed from the raw result)
110 * @template TInput - The input type accepted by `generate` (defaults to any object)
111 */
112export interface UseGenerationReturn<
113 TOutput,
114 TInput extends Record<string, any> = Record<string, any>,
115> {
116 /** Trigger a generation request */
117 generate: (input: TInput) => Promise<void>
118 /** The generation result, or null if not yet generated */
119 result: Accessor<TOutput | null>
120 /** Whether a generation is currently in progress */
121 isLoading: Accessor<boolean>
122 /** Current error, if any */
123 error: Accessor<Error | undefined>
124 /** Current state of the generation client */
125 status: Accessor<GenerationClientState>
126 /** Abort the current generation */
127 stop: () => void
128 /** Clear result, error, and return to idle */
129 reset: () => void
130 /**
131 * The id of the generation job currently running, or `null` when nothing is in
132 * flight. Each call to `generate` is one job with its own id. Pass it to your
133 * own endpoint to cancel or poll the provider job — `stop()` only aborts the
134 * local stream, it does not stop work already running on the provider.
135 */
136 runId: Accessor<string | null>
137}
138
139/**
140 * Generic Solid hook for one-shot generation tasks.
141 *
142 * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,
143 * `useTranscription`, and `useSummarize`. You can also use it directly
144 * for custom generation types.
145 *
146 * @template TInput - The input type for the generation request
147 * @template TResult - The result type returned by the generation
148 * @template TOutput - The transformed output type (defaults to TResult)
149 *
150 * @example
151 * ```tsx
152 * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({
153 * connection: fetchServerSentEvents('/api/generate/custom'),
154 * })
155 *
156 * await generate({ prompt: 'Hello' })
157 * ```
158 */
159// `TTransformed` infers from the `onResult` return position (a covariant
160// inference site that works even for an optional nested property), which types
161// the callback parameter as `TResult` and narrows `result`. Inferring the
162// whole callback as a defaulted type parameter instead collapses to the
163// default, leaving the parameter `any` — a hard error under `strict`. See
164// issue #848.
165export function useGeneration<
166 TInput extends Record<string, any>,
167 TResult,
168 TTransformed = void,
169>(
170 options: Omit<
171 UseGenerationOptions<TInput, TResult>,
172 'onResult' | 'persistence' | 'threadId'
173 > & {
174 onResult?: (result: TResult) => TTransformed
175 } & GenerationPersistenceOptions,
176): UseGenerationReturn<
177 InferGenerationOutputFromReturn<TResult, TTransformed>,
178 TInput
179> {
180 type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>
181
182 const [result, setResult] = createSignal<TOutput | null>(null)
183 const [isLoading, setIsLoading] = createSignal(false)
184 const [error, setError] = createSignal<Error | undefined>(undefined)
185 const [status, setStatus] = createSignal<GenerationClientState>('idle')
186 const [runId, setRunId] = createSignal<string | null>(null)
187 let disposed = false
188
189 // Built once. `untrack` keeps the option reads below from subscribing
190 // construction to `options.persistence` / `options.devtools` /
191 // `options.body`: a re-run would build a second client
192 // and orphan the first (only the live one is disposed on cleanup). Later
193 // `options.body` changes are pushed through `updateOptions` instead.
194 const client = untrack((): GenerationClient<TInput, TResult, TOutput> => {
195 // Conditional spread on `body`: `GenerationClientOptions.body` is a
196 // strict optional (`body?: Record<string, any>`) and EOPT forbids
197 // assigning the source `T | undefined` directly.
198 const clientOptions: Omit<
199 GenerationClientOptions<TInput, TResult, TOutput>,
200 'persistence' | 'threadId'
201 > = {
202 body: options.body,
203 ...(options.hydrateGeneration !== undefined && {
204 hydrateGeneration: options.hydrateGeneration,
205 }),
206 ...(options.joinRun !== undefined && { joinRun: options.joinRun }),
207 ...(options.byok !== undefined && { byok: options.byok }),
208 byokProvider: () => options.byokProvider?.(),
209 ...(options.reconstructResult
210 ? { reconstructResult: options.reconstructResult }
211 : {}),
212 devtoolsBridgeFactory: createGenerationDevtoolsBridge,
213 devtools: {
214 ...options.devtools,
215 framework: 'solid',
216 hookName: 'useGeneration',
217 },
218 // The transform's raw return type (`TTransformed`) and the stored output
219 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
220 // the cast bridges the relationship that the conditional type hides.
221 onResult: ((r: TResult) => options.onResult?.(r)) as (
222 result: TResult,
223 ) => TOutput | null | void,
224 onError: (e: Error) => {
225 if (!disposed) options.onError?.(e)
226 },
227 onProgress: (p: number, m?: string) => {
228 if (!disposed) options.onProgress?.(p, m)
229 },
230 onChunk: (c: StreamChunk) => {
231 if (!disposed) options.onChunk?.(c)
232 },
233 onResultChange: (r) => {
234 if (!disposed) setResult(() => r)
235 },
236 onLoadingChange: (l) => {
237 if (!disposed) setIsLoading(l)
238 },
239 onErrorChange: (e) => {
240 if (!disposed) setError(e)
241 },
242 onStatusChange: (s) => {
243 if (!disposed) setStatus(s)
244 },
245 onResumeStateChange: (rs) => {
246 if (!disposed) setRunId(rs?.runId ?? null)
247 },
248 }
249
250 const persistenceProps =
251 typeof options.threadId === 'string' && options.persistence
252 ? {
253 persistence: options.persistence,
254 threadId: options.threadId,
255 }
256 : {
257 ...(options.threadId !== undefined && {
258 threadId: options.threadId,
259 }),
260 }
261
262 if (options.connection) {
263 return new GenerationClient<TInput, TResult, TOutput>({
264 ...clientOptions,
265 ...persistenceProps,
266 connection: options.connection,
267 })
268 }
269
270 if (options.fetcher) {
271 return new GenerationClient<TInput, TResult, TOutput>({
272 ...clientOptions,
273 ...persistenceProps,
274 fetcher: options.fetcher,
275 })
276 }
277
278 throw new Error(
279 'useGeneration requires either a connection or fetcher option',
280 )
281 })
282
283 // Sync body changes without recreating client
284 createEffect(() => {
285 const currentBody = options.body
286 client.updateOptions({
287 ...(currentBody !== undefined && { body: currentBody }),
288 })
289 })
290
291 // Mount devtools only. Generation runs are never auto-started on mount — a
292 // persisted snapshot is hydrated for display, never replayed.
293 onMount(() => {
294 client.mountDevtools()
295 })
296
297 // Cleanup on unmount: stop any in-flight requests and unregister devtools
298 onCleanup(() => {
299 disposed = true
300 client.dispose()
301 })
302
303 const generate = async (input: TInput) => {
304 await client.generate(input)
305 }
306
307 const stop = () => {
308 client.stop()
309 }
310
311 const reset = () => {
312 client.reset()
313 }
314
315 return {
316 generate,
317 result,
318 isLoading,
319 error,
320 status,
321 stop,
322 reset,
323 runId,
324 }
325}