Open History to see the last commit
1import { describe, it, expect, vi } from 'vitest'
2import { EventType } from '@tanstack/ai/client'
3import { VideoGenerationClient } from '../src/video-generation-client'
4import type { StreamChunk } from '@tanstack/ai/client'
5import type { ConnectConnectionAdapter } from '../src/connection-adapters'
6import type { VideoGenerateInput } from '../src/generation-types'
7
8// Helper to create a mock connect-based adapter from StreamChunks
9function createMockConnection(
10 chunks: Array<StreamChunk>,
11): ConnectConnectionAdapter {
12 return {
13 async *connect() {
14 for (const chunk of chunks) {
15 yield chunk
16 }
17 },
18 }
19}
20
21describe('VideoGenerationClient', () => {
22 it.each(['', undefined])('throws when threadId is %j', (threadId) => {
23 expect(
24 () =>
25 new VideoGenerationClient({
26 threadId: threadId as never,
27 fetcher: async () => ({
28 jobId: 'job-1',
29 status: 'completed',
30 url: 'https://example.com/video.mp4',
31 }),
32 }),
33 ).toThrow(
34 'VideoGenerationClient: threadId is required (a non-empty string).',
35 )
36 })
37
38 describe('fetcher mode', () => {
39 it('should generate a result using fetcher', async () => {
40 const mockResult = {
41 jobId: 'job-1',
42 status: 'completed' as const,
43 url: 'https://example.com/video.mp4',
44 }
45 const onResult = vi.fn()
46 const onResultChange = vi.fn()
47
48 const client = new VideoGenerationClient({
49 threadId: 'thread-1',
50 fetcher: async () => mockResult,
51 onResult,
52 onResultChange,
53 })
54
55 await client.generate({ prompt: 'test video' })
56
57 expect(onResult).toHaveBeenCalledWith(mockResult)
58 expect(onResultChange).toHaveBeenCalledWith(mockResult)
59 expect(client.getResult()).toEqual(mockResult)
60 expect(client.getStatus()).toBe('success')
61 expect(client.getIsLoading()).toBe(false)
62 })
63
64 it('should handle fetcher errors', async () => {
65 const onError = vi.fn()
66 const onErrorChange = vi.fn()
67
68 const client = new VideoGenerationClient({
69 threadId: 'thread-1',
70 fetcher: async () => {
71 throw new Error('video fetch failed')
72 },
73 onError,
74 onErrorChange,
75 })
76
77 await client.generate({ prompt: 'test' })
78
79 expect(onError).toHaveBeenCalledWith(expect.any(Error))
80 expect(onError.mock.calls[0]![0].message).toBe('video fetch failed')
81 expect(client.getStatus()).toBe('error')
82 expect(client.getError()?.message).toBe('video fetch failed')
83 })
84
85 it('should track loading state during fetcher call', async () => {
86 const states: Array<boolean> = []
87
88 const client = new VideoGenerationClient({
89 threadId: 'thread-1',
90 fetcher: async () => ({
91 jobId: 'job-1',
92 status: 'completed' as const,
93 url: 'https://example.com/video.mp4',
94 }),
95 onLoadingChange: (isLoading) => states.push(isLoading),
96 })
97
98 await client.generate({ prompt: 'test' })
99
100 expect(states).toEqual([true, false])
101 })
102
103 it('should pass abort signal, threadId and runId to fetcher', async () => {
104 const fetcherSpy = vi.fn(
105 async (
106 _input: VideoGenerateInput,
107 options?: { signal: AbortSignal },
108 ) => {
109 expect(options).toBeDefined()
110 expect(options!.signal).toBeInstanceOf(AbortSignal)
111 expect(options!.signal.aborted).toBe(false)
112 return {
113 jobId: 'job-1',
114 status: 'completed' as const,
115 url: 'https://example.com/video.mp4',
116 }
117 },
118 )
119
120 const client = new VideoGenerationClient({
121 threadId: 'thread-1',
122 fetcher: fetcherSpy,
123 })
124
125 await client.generate({ prompt: 'test video' })
126
127 expect(fetcherSpy).toHaveBeenCalledTimes(1)
128 expect(fetcherSpy).toHaveBeenCalledWith(
129 { prompt: 'test video' },
130 {
131 signal: expect.any(AbortSignal),
132 threadId: 'thread-1',
133 runId: expect.any(String),
134 },
135 )
136 })
137
138 it('should not allow concurrent requests', async () => {
139 let resolveFirst: (value: {
140 jobId: string
141 status: 'completed'
142 url: string
143 }) => void
144 let callCount = 0
145
146 const client = new VideoGenerationClient({
147 threadId: 'thread-1',
148 fetcher: async () => {
149 callCount++
150 return new Promise<{
151 jobId: string
152 status: 'completed'
153 url: string
154 }>((resolve) => {
155 resolveFirst = resolve
156 })
157 },
158 })
159
160 const p1 = client.generate({ prompt: 'test' })
161 const p2 = client.generate({ prompt: 'test2' }) // should be no-op
162
163 resolveFirst!({
164 jobId: 'job-1',
165 status: 'completed',
166 url: 'https://example.com/video.mp4',
167 })
168 await p1
169 await p2
170
171 expect(callCount).toBe(1)
172 })
173 })
174
175 describe('connection mode', () => {
176 it('should process stream with video job lifecycle events', async () => {
177 const onResult = vi.fn()
178 const onJobCreated = vi.fn()
179 const onStatusUpdate = vi.fn()
180
181 const connection = createMockConnection([
182 {
183 type: EventType.RUN_STARTED,
184 runId: 'run-1',
185 threadId: 'thread-1',
186 timestamp: Date.now(),
187 },
188 {
189 type: EventType.CUSTOM,
190 name: 'video:job:created',
191 value: { jobId: 'job-123' },
192 timestamp: Date.now(),
193 },
194 {
195 type: EventType.CUSTOM,
196 name: 'video:status',
197 value: {
198 jobId: 'job-123',
199 status: 'processing',
200 progress: 50,
201 },
202 timestamp: Date.now(),
203 },
204 {
205 type: EventType.CUSTOM,
206 name: 'video:status',
207 value: {
208 jobId: 'job-123',
209 status: 'completed',
210 progress: 100,
211 },
212 timestamp: Date.now(),
213 },
214 {
215 type: EventType.CUSTOM,
216 name: 'generation:result',
217 value: {
218 jobId: 'job-123',
219 status: 'completed',
220 url: 'https://example.com/video.mp4',
221 },
222 timestamp: Date.now(),
223 },
224 {
225 type: EventType.RUN_FINISHED,
226 runId: 'run-1',
227 threadId: 'thread-1',
228 metadata: { tanstack: { finishReason: 'stop' as const } },
229 timestamp: Date.now(),
230 },
231 ])
232
233 const client = new VideoGenerationClient({
234 threadId: 'thread-1',
235 connection,
236 onResult,
237 onJobCreated,
238 onStatusUpdate,
239 })
240
241 await client.generate({ prompt: 'A flying car' })
242
243 expect(onJobCreated).toHaveBeenCalledWith('job-123')
244 expect(onStatusUpdate).toHaveBeenCalledTimes(2)
245 expect(onResult).toHaveBeenCalledWith(
246 expect.objectContaining({
247 jobId: 'job-123',
248 url: 'https://example.com/video.mp4',
249 }),
250 )
251 expect(client.getStatus()).toBe('success')
252 expect(client.getJobId()).toBe('job-123')
253 expect(client.getSnapshot().runId).toBeNull()
254 })
255
256 it('should track video status updates', async () => {
257 const onVideoStatusChange = vi.fn()
258
259 const connection = createMockConnection([
260 {
261 type: EventType.RUN_STARTED,
262 runId: 'run-1',
263 threadId: 'thread-1',
264 timestamp: Date.now(),
265 },
266 {
267 type: EventType.CUSTOM,
268 name: 'video:status',
269 value: {
270 jobId: 'job-1',
271 status: 'processing',
272 progress: 25,
273 },
274 timestamp: Date.now(),
275 },
276 {
277 type: EventType.CUSTOM,
278 name: 'generation:result',
279 value: {
280 jobId: 'job-1',
281 status: 'completed',
282 url: 'https://example.com/video.mp4',
283 },
284 timestamp: Date.now(),
285 },
286 {
287 type: EventType.RUN_FINISHED,
288 runId: 'run-1',
289 threadId: 'thread-1',
290 metadata: { tanstack: { finishReason: 'stop' as const } },
291 timestamp: Date.now(),
292 },
293 ])
294
295 const client = new VideoGenerationClient({
296 threadId: 'thread-1',
297 connection,
298 onVideoStatusChange,
299 })
300
301 await client.generate({ prompt: 'test' })
302
303 expect(onVideoStatusChange).toHaveBeenCalledWith({
304 jobId: 'job-1',
305 status: 'processing',
306 progress: 25,
307 })
308 expect(client.getVideoStatus()).toEqual({
309 jobId: 'job-1',
310 status: 'completed',
311 progress: 100,
312 url: 'https://example.com/video.mp4',
313 })
314 })
315
316 it('should handle RUN_ERROR from stream', async () => {
317 const onError = vi.fn()
318
319 const connection = createMockConnection([
320 {
321 type: EventType.RUN_STARTED,
322 runId: 'run-1',
323 threadId: 'thread-1',
324 timestamp: Date.now(),
325 },
326 {
327 type: EventType.RUN_ERROR,
328 message: 'Video generation failed',
329 runId: 'run-1',
330 error: { message: 'Video generation failed' },
331 timestamp: Date.now(),
332 },
333 ])
334
335 const client = new VideoGenerationClient({
336 threadId: 'thread-1',
337 connection,
338 onError,
339 })
340
341 await client.generate({ prompt: 'test' })
342
343 expect(onError).toHaveBeenCalledWith(expect.any(Error))
344 expect(client.getStatus()).toBe('error')
345 expect(client.getError()?.message).toBe('Video generation failed')
346 expect(client.getSnapshot().runId).toBeNull()
347 })
348
349 it('should report progress from video:status events', async () => {
350 const onProgress = vi.fn()
351
352 const connection = createMockConnection([
353 {
354 type: EventType.RUN_STARTED,
355 runId: 'run-1',
356 threadId: 'thread-1',
357 timestamp: Date.now(),
358 },
359 {
360 type: EventType.CUSTOM,
361 name: 'video:status',
362 value: {
363 jobId: 'job-1',
364 status: 'processing',
365 progress: 50,
366 },
367 timestamp: Date.now(),
368 },
369 {
370 type: EventType.RUN_FINISHED,
371 runId: 'run-1',
372 threadId: 'thread-1',
373 metadata: { tanstack: { finishReason: 'stop' as const } },
374 timestamp: Date.now(),
375 },
376 ])
377
378 const client = new VideoGenerationClient({
379 threadId: 'thread-1',
380 connection,
381 onProgress,
382 })
383
384 await client.generate({ prompt: 'test' })
385
386 expect(onProgress).toHaveBeenCalledWith(50)
387 })
388
389 it('should report progress from generation:progress events', async () => {
390 const onProgress = vi.fn()
391
392 const connection = createMockConnection([
393 {
394 type: EventType.RUN_STARTED,
395 runId: 'run-1',
396 threadId: 'thread-1',
397 timestamp: Date.now(),
398 },
399 {
400 type: EventType.CUSTOM,
401 name: 'generation:progress',
402 value: { progress: 75, message: 'Almost done' },
403 timestamp: Date.now(),
404 },
405 {
406 type: EventType.RUN_FINISHED,
407 runId: 'run-1',
408 threadId: 'thread-1',
409 metadata: { tanstack: { finishReason: 'stop' as const } },
410 timestamp: Date.now(),
411 },
412 ])
413
414 const client = new VideoGenerationClient({
415 threadId: 'thread-1',
416 connection,
417 onProgress,
418 })
419
420 await client.generate({ prompt: 'test' })
421
422 expect(onProgress).toHaveBeenCalledWith(75, 'Almost done')
423 })
424
425 it('should call onChunk for each stream chunk', async () => {
426 const onChunk = vi.fn()
427
428 const connection = createMockConnection([
429 {
430 type: EventType.RUN_STARTED,
431 runId: 'run-1',
432 threadId: 'thread-1',
433 timestamp: Date.now(),
434 },
435 {
436 type: EventType.CUSTOM,
437 name: 'generation:result',
438 value: {
439 jobId: 'job-1',
440 status: 'completed',
441 url: 'https://example.com/video.mp4',
442 },
443 timestamp: Date.now(),
444 },
445 {
446 type: EventType.RUN_FINISHED,
447 runId: 'run-1',
448 threadId: 'thread-1',
449 metadata: { tanstack: { finishReason: 'stop' as const } },
450 timestamp: Date.now(),
451 },
452 ])
453
454 const client = new VideoGenerationClient({
455 threadId: 'thread-1',
456 connection,
457 onChunk,
458 })
459
460 await client.generate({ prompt: 'test' })
461
462 expect(onChunk).toHaveBeenCalledTimes(3)
463 })
464
465 it('should pass body and input as data to connection', async () => {
466 const connectSpy = vi.fn(async function* () {
467 yield {
468 type: EventType.RUN_FINISHED as const,
469 runId: 'run-1',
470 threadId: 'thread-1',
471 metadata: { tanstack: { finishReason: 'stop' as const } },
472 timestamp: Date.now(),
473 }
474 })
475
476 const connection: ConnectConnectionAdapter = { connect: connectSpy }
477
478 const client = new VideoGenerationClient({
479 threadId: 'thread-1',
480 connection,
481 body: { model: 'runway-gen3' },
482 })
483
484 await client.generate({ prompt: 'A sunset', size: '1280x720' })
485
486 expect(connectSpy).toHaveBeenCalledWith(
487 [],
488 { model: 'runway-gen3', prompt: 'A sunset', size: '1280x720' },
489 expect.any(AbortSignal),
490 expect.objectContaining({
491 threadId: 'thread-1',
492 runId: expect.stringMatching(/^run-/),
493 }),
494 )
495 })
496 })
497
498 describe('stop()', () => {
499 it('should abort in-flight request and reset to idle', async () => {
500 let resolvePromise: (value: {
501 jobId: string
502 status: 'completed'
503 url: string
504 }) => void
505
506 const client = new VideoGenerationClient({
507 threadId: 'thread-1',
508 fetcher: async () => {
509 return new Promise<{
510 jobId: string
511 status: 'completed'
512 url: string
513 }>((resolve) => {
514 resolvePromise = resolve
515 })
516 },
517 })
518
519 const generatePromise = client.generate({ prompt: 'test' })
520 expect(client.getIsLoading()).toBe(true)
521 expect(client.getSnapshot().runId).toEqual(expect.any(String))
522
523 client.stop()
524 expect(client.getIsLoading()).toBe(false)
525 expect(client.getStatus()).toBe('idle')
526 expect(client.getSnapshot().runId).toBeNull()
527
528 resolvePromise!({
529 jobId: 'job-1',
530 status: 'completed',
531 url: 'https://example.com/video.mp4',
532 })
533 await generatePromise
534 })
535 })
536
537 describe('reset()', () => {
538 it('should clear all state and return to idle', async () => {
539 const onJobIdChange = vi.fn()
540 const onVideoStatusChange = vi.fn()
541
542 const connection = createMockConnection([
543 {
544 type: EventType.RUN_STARTED,
545 runId: 'run-1',
546 threadId: 'thread-1',
547 timestamp: Date.now(),
548 },
549 {
550 type: EventType.CUSTOM,
551 name: 'video:job:created',
552 value: { jobId: 'job-123' },
553 timestamp: Date.now(),
554 },
555 {
556 type: EventType.CUSTOM,
557 name: 'video:status',
558 value: {
559 jobId: 'job-123',
560 status: 'processing',
561 progress: 50,
562 },
563 timestamp: Date.now(),
564 },
565 {
566 type: EventType.CUSTOM,
567 name: 'generation:result',
568 value: {
569 jobId: 'job-123',
570 status: 'completed',
571 url: 'https://example.com/video.mp4',
572 },
573 timestamp: Date.now(),
574 },
575 {
576 type: EventType.RUN_FINISHED,
577 runId: 'run-1',
578 threadId: 'thread-1',
579 metadata: { tanstack: { finishReason: 'stop' as const } },
580 timestamp: Date.now(),
581 },
582 ])
583
584 const client = new VideoGenerationClient({
585 threadId: 'thread-1',
586 connection,
587 onJobIdChange,
588 onVideoStatusChange,
589 })
590
591 await client.generate({ prompt: 'test' })
592 expect(client.getResult()).not.toBeNull()
593 expect(client.getJobId()).toBe('job-123')
594 expect(client.getStatus()).toBe('success')
595
596 client.reset()
597 expect(client.getResult()).toBeNull()
598 expect(client.getJobId()).toBeNull()
599 expect(client.getVideoStatus()).toBeNull()
600 expect(client.getError()).toBeUndefined()
601 expect(client.getStatus()).toBe('idle')
602 expect(client.getSnapshot().runId).toBeNull()
603 })
604 })
605
606 describe('updateOptions()', () => {
607 it('should update body without recreating client', async () => {
608 const connectSpy = vi.fn(async function* () {
609 yield {
610 type: EventType.RUN_FINISHED as const,
611 runId: 'run-1',
612 threadId: 'thread-1',
613 metadata: { tanstack: { finishReason: 'stop' as const } },
614 timestamp: Date.now(),
615 }
616 })
617
618 const connection: ConnectConnectionAdapter = { connect: connectSpy }
619
620 const client = new VideoGenerationClient({
621 threadId: 'thread-1',
622 connection,
623 body: { model: 'old' },
624 })
625
626 client.updateOptions({ body: { model: 'new' } })
627 await client.generate({ prompt: 'test' })
628
629 expect(connectSpy).toHaveBeenCalledWith(
630 [],
631 { model: 'new', prompt: 'test' },
632 expect.any(AbortSignal),
633 expect.objectContaining({
634 threadId: 'thread-1',
635 runId: expect.stringMatching(/^run-/),
636 }),
637 )
638 })
639 })
640
641 describe('abort handling', () => {
642 it('should not set result if aborted mid-stream', async () => {
643 const onResult = vi.fn()
644 const onJobCreated = vi.fn()
645
646 const connection: ConnectConnectionAdapter = {
647 async *connect(_msgs, _data, signal) {
648 yield {
649 type: EventType.RUN_STARTED as const,
650 runId: 'run-1',
651 threadId: 'thread-1',
652 timestamp: Date.now(),
653 }
654 yield {
655 type: EventType.CUSTOM as const,
656 name: 'video:job:created',
657 value: { jobId: 'job-123' },
658 timestamp: Date.now(),
659 }
660 // Wait until abort is triggered
661 await new Promise<void>((resolve) => {
662 signal?.addEventListener('abort', () => resolve())
663 })
664 // Adapter honors abort signal and stops yielding
665 if (signal?.aborted) return
666 yield {
667 type: EventType.CUSTOM as const,
668 name: 'generation:result',
669 value: {
670 jobId: 'job-123',
671 status: 'completed',
672 url: 'https://example.com/video.mp4',
673 },
674 timestamp: Date.now(),
675 }
676 },
677 }
678
679 const client = new VideoGenerationClient({
680 threadId: 'thread-1',
681 connection,
682 onResult,
683 onJobCreated,
684 })
685
686 const generatePromise = client.generate({ prompt: 'test' })
687 await new Promise((r) => setTimeout(r, 0))
688
689 client.stop()
690 await generatePromise
691
692 expect(onResult).not.toHaveBeenCalled()
693 expect(client.getResult()).toBeNull()
694 expect(client.getStatus()).toBe('idle')
695 })
696 })
697
698 describe('error wrapping', () => {
699 it('should wrap non-Error thrown values in Error', async () => {
700 const onError = vi.fn()
701
702 const client = new VideoGenerationClient({
703 threadId: 'thread-1',
704 fetcher: async () => {
705 throw 'video error string'
706 },
707 onError,
708 })
709
710 await client.generate({ prompt: 'test' })
711
712 expect(onError).toHaveBeenCalledWith(expect.any(Error))
713 expect(onError.mock.calls[0]![0].message).toBe('video error string')
714 expect(client.getError()?.message).toBe('video error string')
715 })
716
717 it('should throw if neither connection nor fetcher is provided', async () => {
718 const onError = vi.fn()
719
720 // @ts-expect-error verifying the runtime guard for JavaScript callers
721 const client = new VideoGenerationClient({
722 threadId: 'thread-1',
723 onError,
724 })
725
726 await client.generate({ prompt: 'test' })
727
728 expect(onError).toHaveBeenCalledWith(expect.any(Error))
729 expect(client.getError()?.message).toBe(
730 'VideoGenerationClient requires either a connection or fetcher option',
731 )
732 })
733 })
734
735 describe('sequential generation', () => {
736 it('should allow a second generation after the first completes', async () => {
737 let callCount = 0
738
739 const client = new VideoGenerationClient({
740 threadId: 'thread-1',
741 fetcher: async () => {
742 callCount++
743 return {
744 jobId: `job-${callCount}`,
745 status: 'completed' as const,
746 url: `https://example.com/video-${callCount}.mp4`,
747 }
748 },
749 })
750
751 await client.generate({ prompt: 'first' })
752 expect(client.getResult()?.jobId).toBe('job-1')
753
754 await client.generate({ prompt: 'second' })
755 expect(client.getResult()?.jobId).toBe('job-2')
756 expect(callCount).toBe(2)
757 })
758 })
759
760 describe('state transitions', () => {
761 it('should follow idle -> generating -> success', async () => {
762 const states: Array<string> = []
763
764 const client = new VideoGenerationClient({
765 threadId: 'thread-1',
766 fetcher: async () => ({
767 jobId: 'job-1',
768 status: 'completed' as const,
769 url: 'https://example.com/video.mp4',
770 }),
771 onStatusChange: (status) => states.push(status),
772 })
773
774 expect(client.getStatus()).toBe('idle')
775 await client.generate({ prompt: 'test' })
776
777 expect(states).toEqual(['generating', 'success'])
778 })
779
780 it('should follow idle -> generating -> error on failure', async () => {
781 const states: Array<string> = []
782
783 const client = new VideoGenerationClient({
784 threadId: 'thread-1',
785 fetcher: async () => {
786 throw new Error('fail')
787 },
788 onStatusChange: (status) => states.push(status),
789 })
790
791 await client.generate({ prompt: 'test' })
792
793 expect(states).toEqual(['generating', 'error'])
794 })
795 })
796})