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

inject-generate-video.ts

253 lines8.7 KB

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
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>
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 }
185​
186 let client: VideoGenerationClient<TOutput>
187 if (options.connection) {
188 client = new VideoGenerationClient({
189 ...baseOptions,
190 connection: options.connection,
191 })
192 } else if (options.fetcher) {
193 client = new VideoGenerationClient({
194 ...baseOptions,
195 fetcher: options.fetcher,
196 })
197 } else {
198 throw new Error(
199 'injectGenerateVideo requires either a connection or fetcher option',
200 )
201 }
202​
203 const applySnapshot = () => {
204 const next = client.getSnapshot()
205 result.set(next.result)
206 isLoading.set(next.isLoading)
207 error.set(next.error)
208 status.set(next.status)
209 runId.set(next.runId)
210 jobId.set(next.jobId)
211 videoStatus.set(next.videoStatus)
212 }
213 applySnapshot()
214 const unsubscribeSnapshot = client.subscribe(applySnapshot)
215​
216 if (bodySource) {
217 effect(
218 () => {
219 client.updateOptions({
220 body: bodySource(),
221 })
222 },
223 { injector },
224 )
225 }
226​
227 // Mount devtools only. Generation runs are never auto-started after render —
228 // persisted state is read-only for display.
229 afterNextRender(
230 () => {
231 client.mountDevtools()
232 },
233 { injector },
234 )
235 destroyRef.onDestroy(() => {
236 disposed = true
237 unsubscribeSnapshot()
238 client.dispose()
239 })
240​
241 return {
242 generate: (input: VideoGenerateInput) => client.generate(input),
243 result: result.asReadonly(),
244 jobId: jobId.asReadonly(),
245 videoStatus: videoStatus.asReadonly(),
246 isLoading: isLoading.asReadonly(),
247 error: error.asReadonly(),
248 status: status.asReadonly(),
249 stop: () => client.stop(),
250 reset: () => client.reset(),
251 runId: runId.asReadonly(),
252 }