Open History to see the last commit
1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import { aiEventClient } from '@tanstack/ai-event-client'
3import { EventType } from '@tanstack/ai'
4import { createAIDevtoolsGenerationPreview } from '../src/devtools'
5import { GenerationClient } from '../src/generation-client'
6import { VideoGenerationClient } from '../src/video-generation-client'
7import type { StreamChunk } from '@tanstack/ai'
8import type { ConnectConnectionAdapter } from '../src/connection-adapters'
9
10interface StopRunOptions {
11 threadId: string
12 devtools: { hookName: string }
13 fetchText: () => Promise<string>
14 onLoadingChange?: (isLoading: boolean) => void
15 onStatusChange?: (status: string) => void
16 onErrorChange?: (error: Error | undefined) => void
17}
18
19interface DevtoolsEvent<TPayload = unknown> {
20 type: string
21 payload: TPayload
22 pluginId?: string
23}
24
25type DevtoolsEventCallback = (event: DevtoolsEvent) => void
26
27const eventClientMock = vi.hoisted(() => {
28 const listeners = new Map<string, Array<DevtoolsEventCallback>>()
29 const unsubscribe = vi.fn()
30
31 return {
32 emit: vi.fn(),
33 emitAIDevtoolsEvent: vi.fn((eventName: string, payload: unknown) => {
34 eventClientMock.emit(eventName, payload)
35 }),
36 unsubscribe,
37 on: vi.fn((eventName: string, callback: DevtoolsEventCallback) => {
38 const currentListeners = listeners.get(eventName) ?? []
39 currentListeners.push(callback)
40 listeners.set(eventName, currentListeners)
41
42 return () => {
43 unsubscribe()
44 const nextListeners = (listeners.get(eventName) ?? []).filter(
45 (listener) => listener !== callback,
46 )
47 listeners.set(eventName, nextListeners)
48 }
49 }),
50 dispatch(eventName: string, payload: unknown) {
51 for (const listener of listeners.get(eventName) ?? []) {
52 listener({
53 type: `tanstack-ai-devtools:${eventName}`,
54 payload,
55 pluginId: 'tanstack-ai-devtools',
56 })
57 }
58 },
59 emitted(eventName: string) {
60 return eventClientMock.emit.mock.calls.filter(
61 ([name]) => name === eventName,
62 )
63 },
64 reset() {
65 listeners.clear()
66 unsubscribe.mockClear()
67 },
68 }
69})
70
71vi.mock('@tanstack/ai-event-client', () => ({
72 aiEventClient: {
73 emit: eventClientMock.emit,
74 on: eventClientMock.on,
75 },
76 emitAIDevtoolsEvent: eventClientMock.emitAIDevtoolsEvent,
77 createAIDevtoolsEventEnvelope: (input: {
78 eventType: string
79 timestamp: number
80 }) => ({
81 ...input,
82 eventId: `event:${input.eventType}:${input.timestamp}`,
83 }),
84}))
85
86describe('generation client devtools bridge', () => {
87 beforeEach(() => {
88 vi.clearAllMocks()
89 eventClientMock.reset()
90 })
91
92 function resultChunk(value: unknown) {
93 return {
94 type: EventType.CUSTOM,
95 name: 'generation:result',
96 value,
97 timestamp: Date.now(),
98 } satisfies StreamChunk
99 }
100
101 function runStartedChunk(runId: string) {
102 return {
103 type: EventType.RUN_STARTED,
104 runId,
105 threadId: 'thread-1',
106 timestamp: Date.now(),
107 } satisfies StreamChunk
108 }
109
110 function runFinishedChunk(runId: string) {
111 return {
112 type: EventType.RUN_FINISHED,
113 runId,
114 threadId: 'thread-1',
115 timestamp: Date.now(),
116 metadata: { tanstack: { finishReason: 'stop' } },
117 } satisfies StreamChunk
118 }
119
120 function createDeferred<T>() {
121 let resolve!: (value: T) => void
122 const promise = new Promise<T>((nextResolve) => {
123 resolve = nextResolve
124 })
125 return { promise, resolve }
126 }
127
128 function latestSnapshotState() {
129 const snapshot = eventClientMock.emitted('hook:state-snapshot').at(-1)?.[1]
130 if (!isSnapshotStatePayload(snapshot)) {
131 throw new Error('Expected a hook state snapshot payload')
132 }
133 return snapshot.state
134 }
135
136 function latestGenerationRuns() {
137 const runs = latestSnapshotState().runs
138 if (!Array.isArray(runs)) {
139 throw new Error('Expected generation snapshot runs')
140 }
141 return runs
142 }
143
144 function isSnapshotStatePayload(
145 value: unknown,
146 ): value is { state: Record<string, unknown> } {
147 return Boolean(
148 value &&
149 typeof value === 'object' &&
150 'state' in value &&
151 value.state &&
152 typeof value.state === 'object' &&
153 !Array.isArray(value.state),
154 )
155 }
156
157 it('normalizes generation results into renderable devtools previews', () => {
158 expect(
159 createAIDevtoolsGenerationPreview({
160 outputKind: 'image',
161 result: {
162 id: 'img-1',
163 model: 'image-model',
164 images: [
165 { url: 'https://example.com/image.png' },
166 { b64Json: 'iVBORw0KGgo=' },
167 ],
168 },
169 }),
170 ).toEqual({
171 kind: 'image',
172 items: [
173 {
174 src: 'https://example.com/image.png',
175 sourceType: 'url',
176 },
177 {
178 src: 'data:image/png;base64,iVBORw0KGgo=',
179 sourceType: 'base64',
180 mimeType: 'image/png',
181 },
182 ],
183 })
184
185 expect(
186 createAIDevtoolsGenerationPreview({
187 outputKind: 'audio',
188 result: {
189 id: 'speech-1',
190 model: 'tts-model',
191 audio: 'UklGRg==',
192 format: 'wav',
193 contentType: 'audio/wav',
194 },
195 }),
196 ).toEqual({
197 kind: 'audio',
198 items: [
199 {
200 src: 'data:audio/wav;base64,UklGRg==',
201 sourceType: 'base64',
202 mimeType: 'audio/wav',
203 format: 'wav',
204 },
205 ],
206 })
207
208 expect(
209 createAIDevtoolsGenerationPreview({
210 outputKind: 'text',
211 result: {
212 id: 'transcription-1',
213 model: 'whisper',
214 text: 'Hello world',
215 },
216 }),
217 ).toEqual({
218 kind: 'text',
219 text: 'Hello world',
220 })
221
222 expect(
223 createAIDevtoolsGenerationPreview({
224 outputKind: 'video',
225 result: null,
226 videoStatus: {
227 jobId: 'job-1',
228 status: 'processing',
229 progress: 50,
230 url: 'https://example.com/video.mp4',
231 },
232 }),
233 ).toEqual({
234 kind: 'video',
235 items: [
236 {
237 src: 'https://example.com/video.mp4',
238 sourceType: 'url',
239 },
240 ],
241 job: {
242 jobId: 'job-1',
243 status: 'processing',
244 progress: 50,
245 },
246 })
247 })
248
249 it('registers a generation hook and emits run lifecycle for fetcher mode', async () => {
250 const client = new GenerationClient({
251 threadId: 'gen-1',
252 fetcher: async () => ({ text: 'done' }),
253 devtools: {
254 framework: 'react',
255 hookName: 'useGenerateObject',
256 outputKind: 'structured',
257 },
258 })
259 vi.clearAllMocks()
260
261 await client.generate({ prompt: 'make object' })
262
263 expect(aiEventClient.emit).toHaveBeenCalledWith(
264 'run:started',
265 expect.objectContaining({
266 hookId: 'gen-1',
267 source: 'client',
268 visibility: 'client-state',
269 runId: expect.any(String),
270 status: 'started',
271 }),
272 )
273 expect(aiEventClient.emit).toHaveBeenCalledWith(
274 'run:completed',
275 expect.objectContaining({
276 hookId: 'gen-1',
277 source: 'client',
278 visibility: 'client-state',
279 runId: expect.any(String),
280 status: 'completed',
281 }),
282 )
283 expect(aiEventClient.emit).toHaveBeenCalledWith(
284 'hook:state-snapshot',
285 expect.objectContaining({
286 hookId: 'gen-1',
287 hookName: 'useGenerateObject',
288 framework: 'react',
289 outputKind: 'structured',
290 state: expect.objectContaining({
291 status: 'success',
292 isLoading: false,
293 result: { text: 'done' },
294 }),
295 }),
296 )
297
298 client.dispose()
299 })
300
301 describe.each([
302 {
303 name: 'generation',
304 create: (options: StopRunOptions) =>
305 new GenerationClient<{ prompt: string }, { text: string }>({
306 ...options,
307 fetcher: async () => ({ text: await options.fetchText() }),
308 }),
309 successResult: { text: 'done' },
310 },
311 {
312 name: 'video',
313 create: (options: StopRunOptions) =>
314 new VideoGenerationClient({
315 ...options,
316 fetcher: async () => ({
317 jobId: await options.fetchText(),
318 status: 'completed' as const,
319 url: 'https://example.com/video-1.mp4',
320 }),
321 }),
322 successResult: expect.objectContaining({ jobId: 'done' }),
323 },
324 ])(
325 '$name devtools run stopped from a callback',
326 ({ name, create, successResult }) => {
327 it('finishes the run when a runId subscriber stops it', async () => {
328 const fetchText = vi.fn(async () => 'done')
329 const client = create({
330 threadId: `${name}-run-id-stop`,
331 devtools: { hookName: 'useRunIdStop' },
332 fetchText,
333 })
334 const unsubscribe = client.subscribe(() => {
335 if (client.getSnapshot().runId) client.stop()
336 })
337
338 await client.generate({ prompt: 'stop early' })
339
340 expect(fetchText).not.toHaveBeenCalled()
341 expect(latestSnapshotState().activeRunId).toBeNull()
342 unsubscribe()
343 client.dispose()
344 })
345
346 it('finishes the run when loading callback stops it', async () => {
347 const fetchText = vi.fn(async () => 'done')
348 let client!: ReturnType<typeof create>
349 client = create({
350 threadId: `${name}-loading-stop`,
351 devtools: { hookName: 'useLoadingStop' },
352 fetchText,
353 onLoadingChange: (isLoading) => {
354 if (isLoading) client.stop()
355 },
356 })
357
358 await client.generate({ prompt: 'stop while loading' })
359
360 expect(fetchText).not.toHaveBeenCalled()
361 expect(latestSnapshotState().activeRunId).toBeNull()
362 client.dispose()
363 })
364
365 it('finishes a completed run when success callback stops it', async () => {
366 let client!: ReturnType<typeof create>
367 client = create({
368 threadId: `${name}-success-stop`,
369 devtools: { hookName: 'useSuccessStop' },
370 fetchText: async () => 'done',
371 onStatusChange: (status) => {
372 if (status === 'success') client.stop()
373 },
374 })
375
376 await client.generate({ prompt: 'finish then stop' })
377
378 expect(latestSnapshotState().activeRunId).toBeNull()
379 expect(latestGenerationRuns().at(-1)).toEqual(
380 expect.objectContaining({ status: 'success', result: successResult }),
381 )
382 client.dispose()
383 })
384
385 it.each(['onStatusChange', 'onErrorChange'] as const)(
386 'records an errored run when %s stops it',
387 async (callback) => {
388 let client!: ReturnType<typeof create>
389 const stopOnError = () => {
390 if (client.getError()) client.stop()
391 }
392 client = create({
393 threadId: `${name}-error-stop-${callback}`,
394 devtools: { hookName: 'useErrorStop' },
395 fetchText: async () => {
396 throw new Error(`${name} failed`)
397 },
398 [callback]: stopOnError,
399 })
400
401 await client.generate({ prompt: 'fail then stop' })
402
403 expect(latestSnapshotState().activeRunId).toBeNull()
404 expect(latestGenerationRuns().at(-1)).toEqual(
405 expect.objectContaining({
406 status: 'error',
407 error: `${name} failed`,
408 }),
409 )
410 client.dispose()
411 },
412 )
413 },
414 )
415
416 it('includes input, progress, and renderable previews in generation snapshots', async () => {
417 const client = new GenerationClient({
418 threadId: 'image-hook',
419 fetcher: async () => ({
420 id: 'img-1',
421 model: 'image-model',
422 images: [
423 { url: 'https://example.com/image.png' },
424 { b64Json: 'iVBORw0KGgo=' },
425 ],
426 }),
427 devtools: {
428 framework: 'react',
429 hookName: 'useGenerateImage',
430 outputKind: 'image',
431 },
432 })
433 vi.clearAllMocks()
434
435 await client.generate({ prompt: 'A quiet desk', numberOfImages: 2 })
436
437 expect(latestSnapshotState()).toEqual(
438 expect.objectContaining({
439 input: { prompt: 'A quiet desk', numberOfImages: 2 },
440 progress: null,
441 preview: {
442 kind: 'image',
443 items: [
444 {
445 src: 'https://example.com/image.png',
446 sourceType: 'url',
447 },
448 {
449 src: 'data:image/png;base64,iVBORw0KGgo=',
450 sourceType: 'base64',
451 mimeType: 'image/png',
452 },
453 ],
454 },
455 }),
456 )
457
458 client.dispose()
459 })
460
461 it('tracks streamed progress in generation snapshots', async () => {
462 const connect: ConnectConnectionAdapter['connect'] = async function* () {
463 yield runStartedChunk('run-progress')
464 yield {
465 type: EventType.CUSTOM,
466 name: 'generation:progress',
467 value: { progress: 40, message: 'Rendering preview' },
468 timestamp: Date.now(),
469 } satisfies StreamChunk
470 yield resultChunk({ summary: 'short version' })
471 yield runFinishedChunk('run-progress')
472 }
473
474 const client = new GenerationClient({
475 threadId: 'summary-hook',
476 connection: { connect },
477 devtools: {
478 hookName: 'useSummarize',
479 outputKind: 'text',
480 },
481 })
482 vi.clearAllMocks()
483
484 await client.generate({ text: 'Long text' })
485
486 expect(latestSnapshotState()).toEqual(
487 expect.objectContaining({
488 input: { text: 'Long text' },
489 progress: {
490 value: 100,
491 message: 'Rendering preview',
492 },
493 preview: {
494 kind: 'text',
495 text: 'short version',
496 },
497 }),
498 )
499
500 client.dispose()
501 })
502
503 it('retains grouped generation snapshots for previous runs', async () => {
504 const connect: ConnectConnectionAdapter['connect'] = async function* (
505 _messages,
506 data,
507 ) {
508 const prompt = typeof data?.prompt === 'string' ? data.prompt : 'unknown'
509 const runId = `run-${prompt}`
510 yield runStartedChunk(runId)
511 yield {
512 type: EventType.CUSTOM,
513 name: 'generation:progress',
514 value: { progress: 70, message: `Rendering ${prompt}` },
515 timestamp: Date.now(),
516 } satisfies StreamChunk
517 yield resultChunk({
518 id: `img-${prompt}`,
519 model: 'image-model',
520 images: [{ url: `https://example.com/${prompt}.png` }],
521 })
522 yield runFinishedChunk(runId)
523 }
524
525 const client = new GenerationClient({
526 threadId: 'image-history',
527 connection: { connect },
528 devtools: {
529 hookName: 'useGenerateImage',
530 outputKind: 'image',
531 },
532 })
533 vi.clearAllMocks()
534
535 await client.generate({ prompt: 'one' })
536 await client.generate({ prompt: 'two' })
537
538 expect(latestGenerationRuns()).toEqual([
539 expect.objectContaining({
540 id: 'run-one',
541 input: { prompt: 'one' },
542 status: 'success',
543 isLoading: false,
544 progress: {
545 value: 100,
546 message: 'Rendering one',
547 },
548 result: expect.objectContaining({
549 id: 'img-one',
550 }),
551 preview: {
552 kind: 'image',
553 items: [
554 {
555 src: 'https://example.com/one.png',
556 sourceType: 'url',
557 },
558 ],
559 },
560 }),
561 expect.objectContaining({
562 id: 'run-two',
563 input: { prompt: 'two' },
564 status: 'success',
565 isLoading: false,
566 progress: {
567 value: 100,
568 message: 'Rendering two',
569 },
570 result: expect.objectContaining({
571 id: 'img-two',
572 }),
573 preview: {
574 kind: 'image',
575 items: [
576 {
577 src: 'https://example.com/two.png',
578 sourceType: 'url',
579 },
580 ],
581 },
582 }),
583 ])
584
585 client.dispose()
586 })
587
588 it('responds to devtools state requests for a generation hook', async () => {
589 const client = new GenerationClient({
590 threadId: 'gen-1',
591 fetcher: async () => ({ text: 'done' }),
592 devtools: {
593 framework: 'react',
594 hookName: 'useGenerateText',
595 outputKind: 'text',
596 },
597 })
598 client.mountDevtools()
599 vi.clearAllMocks()
600
601 eventClientMock.dispatch('devtools:request-state', {
602 targetHookId: 'gen-1',
603 })
604
605 expect(aiEventClient.emit).toHaveBeenCalledWith(
606 'hook:registered',
607 expect.objectContaining({
608 hookId: 'gen-1',
609 hookName: 'useGenerateText',
610 framework: 'react',
611 outputKind: 'text',
612 }),
613 )
614 expect(aiEventClient.emit).toHaveBeenCalledWith(
615 'hook:state-snapshot',
616 expect.objectContaining({
617 hookId: 'gen-1',
618 state: expect.objectContaining({
619 status: 'idle',
620 isLoading: false,
621 result: null,
622 activeRunId: null,
623 }),
624 }),
625 )
626
627 client.dispose()
628 })
629
630 it('emits errored run lifecycle for generation failures', async () => {
631 const client = new GenerationClient({
632 threadId: 'gen-1',
633 fetcher: async () => {
634 throw new Error('Generation failed')
635 },
636 devtools: {
637 hookName: 'useGenerateObject',
638 outputKind: 'structured',
639 },
640 })
641 vi.clearAllMocks()
642
643 await client.generate({ prompt: 'fail' })
644
645 expect(aiEventClient.emit).toHaveBeenCalledWith(
646 'run:errored',
647 expect.objectContaining({
648 hookId: 'gen-1',
649 runId: expect.any(String),
650 status: 'errored',
651 error: 'Generation failed',
652 }),
653 )
654 expect(aiEventClient.emit).toHaveBeenCalledWith(
655 'hook:state-snapshot',
656 expect.objectContaining({
657 hookId: 'gen-1',
658 state: expect.objectContaining({
659 status: 'error',
660 isLoading: false,
661 error: 'Generation failed',
662 }),
663 }),
664 )
665
666 client.dispose()
667 })
668
669 it('registers a generation hook for streaming connection mode', async () => {
670 const connect: ConnectConnectionAdapter['connect'] = async function* (
671 _messages,
672 _data,
673 _signal,
674 ) {
675 yield runStartedChunk('server-run-1')
676 yield resultChunk({ text: 'streamed' })
677 yield runFinishedChunk('server-run-1')
678 }
679 const connectSpy = vi.fn(connect)
680
681 const client = new GenerationClient({
682 threadId: 'gen-stream',
683 connection: {
684 connect: connectSpy,
685 },
686 devtools: {
687 hookName: 'useGenerateText',
688 outputKind: 'text',
689 },
690 })
691 vi.clearAllMocks()
692
693 await client.generate({ prompt: 'stream' })
694 const runContext = connectSpy.mock.calls[0]?.[3]
695
696 expect(runContext).toEqual(
697 expect.objectContaining({
698 threadId: 'gen-stream',
699 runId: expect.any(String),
700 }),
701 )
702
703 expect(aiEventClient.emit).toHaveBeenCalledWith(
704 'run:started',
705 expect.objectContaining({
706 hookId: 'gen-stream',
707 runId: 'server-run-1',
708 }),
709 )
710 expect(aiEventClient.emit).not.toHaveBeenCalledWith(
711 'run:started',
712 expect.objectContaining({
713 hookId: 'gen-stream',
714 runId: runContext?.runId,
715 }),
716 )
717 expect(eventClientMock.emitted('run:started')).toHaveLength(1)
718 expect(aiEventClient.emit).toHaveBeenCalledWith(
719 'run:completed',
720 expect.objectContaining({
721 hookId: 'gen-stream',
722 runId: 'server-run-1',
723 }),
724 )
725 expect(aiEventClient.emit).toHaveBeenCalledWith(
726 'hook:state-snapshot',
727 expect.objectContaining({
728 hookId: 'gen-stream',
729 state: expect.objectContaining({
730 status: 'success',
731 isLoading: false,
732 result: { text: 'streamed' },
733 }),
734 }),
735 )
736
737 client.dispose()
738 })
739
740 it('does not emit hook updates after disposal', async () => {
741 const deferred = createDeferred<{ text: string }>()
742 const client = new GenerationClient({
743 threadId: 'gen-1',
744 fetcher: async () => deferred.promise,
745 devtools: {
746 hookName: 'useGenerateText',
747 outputKind: 'text',
748 },
749 })
750 const generatePromise = client.generate({ prompt: 'slow' })
751 await Promise.resolve()
752
753 client.dispose()
754 const unregisteredIndex = eventClientMock.emit.mock.calls.findIndex(
755 ([eventName]) => eventName === 'hook:unregistered',
756 )
757 deferred.resolve({ text: 'late' })
758 await generatePromise
759
760 expect(unregisteredIndex).toBeGreaterThanOrEqual(0)
761 const emittedAfterDispose = eventClientMock.emit.mock.calls
762 .slice(unregisteredIndex + 1)
763 .map(([eventName]) => eventName)
764 expect(emittedAfterDispose).not.toContain('hook:updated')
765 expect(emittedAfterDispose).not.toContain('hook:state-snapshot')
766 })
767
768 it('uses the stream run id for video connection lifecycle events', async () => {
769 const connect: ConnectConnectionAdapter['connect'] = async function* (
770 _messages,
771 _data,
772 _signal,
773 ) {
774 yield runStartedChunk('server-video-run-1')
775 yield {
776 type: EventType.CUSTOM,
777 name: 'generation:result',
778 value: {
779 jobId: 'job-1',
780 status: 'completed',
781 url: 'https://example.com/video.mp4',
782 },
783 timestamp: Date.now(),
784 } satisfies StreamChunk
785 yield runFinishedChunk('server-video-run-1')
786 }
787 const connectSpy = vi.fn(connect)
788
789 const client = new VideoGenerationClient({
790 threadId: 'video-stream',
791 connection: {
792 connect: connectSpy,
793 },
794 devtools: {
795 hookName: 'useGenerateVideo',
796 outputKind: 'video',
797 },
798 })
799 vi.clearAllMocks()
800
801 await client.generate({ prompt: 'stream video' })
802 const runId = connectSpy.mock.calls[0]?.[3]?.runId ?? 'missing-run'
803
804 expect(aiEventClient.emit).not.toHaveBeenCalledWith(
805 'run:started',
806 expect.objectContaining({
807 hookId: 'video-stream',
808 runId,
809 }),
810 )
811 expect(eventClientMock.emitted('run:started')).toHaveLength(1)
812 expect(aiEventClient.emit).toHaveBeenCalledWith(
813 'run:completed',
814 expect.objectContaining({
815 hookId: 'video-stream',
816 runId: 'server-video-run-1',
817 }),
818 )
819
820 client.dispose()
821 })
822
823 it('registers a video hook and includes job state in snapshots', async () => {
824 const client = new VideoGenerationClient({
825 threadId: 'video-1',
826 fetcher: async () => ({
827 jobId: 'job-1',
828 status: 'completed',
829 url: 'https://example.com/video.mp4',
830 }),
831 devtools: {
832 framework: 'react',
833 hookName: 'useGenerateVideo',
834 outputKind: 'video',
835 },
836 })
837
838 await client.generate({ prompt: 'make video' })
839
840 expect(aiEventClient.emit).toHaveBeenCalledWith(
841 'hook:registered',
842 expect.objectContaining({
843 hookId: 'video-1',
844 hookName: 'useGenerateVideo',
845 framework: 'react',
846 outputKind: 'video',
847 }),
848 )
849 expect(aiEventClient.emit).toHaveBeenCalledWith(
850 'run:completed',
851 expect.objectContaining({
852 hookId: 'video-1',
853 status: 'completed',
854 }),
855 )
856 expect(aiEventClient.emit).toHaveBeenCalledWith(
857 'hook:state-snapshot',
858 expect.objectContaining({
859 hookId: 'video-1',
860 state: expect.objectContaining({
861 status: 'success',
862 isLoading: false,
863 jobId: 'job-1',
864 result: expect.objectContaining({
865 url: 'https://example.com/video.mp4',
866 }),
867 }),
868 }),
869 )
870
871 client.dispose()
872 })
873
874 it('includes input, progress, and renderable previews in video snapshots', async () => {
875 const connect: ConnectConnectionAdapter['connect'] = async function* () {
876 yield runStartedChunk('video-run')
877 yield {
878 type: EventType.CUSTOM,
879 name: 'video:job:created',
880 value: { jobId: 'job-1' },
881 timestamp: Date.now(),
882 } satisfies StreamChunk
883 yield {
884 type: EventType.CUSTOM,
885 name: 'video:status',
886 value: {
887 jobId: 'job-1',
888 status: 'processing',
889 progress: 60,
890 url: 'https://example.com/preview.mp4',
891 },
892 timestamp: Date.now(),
893 } satisfies StreamChunk
894 yield {
895 type: EventType.CUSTOM,
896 name: 'generation:result',
897 value: {
898 jobId: 'job-1',
899 status: 'completed',
900 url: 'https://example.com/final.mp4',
901 },
902 timestamp: Date.now(),
903 } satisfies StreamChunk
904 yield runFinishedChunk('video-run')
905 }
906
907 const client = new VideoGenerationClient({
908 threadId: 'video-hook',
909 connection: { connect },
910 devtools: {
911 hookName: 'useGenerateVideo',
912 outputKind: 'video',
913 },
914 })
915 vi.clearAllMocks()
916
917 await client.generate({ prompt: 'A flying car', duration: 4 })
918
919 expect(latestSnapshotState()).toEqual(
920 expect.objectContaining({
921 input: { prompt: 'A flying car', duration: 4 },
922 progress: {
923 value: 100,
924 },
925 preview: {
926 kind: 'video',
927 items: [
928 {
929 src: 'https://example.com/final.mp4',
930 sourceType: 'url',
931 },
932 ],
933 job: {
934 jobId: 'job-1',
935 status: 'completed',
936 progress: 100,
937 },
938 },
939 }),
940 )
941
942 client.dispose()
943 })
944
945 it('retains grouped video generation snapshots for previous runs', async () => {
946 const connect: ConnectConnectionAdapter['connect'] = async function* (
947 _messages,
948 data,
949 ) {
950 const prompt = typeof data?.prompt === 'string' ? data.prompt : 'unknown'
951 const runId = `video-run-${prompt}`
952 const jobId = `job-${prompt}`
953 yield runStartedChunk(runId)
954 yield {
955 type: EventType.CUSTOM,
956 name: 'video:job:created',
957 value: { jobId },
958 timestamp: Date.now(),
959 } satisfies StreamChunk
960 yield {
961 type: EventType.CUSTOM,
962 name: 'video:status',
963 value: {
964 jobId,
965 status: 'processing',
966 progress: 70,
967 },
968 timestamp: Date.now(),
969 } satisfies StreamChunk
970 yield {
971 type: EventType.CUSTOM,
972 name: 'generation:result',
973 value: {
974 jobId,
975 status: 'completed',
976 url: `https://example.com/${prompt}.mp4`,
977 },
978 timestamp: Date.now(),
979 } satisfies StreamChunk
980 yield runFinishedChunk(runId)
981 }
982
983 const client = new VideoGenerationClient({
984 threadId: 'video-history',
985 connection: { connect },
986 devtools: {
987 hookName: 'useGenerateVideo',
988 outputKind: 'video',
989 },
990 })
991 vi.clearAllMocks()
992
993 await client.generate({ prompt: 'one' })
994 await client.generate({ prompt: 'two' })
995
996 expect(latestGenerationRuns()).toEqual([
997 expect.objectContaining({
998 id: 'video-run-one',
999 input: { prompt: 'one' },
1000 status: 'success',
1001 isLoading: false,
1002 progress: {
1003 value: 100,
1004 },
1005 jobId: 'job-one',
1006 videoStatus: expect.objectContaining({
1007 jobId: 'job-one',
1008 status: 'completed',
1009 progress: 100,
1010 url: 'https://example.com/one.mp4',
1011 }),
1012 preview: {
1013 kind: 'video',
1014 items: [
1015 {
1016 src: 'https://example.com/one.mp4',
1017 sourceType: 'url',
1018 },
1019 ],
1020 job: {
1021 jobId: 'job-one',
1022 status: 'completed',
1023 progress: 100,
1024 },
1025 },
1026 }),
1027 expect.objectContaining({
1028 id: 'video-run-two',
1029 input: { prompt: 'two' },
1030 status: 'success',
1031 isLoading: false,
1032 progress: {
1033 value: 100,
1034 },
1035 jobId: 'job-two',
1036 videoStatus: expect.objectContaining({
1037 jobId: 'job-two',
1038 status: 'completed',
1039 progress: 100,
1040 url: 'https://example.com/two.mp4',
1041 }),
1042 }),
1043 ])
1044
1045 client.dispose()
1046 })
1047})