Open History to see the last commit
1import { useGeneration } from './use-generation'
2import { reconstructImageResult } from '@tanstack/ai-client'
3import type { ImageGenerationResult, StreamChunk } from '@tanstack/ai'
4import type {
5 AIDevtoolsDisplayOptions,
6 ConnectConnectionAdapter,
7 GenerationClientState,
8 GenerationFetcher,
9 GenerationPersistenceOptions,
10 ImageGenerateInput,
11 InferGenerationOutputFromReturn,
12} from '@tanstack/ai-client'
13
14/**
15 * Options for the useGenerateImage hook.
16 *
17 * @template TOutput - The output type after optional transform (defaults to ImageGenerationResult)
18 */
19export interface UseGenerateImageOptions<TOutput = ImageGenerationResult> {
20 /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
21 connection?: ConnectConnectionAdapter
22 /** Direct async function for image generation */
23 fetcher?: GenerationFetcher<ImageGenerateInput, ImageGenerationResult>
24 /**
25 * @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
26 */
27 id?: string
28 /** Additional body parameters to send with connect-based adapter requests */
29 body?: Record<string, any>
30 /** Display options for TanStack AI Devtools. */
31 devtools?: AIDevtoolsDisplayOptions
32 /**
33 * How this generation persists across reloads.
34 * - Omit / `false`: ephemeral, in-memory only.
35 * - `true`: server-driven — on mount the client hydrates the last generation
36 * for its `threadId` from the server (needs a connection with a
37 * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
38 */
39 persistence?: boolean
40 /**
41 * The **scope** this generation belongs to: a stable, app-chosen name for the
42 * slot successive runs fill — not a link to a chat conversation.
43 *
44 * The hook starts empty and produces many runs over its life; each gets its
45 * own `runId`, but all belong to one scope. Persistence keys on this, so
46 * derive it from your own domain and keep it identical across reloads (e.g.
47 * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
48 * id on the wire, which the protocol requires.
49 *
50 * **Required whenever `persistence` is set** — an app that cannot name the
51 * scope has nothing to restore to. Optional for ephemeral generations, where
52 * it falls back to `id` purely to satisfy the wire.
53 */
54 threadId?: string
55 /**
56 * Server-driven hydration handler for `persistence: true` when the
57 * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
58 * `rpcStream()` adapter built without handlers) — typically a one-line
59 * server-function call. The connection's own handler takes precedence.
60 */
61 hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
62 /**
63 * Re-attach handler that replays a run still generating to completion on
64 * mount, when the connection doesn't carry one. Without it, a restored
65 * `running` snapshot surfaces as an (interrupted) error. The connection's
66 * own handler takes precedence.
67 */
68 joinRun?: ConnectConnectionAdapter['joinRun']
69 /**
70 * Callback when images are generated. Can optionally return a transformed value.
71 *
72 * - Return a non-null value to transform and store it as the result
73 * - Return `null` to keep the previous result unchanged
74 * - Return nothing (`void`) to store the raw result as-is
75 */
76 onResult?: (result: ImageGenerationResult) => TOutput | null | void
77 /** Callback when an error occurs */
78 onError?: (error: Error) => void
79 /** Callback when progress is reported (0-100) */
80 onProgress?: (progress: number, message?: string) => void
81 /** Callback for each stream chunk (connect-based adapter mode only) */
82 onChunk?: (chunk: StreamChunk) => void
83}
84
85/**
86 * Return type for the useGenerateImage hook.
87 *
88 * @template TOutput - The output type (after optional transform)
89 */
90export interface UseGenerateImageReturn<TOutput = ImageGenerationResult> {
91 /** Trigger image generation */
92 generate: (input: ImageGenerateInput) => Promise<void>
93 /** The generation result containing images, or null */
94 result: TOutput | null
95 /** Whether generation is in progress */
96 isLoading: boolean
97 /** Current error, if any */
98 error: Error | undefined
99 /** Current state of the generation */
100 status: GenerationClientState
101 /** Abort the current generation */
102 stop: () => void
103 /** Clear result, error, and return to idle */
104 reset: () => void
105 /**
106 * The id of the generation job currently running, or `null` when nothing is in
107 * flight. Each call to `generate` is one job with its own id. Pass it to your
108 * own endpoint to cancel or poll the provider job — `stop()` only aborts the
109 * local stream, it does not stop work already running on the provider.
110 */
111 runId: string | null
112}
113
114/**
115 * React hook for generating images using AI models.
116 *
117 * Supports two transport modes:
118 * - **ConnectConnectionAdapter** — Streaming transport (SSE, HTTP stream, custom)
119 * - **Fetcher** — Direct async function call
120 *
121 * @example
122 * ```tsx
123 * import { useGenerateImage } from '@tanstack/ai-react'
124 * import { fetchServerSentEvents } from '@tanstack/ai-client'
125 *
126 * function ImageGenerator() {
127 * const { generate, result, isLoading, error, reset } = useGenerateImage({
128 * connection: fetchServerSentEvents('/api/generate/image'),
129 * })
130 *
131 * return (
132 * <div>
133 * <button onClick={() => generate({ prompt: 'A sunset over mountains' })}>
134 * Generate
135 * </button>
136 * {isLoading && <p>Generating...</p>}
137 * {error && <p>Error: {error.message}</p>}
138 * {result?.images.map((img, i) => (
139 * <img key={i} src={img.url || `data:image/png;base64,${img.b64Json}`} />
140 * ))}
141 * </div>
142 * )
143 * }
144 * ```
145 */
146export function useGenerateImage<TTransformed = void>(
147 options: Omit<
148 UseGenerateImageOptions,
149 'onResult' | 'persistence' | 'threadId' | 'id'
150 > & {
151 onResult?: (result: ImageGenerationResult) => TTransformed
152 } & GenerationPersistenceOptions,
153): UseGenerateImageReturn<
154 InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>
155> {
156 const devtools = {
157 ...options.devtools,
158 framework: 'react',
159 hookName: 'useGenerateImage',
160 outputKind: 'image' as const,
161 }
162 const generation = useGeneration<
163 ImageGenerateInput,
164 ImageGenerationResult,
165 TTransformed
166 >({
167 ...options,
168 devtools,
169 reconstructResult: reconstructImageResult,
170 })
171
172 return generation
173}