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