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