Open History to see the last commit
1import { GenerationClient } from '@tanstack/ai-client'
2import { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import {
4 DestroyRef,
5 Injector,
6 afterNextRender,
7 assertInInjectionContext,
8 effect,
9 inject,
10 signal,
11} from '@angular/core'
12import { toReactive } from './internal/to-reactive'
13import type { Signal } from '@angular/core'
14import type { StreamChunk } from '@tanstack/ai'
15import type {
16 AIDevtoolsDisplayOptions,
17 ConnectConnectionAdapter,
18 GenerationClientOptions,
19 GenerationClientState,
20 GenerationFetcher,
21 GenerationPersistenceOptions,
22 GenerationRestoredResult,
23 InferGenerationOutputFromReturn,
24} from '@tanstack/ai-client'
25import type { ByokClient } from '@tanstack/ai-client/byok'
26import type { ProviderId } from '@tanstack/ai/byok'
27import type { ReactiveOption } from './internal/to-reactive'
28
29export interface InjectGenerationOptions<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 request body params. Reactive. */
35 body?: ReactiveOption<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 hook 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 whenever `persistence` is set** — an app that cannot name the
61 * scope has nothing to restore to. Optional for ephemeral generations. If
62 * omitted, the client mints a wire id after mount.
63 */
64 threadId?: string
65 /**
66 * Server-driven hydration handler for `persistence: true` when the
67 * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
68 * `rpcStream()` adapter built without handlers) — typically a one-line
69 * server-function call. The connection's own handler takes precedence.
70 */
71 hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
72 /**
73 * Re-attach handler that replays a run still generating to completion on
74 * mount, when the connection doesn't carry one. Without it, a restored
75 * `running` snapshot surfaces as an (interrupted) error. The connection's
76 * own handler takes precedence.
77 */
78 joinRun?: ConnectConnectionAdapter['joinRun']
79 /**
80 * Callback when a result is received. Can optionally return a transformed value.
81 *
82 * - Return a non-null value to transform and store it as the result
83 * - Return `null` to keep the previous result unchanged
84 * - Return nothing (`void`) to store the raw result as-is
85 */
86 onResult?: (result: TResult) => TOutput | null | void
87 /** Callback when an error occurs */
88 onError?: (error: Error) => void
89 /** Callback when progress is reported (0-100) */
90 onProgress?: (progress: number, message?: string) => void
91 /** Callback for each stream chunk (connect-based adapter mode only) */
92 onChunk?: (chunk: StreamChunk) => void
93 /**
94 * @internal Rebuild a typed result from a restored snapshot, injected by each
95 * specialized injectable (image / speech / audio / transcription / summarize).
96 * Forwarded to the client so a server-hydrate restore repaints `result`.
97 */
98 reconstructResult?: (restored: GenerationRestoredResult) => TResult | null
99}
100
101/**
102 * Return type for the injectGeneration function.
103 *
104 * @template TOutput - The output type (after optional transform)
105 * @template TInput - The input type accepted by `generate` (defaults to any object)
106 */
107export interface InjectGenerationResult<
108 TOutput,
109 TInput extends Record<string, any> = Record<string, any>,
110> {
111 /** Trigger a generation request */
112 generate: (input: TInput) => Promise<void>
113 /** The generation result, or null if not yet generated */
114 result: Signal<TOutput | null>
115 /** Whether a generation is currently in progress */
116 isLoading: Signal<boolean>
117 /** Current error, if any */
118 error: Signal<Error | undefined>
119 /** Current state of the generation client */
120 status: Signal<GenerationClientState>
121 /** Abort the current generation */
122 stop: () => void
123 /** Clear result, error, and return to idle */
124 reset: () => void
125 /** Identity of the in-flight run while one is streaming, or null after it ends */
126 /**
127 * The id of the generation job currently running, or `null` when nothing is in
128 * flight. Each call to `generate` is one job with its own id. Pass it to your
129 * own endpoint to cancel or poll the provider job — `stop()` only aborts the
130 * local stream, it does not stop work already running on the provider.
131 */
132 runId: Signal<string | null>
133}
134
135// `TTransformed` infers from the `onResult` return position (a covariant
136// inference site that works even for an optional nested property), which types
137// the callback parameter as `TResult` and narrows `result`. Inferring the
138// whole callback as a defaulted type parameter instead collapses to the
139// default, leaving the parameter `any` — a hard error under `strict`. See
140// issue #848.
141export function injectGeneration<
142 TInput extends Record<string, any>,
143 TResult,
144 TTransformed = void,
145>(
146 options: Omit<
147 InjectGenerationOptions<TInput, TResult>,
148 'onResult' | 'persistence' | 'threadId'
149 > & {
150 onResult?: (result: TResult) => TTransformed
151 } & GenerationPersistenceOptions,
152): InjectGenerationResult<
153 InferGenerationOutputFromReturn<TResult, TTransformed>,
154 TInput
155> {
156 assertInInjectionContext(injectGeneration)
157
158 type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>
159
160 const destroyRef = inject(DestroyRef)
161 const injector = inject(Injector)
162
163 const result = signal<TOutput | null>(null)
164 const isLoading = signal(false)
165 const error = signal<Error | undefined>(undefined)
166 const status = signal<GenerationClientState>('idle')
167 const runId = signal<string | null>(null)
168 let disposed = false
169
170 const bodySource =
171 options.body !== undefined ? toReactive(options.body) : undefined
172
173 const clientOptions: Omit<
174 GenerationClientOptions<TInput, TResult, TOutput>,
175 'persistence' | 'threadId'
176 > = {
177 ...(bodySource !== undefined && { body: bodySource() }),
178 ...(options.hydrateGeneration !== undefined && {
179 hydrateGeneration: options.hydrateGeneration,
180 }),
181 ...(options.joinRun !== undefined && { joinRun: options.joinRun }),
182 ...(options.byok !== undefined && { byok: options.byok }),
183 byokProvider: () => options.byokProvider?.(),
184 ...(options.reconstructResult
185 ? { reconstructResult: options.reconstructResult }
186 : {}),
187 devtoolsBridgeFactory: createGenerationDevtoolsBridge,
188 devtools: {
189 ...options.devtools,
190 framework: 'angular',
191 hookName: 'injectGeneration',
192 },
193 // The transform's raw return type (`TTransformed`) and the stored output
194 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
195 // the cast bridges the relationship that the conditional type hides.
196 onResult: ((r: TResult) => options.onResult?.(r)) as (
197 result: TResult,
198 ) => TOutput | null | void,
199 onError: (e: Error) => {
200 if (!disposed) options.onError?.(e)
201 },
202 onProgress: (p: number, m?: string) => {
203 if (!disposed) options.onProgress?.(p, m)
204 },
205 onChunk: (c: StreamChunk) => {
206 if (!disposed) options.onChunk?.(c)
207 },
208 }
209
210 const persistenceProps =
211 typeof options.threadId === 'string' && options.persistence
212 ? {
213 persistence: options.persistence,
214 threadId: options.threadId,
215 }
216 : {
217 ...(options.threadId !== undefined && {
218 threadId: options.threadId,
219 }),
220 }
221
222 let client: GenerationClient<TInput, TResult, TOutput>
223 if (options.connection) {
224 client = new GenerationClient({
225 ...clientOptions,
226 ...persistenceProps,
227 connection: options.connection,
228 })
229 } else if (options.fetcher) {
230 client = new GenerationClient({
231 ...clientOptions,
232 ...persistenceProps,
233 fetcher: options.fetcher,
234 })
235 } else {
236 throw new Error(
237 'injectGeneration requires either a connection or fetcher option',
238 )
239 }
240
241 const applySnapshot = () => {
242 const next = client.getSnapshot()
243 result.set(next.result)
244 isLoading.set(next.isLoading)
245 error.set(next.error)
246 status.set(next.status)
247 runId.set(next.runId)
248 }
249 applySnapshot()
250 const unsubscribeSnapshot = client.subscribe(applySnapshot)
251
252 if (bodySource) {
253 effect(
254 () => {
255 client.updateOptions({
256 body: bodySource(),
257 })
258 },
259 { injector },
260 )
261 }
262
263 // Mount devtools only. Generation runs are never auto-started after render —
264 // persisted state is read-only for display.
265 afterNextRender(
266 () => {
267 client.mountDevtools()
268 },
269 { injector },
270 )
271 destroyRef.onDestroy(() => {
272 disposed = true
273 unsubscribeSnapshot()
274 client.dispose()
275 })
276
277 return {
278 generate: (input: TInput) => client.generate(input),
279 result: result.asReadonly(),
280 isLoading: isLoading.asReadonly(),
281 error: error.asReadonly(),
282 status: status.asReadonly(),
283 stop: () => client.stop(),
284 reset: () => client.reset(),
285 runId: runId.asReadonly(),
286 }
287}