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