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