Open History to see the last commit
1import { VideoGenerationClient } from '@tanstack/ai-client'
2import { createVideoDevtoolsBridge } 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 { ReactiveOption } from './internal/to-reactive'
15import type {
16 AIDevtoolsDisplayOptions,
17 ConnectConnectionAdapter,
18 GenerationClientState,
19 GenerationFetcher,
20 GenerationPersistenceOptions,
21 InferGenerationOutputFromReturn,
22 VideoGenerateInput,
23 VideoGenerateResult,
24 VideoStatusInfo,
25} from '@tanstack/ai-client'
26import type { ByokClient } from '@tanstack/ai-client/byok'
27import type { ProviderId } from '@tanstack/ai/byok'
28import type { StreamChunk } from '@tanstack/ai'
29
30export interface InjectGenerateVideoOptions<TOutput = VideoGenerateResult> {
31 connection?: ConnectConnectionAdapter
32 fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>
33 body?: ReactiveOption<Record<string, any>>
34 /** Optional BYOK keyring. Keys go in `x-byok-*` headers, never the body. */
35 byok?: ByokClient
36 /** Optional provider id. If it returns a slug, only that key is sent. If no slug resolves (`byokProvider`, then `body.provider`), generate throws. */
37 byokProvider?: () => ProviderId | undefined
38 devtools?: AIDevtoolsDisplayOptions
39 /**
40 * How this generation persists across reloads.
41 * - Omit / `false`: ephemeral, in-memory only.
42 * - `true`: server-driven — on mount the client hydrates the last generation
43 * for its `threadId` from the server (needs a connection with a
44 * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
45 */
46 persistence?: boolean
47 /**
48 * The **scope** this generation belongs to: a stable, app-chosen name for the
49 * slot successive runs fill — not a link to a chat conversation.
50 *
51 * The hook starts empty and produces many runs over its life; each gets its
52 * own `runId`, but all belong to one scope. Persistence keys on this, so
53 * derive it from your own domain and keep it identical across reloads (e.g.
54 * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
55 * id on the wire, which the protocol requires.
56 *
57 * **Required whenever `persistence` is set** — an app that cannot name the
58 * scope has nothing to restore to. Optional for ephemeral generations. If
59 * omitted, the client mints a wire id after mount.
60 */
61 threadId?: string
62 /**
63 * Server-driven hydration handler for `persistence: true` when the
64 * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
65 * `rpcStream()` adapter built without handlers) — typically a one-line
66 * server-function call. The connection's own handler takes precedence.
67 */
68 hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
69 /**
70 * Re-attach handler that replays a run still generating to completion on
71 * mount, when the connection doesn't carry one. Without it, a restored
72 * `running` snapshot surfaces as an (interrupted) error. The connection's
73 * own handler takes precedence.
74 */
75 joinRun?: ConnectConnectionAdapter['joinRun']
76 onResult?: (result: VideoGenerateResult) => TOutput | null | void
77 onError?: (error: Error) => void
78 onProgress?: (progress: number, message?: string) => void
79 onJobCreated?: (jobId: string) => void
80 onStatusUpdate?: (status: VideoStatusInfo) => void
81 onChunk?: (chunk: StreamChunk) => void
82}
83
84export interface InjectGenerateVideoResult<TOutput = VideoGenerateResult> {
85 generate: (input: VideoGenerateInput) => Promise<void>
86 result: Signal<TOutput | null>
87 jobId: Signal<string | null>
88 videoStatus: Signal<VideoStatusInfo | null>
89 isLoading: Signal<boolean>
90 error: Signal<Error | undefined>
91 status: Signal<GenerationClientState>
92 stop: () => void
93 reset: () => void
94 /**
95 * The id of the generation job currently running, or `null` when nothing is in
96 * flight. Each call to `generate` is one job with its own id. Pass it to your
97 * own endpoint to cancel or poll the provider job — `stop()` only aborts the
98 * local stream, it does not stop work already running on the provider.
99 */
100 runId: Signal<string | null>
101}
102
103// `TTransformed` infers from the `onResult` return position so the callback
104// parameter is typed as `VideoGenerateResult` and `result` narrows to the
105// transform's return. See issue #848.
106export function injectGenerateVideo<TTransformed = void>(
107 options: Omit<
108 InjectGenerateVideoOptions,
109 'onResult' | 'persistence' | 'threadId'
110 > & {
111 onResult?: (result: VideoGenerateResult) => TTransformed
112 } & GenerationPersistenceOptions,
113): InjectGenerateVideoResult<
114 InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>
115> {
116 assertInInjectionContext(injectGenerateVideo)
117
118 type TOutput = InferGenerationOutputFromReturn<
119 VideoGenerateResult,
120 TTransformed
121 >
122
123 const destroyRef = inject(DestroyRef)
124 const injector = inject(Injector)
125
126 const result = signal<TOutput | null>(null)
127 const jobId = signal<string | null>(null)
128 const videoStatus = signal<VideoStatusInfo | null>(null)
129 const isLoading = signal(false)
130 const error = signal<Error | undefined>(undefined)
131 const status = signal<GenerationClientState>('idle')
132 const runId = signal<string | null>(null)
133 let disposed = false
134
135 const bodySource =
136 options.body !== undefined ? toReactive(options.body) : undefined
137
138 const baseOptions = {
139 ...(bodySource !== undefined && { body: bodySource() }),
140 ...(typeof options.threadId === 'string' && options.persistence
141 ? {
142 persistence: options.persistence,
143 threadId: options.threadId,
144 }
145 : {
146 ...(options.threadId !== undefined && {
147 threadId: options.threadId,
148 }),
149 }),
150 ...(options.hydrateGeneration !== undefined && {
151 hydrateGeneration: options.hydrateGeneration,
152 }),
153 ...(options.joinRun !== undefined && { joinRun: options.joinRun }),
154 ...(options.byok !== undefined && { byok: options.byok }),
155 byokProvider: () => options.byokProvider?.(),
156 devtoolsBridgeFactory: createVideoDevtoolsBridge,
157 devtools: {
158 ...options.devtools,
159 framework: 'angular',
160 hookName: 'injectGenerateVideo',
161 outputKind: 'video' as const,
162 },
163 // The transform's raw return type (`TTransformed`) and the stored output
164 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
165 // the cast bridges the relationship that the conditional type hides.
166 onResult: ((r: VideoGenerateResult) => options.onResult?.(r)) as (
167 result: VideoGenerateResult,
168 ) => TOutput | null | void,
169 onError: (e: Error) => {
170 if (!disposed) options.onError?.(e)
171 },
172 onProgress: (p: number, m?: string) => {
173 if (!disposed) options.onProgress?.(p, m)
174 },
175 onChunk: (c: StreamChunk) => {
176 if (!disposed) options.onChunk?.(c)
177 },
178 onJobCreated: (id: string) => {
179 if (!disposed) options.onJobCreated?.(id)
180 },
181 onStatusUpdate: (s: VideoStatusInfo) => {
182 if (!disposed) options.onStatusUpdate?.(s)
183 },
184 onResultChange: (r: TOutput | null) => {
185 if (!disposed) result.set(r)
186 },
187 onLoadingChange: (l: boolean) => {
188 if (!disposed) isLoading.set(l)
189 },
190 onErrorChange: (e: Error | undefined) => {
191 if (!disposed) error.set(e)
192 },
193 onStatusChange: (s: GenerationClientState) => {
194 if (!disposed) status.set(s)
195 },
196 onJobIdChange: (id: string | null) => {
197 if (!disposed) jobId.set(id)
198 },
199 onVideoStatusChange: (s: VideoStatusInfo | null) => {
200 if (!disposed) videoStatus.set(s)
201 },
202 onResumeStateChange: (rs: { runId: string } | null) => {
203 if (!disposed) runId.set(rs?.runId ?? null)
204 },
205 }
206
207 let client: VideoGenerationClient<TOutput>
208 if (options.connection) {
209 client = new VideoGenerationClient({
210 ...baseOptions,
211 connection: options.connection,
212 })
213 } else if (options.fetcher) {
214 client = new VideoGenerationClient({
215 ...baseOptions,
216 fetcher: options.fetcher,
217 })
218 } else {
219 throw new Error(
220 'injectGenerateVideo requires either a connection or fetcher option',
221 )
222 }
223
224 if (bodySource) {
225 effect(
226 () => {
227 client.updateOptions({
228 body: bodySource(),
229 })
230 },
231 { injector },
232 )
233 }
234
235 // Mount devtools only. Generation runs are never auto-started after render —
236 // persisted state is read-only for display.
237 afterNextRender(
238 () => {
239 client.mountDevtools()
240 },
241 { injector },
242 )
243 destroyRef.onDestroy(() => {
244 disposed = true
245 client.dispose()
246 })
247
248 return {
249 generate: (input: VideoGenerateInput) => client.generate(input),
250 result: result.asReadonly(),
251 jobId: jobId.asReadonly(),
252 videoStatus: videoStatus.asReadonly(),
253 isLoading: isLoading.asReadonly(),
254 error: error.asReadonly(),
255 status: status.asReadonly(),
256 stop: () => client.stop(),
257 reset: () => client.reset(),
258 runId: runId.asReadonly(),
259 }
260}