Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

inject-generation.ts

267 lines9.6 KB

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 GenerationRestoredResult,
22 InferGenerationOutputFromReturn,
23} from '@tanstack/ai-client'
24import type { ByokClient } from '@tanstack/ai-client/byok'
25import type { ProviderId } from '@tanstack/ai/byok'
26import type { ReactiveOption } from './internal/to-reactive'
27​
28export interface InjectGenerationOptions<TInput, TResult, TOutput = TResult> {
29 /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
30 connection?: ConnectConnectionAdapter
31 /** Direct async function for one-shot generation (no streaming protocol needed) */
32 fetcher?: GenerationFetcher<TInput, TResult>
33 /** Additional request body params. Reactive. */
34 body?: ReactiveOption<Record<string, any>>
35 /** Optional BYOK keyring. Keys go in `x-byok-*` headers, never the body. */
36 byok?: ByokClient
37 /** Optional provider id. If it returns a slug, only that key is sent. If no slug resolves (`byokProvider`, then `body.provider`), generate throws. */
38 byokProvider?: () => ProviderId | undefined
39 /** Display options for TanStack AI Devtools. */
40 devtools?: AIDevtoolsDisplayOptions
41 /**
42 * How this generation persists across reloads.
43 * - Omit / `false`: ephemeral, in-memory only.
44 * - `true`: server-driven — on mount the client hydrates the last generation
45 * for its `threadId` from the server (needs a connection with a
46 * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
47 */
48 persistence?: boolean
49 /**
50 * The **scope** this generation belongs to: a stable, app-chosen name for the
51 * slot successive runs fill — not a link to a chat conversation.
52 *
53 * The hook starts empty and produces many runs over its life; each gets its
54 * own `runId`, but all belong to one scope. Persistence keys on this, so
55 * derive it from your own domain and keep it identical across reloads (e.g.
56 * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
57 * id on the wire, which the protocol requires.
58 *
59 * Required. A generated id would change on every reload, so persistence
60 * would restore nothing.
61 */
62 threadId: string
63 /**
64 * Server-driven hydration handler for `persistence: true` when the
65 * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
66 * `rpcStream()` adapter built without handlers) — typically a one-line
67 * server-function call. The connection's own handler takes precedence.
68 */
69 hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
70 /**
71 * Re-attach handler that replays a run still generating to completion on
72 * mount, when the connection doesn't carry one. Without it, a restored
73 * `running` snapshot surfaces as an (interrupted) error. The connection's
74 * own handler takes precedence.
75 */
76 joinRun?: ConnectConnectionAdapter['joinRun']
77 /**
78 * Callback when a result is received. Can optionally return a transformed value.
79 *
80 * - Return a non-null value to transform and store it as the result
81 * - Return `null` to keep the previous result unchanged
82 * - Return nothing (`void`) to store the raw result as-is
83 */
84 onResult?: (result: TResult) => TOutput | null | void
85 /** Callback when an error occurs */
86 onError?: (error: Error) => void
87 /** Callback when progress is reported (0-100) */
88 onProgress?: (progress: number, message?: string) => void
89 /** Callback for each stream chunk (connect-based adapter mode only) */
90 onChunk?: (chunk: StreamChunk) => void
91 /**
92 * @internal Rebuild a typed result from a restored snapshot, injected by each
93 * specialized injectable (image / speech / audio / transcription / summarize).
94 * Forwarded to the client so a server-hydrate restore repaints `result`.
95 */
96 reconstructResult?: (restored: GenerationRestoredResult) => TResult | null
98​
99/**
100 * Return type for the injectGeneration function.
101 *
102 * @template TOutput - The output type (after optional transform)
103 * @template TInput - The input type accepted by `generate` (defaults to any object)
104 */
105export interface InjectGenerationResult<
106 TOutput,
107 TInput extends Record<string, any> = Record<string, any>,
108> {
109 /** Trigger a generation request */
110 generate: (input: TInput) => Promise<void>
111 /** The generation result, or null if not yet generated */
112 result: Signal<TOutput | null>
113 /** Whether a generation is currently in progress */
114 isLoading: Signal<boolean>
115 /** Current error, if any */
116 error: Signal<Error | undefined>
117 /** Current state of the generation client */
118 status: Signal<GenerationClientState>
119 /** Abort the current generation */
120 stop: () => void
121 /** Clear result, error, and return to idle */
122 reset: () => void
123 /** Identity of the in-flight run while one is streaming, or null after it ends */
124 /**
125 * The id of the generation job currently running, or `null` when nothing is in
126 * flight. Each call to `generate` is one job with its own id. Pass it to your
127 * own endpoint to cancel or poll the provider job — `stop()` only aborts the
128 * local stream, it does not stop work already running on the provider.
129 */
130 runId: Signal<string | null>
132​
133// `TTransformed` infers from the `onResult` return position (a covariant
134// inference site that works even for an optional nested property), which types
135// the callback parameter as `TResult` and narrows `result`. Inferring the
136// whole callback as a defaulted type parameter instead collapses to the
137// default, leaving the parameter `any` — a hard error under `strict`. See
138// issue #848.
139export function injectGeneration<
140 TInput extends Record<string, any>,
141 TResult,
142 TTransformed = void,
143>(
144 options: Omit<InjectGenerationOptions<TInput, TResult>, 'onResult'> & {
145 onResult?: (result: TResult) => TTransformed
146 },
147): InjectGenerationResult<
148 InferGenerationOutputFromReturn<TResult, TTransformed>,
149 TInput
150> {
151 assertInInjectionContext(injectGeneration)
152​
153 type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>
154​
155 const destroyRef = inject(DestroyRef)
156 const injector = inject(Injector)
157​
158 const result = signal<TOutput | null>(null)
159 const isLoading = signal(false)
160 const error = signal<Error | undefined>(undefined)
161 const status = signal<GenerationClientState>('idle')
162 const runId = signal<string | null>(null)
163 let disposed = false
164​
165 const bodySource =
166 options.body !== undefined ? toReactive(options.body) : undefined
167​
168 const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {
169 persistence: options.persistence,
170 threadId: options.threadId,
171 ...(bodySource !== undefined && { body: bodySource() }),
172 ...(options.hydrateGeneration !== undefined && {
173 hydrateGeneration: options.hydrateGeneration,
174 }),
175 ...(options.joinRun !== undefined && { joinRun: options.joinRun }),
176 ...(options.byok !== undefined && { byok: options.byok }),
177 byokProvider: () => options.byokProvider?.(),
178 ...(options.reconstructResult
179 ? { reconstructResult: options.reconstructResult }
180 : {}),
181 devtoolsBridgeFactory: createGenerationDevtoolsBridge,
182 devtools: {
183 ...options.devtools,
184 framework: 'angular',
185 hookName: 'injectGeneration',
186 },
187 // The transform's raw return type (`TTransformed`) and the stored output
188 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
189 // the cast bridges the relationship that the conditional type hides.
190 onResult: ((r: TResult) => options.onResult?.(r)) as (
191 result: TResult,
192 ) => TOutput | null | void,
193 onError: (e: Error) => {
194 if (!disposed) options.onError?.(e)
195 },
196 onProgress: (p: number, m?: string) => {
197 if (!disposed) options.onProgress?.(p, m)
198 },
199 onChunk: (c: StreamChunk) => {
200 if (!disposed) options.onChunk?.(c)
201 },
202 }
203​
204 let client: GenerationClient<TInput, TResult, TOutput>
205 if (options.connection) {
206 client = new GenerationClient({
207 ...clientOptions,
208 connection: options.connection,
209 })
210 } else if (options.fetcher) {
211 client = new GenerationClient({
212 ...clientOptions,
213 fetcher: options.fetcher,
214 })
215 } else {
216 throw new Error(
217 'injectGeneration requires either a connection or fetcher option',
218 )
219 }
220​
221 const applySnapshot = () => {
222 const next = client.getSnapshot()
223 result.set(next.result)
224 isLoading.set(next.isLoading)
225 error.set(next.error)
226 status.set(next.status)
227 runId.set(next.runId)
228 }
229 applySnapshot()
230 const unsubscribeSnapshot = client.subscribe(applySnapshot)
231​
232 if (bodySource) {
233 effect(
234 () => {
235 client.updateOptions({
236 body: bodySource(),
237 })
238 },
239 { injector },
240 )
241 }
242​
243 // Mount devtools only. Generation runs are never auto-started after render —
244 // persisted state is read-only for display.
245 afterNextRender(
246 () => {
247 client.mountDevtools()
248 },
249 { injector },
250 )
251 destroyRef.onDestroy(() => {
252 disposed = true
253 unsubscribeSnapshot()
254 client.dispose()
255 })
256​
257 return {
258 generate: (input: TInput) => client.generate(input),
259 result: result.asReadonly(),
260 isLoading: isLoading.asReadonly(),
261 error: error.asReadonly(),
262 status: status.asReadonly(),
263 stop: () => client.stop(),
264 reset: () => client.reset(),
265 runId: runId.asReadonly(),
266 }