Open History to see the last commit
1import { beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest'
2import { createGeneration } from '../src/create-generation.svelte'
3import { createGenerateImage } from '../src/create-generate-image.svelte'
4import { createGenerateSpeech } from '../src/create-generate-speech.svelte'
5import { createTranscription } from '../src/create-transcription.svelte'
6import { createSummarize } from '../src/create-summarize.svelte'
7import { createGenerateVideo } from '../src/create-generate-video.svelte'
8import { createMockConnectionAdapter } from './test-utils'
9import { EventType, type StreamChunk } from '@tanstack/ai'
10import type {
11 PersistedArtifactRef,
12 TTSResult,
13 TranscriptionResult,
14} from '@tanstack/ai'
15import type {
16 ConnectConnectionAdapter,
17 RunAgentInputContext,
18} from '@tanstack/ai-client'
19
20// Helper to create generation stream chunks
21function createGenerationChunks(result: unknown): Array<StreamChunk> {
22 return [
23 {
24 type: EventType.RUN_STARTED,
25 runId: 'run-1',
26 threadId: 'thread-1',
27 timestamp: Date.now(),
28 },
29 {
30 type: EventType.CUSTOM,
31 name: 'generation:result',
32 value: result,
33 timestamp: Date.now(),
34 },
35 {
36 type: EventType.RUN_FINISHED,
37 runId: 'run-1',
38 threadId: 'thread-1',
39 finishReason: 'stop',
40 timestamp: Date.now(),
41 },
42 ]
43}
44
45// Helper to create video generation stream chunks
46function createVideoChunks(jobId: string, url: string): Array<StreamChunk> {
47 return [
48 {
49 type: EventType.RUN_STARTED,
50 runId: 'run-1',
51 threadId: 'thread-1',
52 timestamp: Date.now(),
53 },
54 {
55 type: EventType.CUSTOM,
56 name: 'video:job:created',
57 value: { jobId },
58 timestamp: Date.now(),
59 },
60 {
61 type: EventType.CUSTOM,
62 name: 'video:status',
63 value: { jobId, status: 'processing', progress: 50 },
64 timestamp: Date.now(),
65 },
66 {
67 type: EventType.CUSTOM,
68 name: 'generation:result',
69 value: { jobId, status: 'completed', url },
70 timestamp: Date.now(),
71 },
72 {
73 type: EventType.RUN_FINISHED,
74 runId: 'run-1',
75 threadId: 'thread-1',
76 finishReason: 'stop',
77 timestamp: Date.now(),
78 },
79 ]
80}
81
82const videoResumeSnapshot = {
83 schemaVersion: 1 as const,
84 resumeState: { threadId: 'thread-resume', runId: 'run-resume' },
85 status: 'running' as const,
86}
87
88function createRunContextCaptureAdapter(chunks: Array<StreamChunk>): {
89 adapter: ConnectConnectionAdapter
90 connect: ReturnType<typeof vi.fn>
91 runContexts: Array<RunAgentInputContext | undefined>
92} {
93 const runContexts: Array<RunAgentInputContext | undefined> = []
94 const connect = vi.fn()
95 const adapter: ConnectConnectionAdapter = {
96 async *connect(_messages, _data, _signal, runContext) {
97 connect(runContext)
98 runContexts.push(runContext)
99 for (const chunk of chunks) {
100 yield chunk
101 }
102 },
103 }
104 return { adapter, connect, runContexts }
105}
106
107// Snapshot hydration and removal both run through promise queues detached from
108// the caller, so tests wait a macrotask for them to settle.
109function flushAsync(): Promise<void> {
110 return new Promise((resolve) => setTimeout(resolve, 0))
111}
112
113// Helper to create error stream chunks
114function createErrorChunks(message: string): Array<StreamChunk> {
115 return [
116 {
117 type: EventType.RUN_STARTED,
118 runId: 'run-1',
119 threadId: 'thread-1',
120 timestamp: Date.now(),
121 },
122 {
123 type: EventType.RUN_ERROR,
124 message,
125 error: { message },
126 timestamp: Date.now(),
127 },
128 ]
129}
130
131describe('createGeneration', () => {
132 beforeEach(() => {
133 vi.clearAllMocks()
134 })
135
136 describe('initialization', () => {
137 it('should initialize with default state', () => {
138 const adapter = createMockConnectionAdapter()
139 const gen = createGeneration({
140 threadId: 'thread-1',
141 connection: adapter,
142 })
143
144 expect(gen.result).toBeNull()
145 expect(gen.isLoading).toBe(false)
146 expect(gen.error).toBeUndefined()
147 expect(gen.status).toBe('idle')
148 })
149
150 it('should throw if neither connection nor fetcher is provided', () => {
151 expect(() => createGeneration({ threadId: 'thread-1' })).toThrow(
152 'createGeneration requires either a connection or fetcher option',
153 )
154 })
155
156 it('should expose generate, stop, reset, and updateBody methods', () => {
157 const adapter = createMockConnectionAdapter()
158 const gen = createGeneration({
159 threadId: 'thread-1',
160 connection: adapter,
161 })
162
163 expect(typeof gen.generate).toBe('function')
164 expect(typeof gen.stop).toBe('function')
165 expect(typeof gen.reset).toBe('function')
166 expect(typeof gen.updateBody).toBe('function')
167 })
168 })
169
170 describe('fetcher mode', () => {
171 it('should generate a result using fetcher', async () => {
172 const mockResult = { id: '1', data: 'test' }
173 const onResult = vi.fn()
174
175 const gen = createGeneration({
176 threadId: 'thread-1',
177 fetcher: async () => mockResult,
178 onResult,
179 })
180
181 await gen.generate({ prompt: 'test' })
182
183 expect(gen.result).toEqual(mockResult)
184 expect(gen.status).toBe('success')
185 expect(gen.isLoading).toBe(false)
186 expect(onResult).toHaveBeenCalledWith(mockResult)
187 })
188
189 it('should handle fetcher errors', async () => {
190 const onError = vi.fn()
191
192 const gen = createGeneration({
193 threadId: 'thread-1',
194 fetcher: async () => {
195 throw new Error('fetch failed')
196 },
197 onError,
198 })
199
200 await gen.generate({ prompt: 'test' })
201
202 expect(gen.status).toBe('error')
203 expect(gen.error?.message).toBe('fetch failed')
204 expect(onError).toHaveBeenCalledWith(expect.any(Error))
205 })
206 })
207
208 describe('connection mode', () => {
209 it('should process stream and extract result', async () => {
210 const mockResult = {
211 id: '1',
212 images: [{ url: 'http://example.com/img.png' }],
213 }
214 const chunks = createGenerationChunks(mockResult)
215 const adapter = createMockConnectionAdapter({ chunks })
216
217 const gen = createGeneration({
218 threadId: 'thread-1',
219 connection: adapter,
220 })
221
222 await gen.generate({ prompt: 'test' })
223
224 expect(gen.result).toEqual(mockResult)
225 expect(gen.status).toBe('success')
226 })
227
228 it('should handle stream errors', async () => {
229 const chunks = createErrorChunks('Generation failed')
230 const adapter = createMockConnectionAdapter({ chunks })
231
232 const gen = createGeneration({
233 threadId: 'thread-1',
234 connection: adapter,
235 })
236
237 await gen.generate({ prompt: 'test' })
238
239 expect(gen.status).toBe('error')
240 expect(gen.error?.message).toBe('Generation failed')
241 })
242 it('repaints a hydrated running snapshot with no joinRun as an interrupted error on setup', async () => {
243 const { adapter, connect } = createRunContextCaptureAdapter([])
244 const hydrateGeneration = vi.fn(async () => ({
245 resumeSnapshot: {
246 schemaVersion: 1 as const,
247 resumeState: { threadId: 'thread-resume', runId: 'run-resume' },
248 status: 'running' as const,
249 },
250 activeRun: null,
251 }))
252 const gen = createGeneration({
253 threadId: 'running-hydrate',
254 // No `joinRun`, so the restored run cannot be tailed.
255 connection: { ...adapter, hydrateGeneration },
256 persistence: true,
257 })
258
259 await flushAsync()
260
261 expect(hydrateGeneration).toHaveBeenCalledWith('running-hydrate')
262 // Without a `joinRun` handler the restored run cannot be tailed, so it
263 // surfaces as an interrupted error instead of a `generating` status that
264 // would never settle.
265 expect(gen.error?.message).toMatch(/interrupted/)
266 expect(gen.status).toBe('error')
267 expect(gen.isLoading).toBe(false)
268 expect(gen.runId).toBeNull()
269 // Hydration only surfaces state; it never restarts the run.
270 expect(connect).not.toHaveBeenCalled()
271 })
272 })
273
274 describe('stop and reset', () => {
275 it('should stop generation and return to idle', async () => {
276 let resolvePromise: (value: any) => void
277
278 const gen = createGeneration({
279 threadId: 'thread-1',
280 fetcher: async () =>
281 new Promise((resolve) => {
282 resolvePromise = resolve
283 }),
284 })
285
286 const promise = gen.generate({ prompt: 'test' })
287
288 // Wait a tick for loading to be set
289 await new Promise((resolve) => setTimeout(resolve, 10))
290 expect(gen.isLoading).toBe(true)
291
292 gen.stop()
293
294 expect(gen.isLoading).toBe(false)
295 expect(gen.status).toBe('idle')
296
297 resolvePromise!({ id: '1' })
298 await promise.catch(() => {})
299 })
300
301 it('should reset all state', async () => {
302 const gen = createGeneration({
303 threadId: 'thread-1',
304 fetcher: async () => ({ id: '1' }),
305 })
306
307 await gen.generate({ prompt: 'test' })
308
309 expect(gen.result).toEqual({ id: '1' })
310
311 gen.reset()
312
313 expect(gen.result).toBeNull()
314 expect(gen.error).toBeUndefined()
315 expect(gen.status).toBe('idle')
316 })
317 })
318})
319
320describe('createGenerateImage', () => {
321 beforeEach(() => {
322 vi.clearAllMocks()
323 })
324
325 it('should initialize with default state', () => {
326 const adapter = createMockConnectionAdapter()
327 const gen = createGenerateImage({
328 threadId: 'thread-1',
329 connection: adapter,
330 })
331
332 expect(gen.result).toBeNull()
333 expect(gen.isLoading).toBe(false)
334 expect(gen.status).toBe('idle')
335 })
336
337 it('should generate images using fetcher', async () => {
338 const mockResult = {
339 id: 'img-1',
340 images: [{ url: 'http://example.com/img.png' }],
341 model: 'dall-e-3',
342 }
343
344 const gen = createGenerateImage({
345 threadId: 'thread-1',
346 fetcher: async () => mockResult,
347 })
348
349 await gen.generate({ prompt: 'A sunset' })
350
351 expect(gen.result).toEqual(mockResult)
352 expect(gen.status).toBe('success')
353 })
354
355 it('should generate images using connection', async () => {
356 const mockResult = {
357 images: [{ url: 'http://example.com/img.png' }],
358 model: 'dall-e-3',
359 }
360 const chunks = createGenerationChunks(mockResult)
361 const adapter = createMockConnectionAdapter({ chunks })
362
363 const gen = createGenerateImage({
364 threadId: 'thread-1',
365 connection: adapter,
366 })
367
368 await gen.generate({ prompt: 'A sunset' })
369
370 expect(gen.result).toEqual(mockResult)
371 expect(gen.status).toBe('success')
372 })
373
374 it('should handle errors', async () => {
375 const onError = vi.fn()
376
377 const gen = createGenerateImage({
378 threadId: 'thread-1',
379 fetcher: async () => {
380 throw new Error('Image generation failed')
381 },
382 onError,
383 })
384
385 await gen.generate({ prompt: 'test' })
386
387 expect(gen.status).toBe('error')
388 expect(gen.error?.message).toBe('Image generation failed')
389 expect(onError).toHaveBeenCalled()
390 })
391
392 it('should expose stop and reset', () => {
393 const adapter = createMockConnectionAdapter()
394 const gen = createGenerateImage({
395 threadId: 'thread-1',
396 connection: adapter,
397 })
398
399 expect(typeof gen.stop).toBe('function')
400 expect(typeof gen.reset).toBe('function')
401 })
402
403 it('restores a completed image result from a durable artifact url', async () => {
404 // createGenerateImage injects `reconstructImageResult`, so a restored
405 // complete snapshot repaints `result` with the durable serve url — as if the
406 // run had just finished.
407 const artifact: PersistedArtifactRef = {
408 role: 'output',
409 artifactId: 'artifact-image-1',
410 threadId: 'thread-img',
411 runId: 'run-img',
412 name: 'image.png',
413 mimeType: 'image/png',
414 size: 2048,
415 createdAt: '2026-07-06T00:00:00.000Z',
416 url: '/api/artifacts/artifact-image-1',
417 source: {
418 activity: 'image',
419 path: 'runs/run-img/image.png',
420 provider: 'test',
421 model: 'test-image',
422 mediaType: 'image',
423 },
424 }
425 const hydrateGeneration = vi.fn(async () => ({
426 resumeSnapshot: {
427 schemaVersion: 1 as const,
428 resumeState: null,
429 status: 'complete' as const,
430 activity: 'image' as const,
431 result: {
432 id: 'img-restored',
433 model: 'test-image',
434 artifacts: [artifact],
435 },
436 },
437 activeRun: null,
438 }))
439
440 const gen = createGenerateImage({
441 threadId: 'img-hydrate',
442 connection: { ...createMockConnectionAdapter(), hydrateGeneration },
443 persistence: true,
444 })
445
446 await flushAsync()
447
448 // The completed snapshot repaints `status` and rebuilds `result` from the
449 // durable serve url.
450 expect(gen.status).toBe('success')
451 expect(gen.result).toEqual({
452 id: 'img-restored',
453 model: 'test-image',
454 images: [{ url: '/api/artifacts/artifact-image-1' }],
455 artifacts: [artifact],
456 })
457 expect(gen.runId).toBeNull()
458 })
459})
460
461describe('createGenerateSpeech', () => {
462 beforeEach(() => {
463 vi.clearAllMocks()
464 })
465
466 it('should initialize with default state', () => {
467 const adapter = createMockConnectionAdapter()
468 const gen = createGenerateSpeech({
469 threadId: 'thread-1',
470 connection: adapter,
471 })
472
473 expect(gen.result).toBeNull()
474 expect(gen.isLoading).toBe(false)
475 expect(gen.status).toBe('idle')
476 })
477
478 it('should generate speech using fetcher', async () => {
479 const mockResult = {
480 id: 'tts-1',
481 audio: 'base64data',
482 format: 'mp3' as const,
483 model: 'tts-1',
484 }
485
486 const gen = createGenerateSpeech({
487 threadId: 'thread-1',
488 fetcher: async () => mockResult,
489 })
490
491 await gen.generate({ text: 'Hello world' })
492
493 expect(gen.result).toEqual(mockResult)
494 expect(gen.status).toBe('success')
495 })
496
497 it('should generate speech using connection', async () => {
498 const mockResult = { audio: 'base64data', format: 'mp3', model: 'tts-1' }
499 const chunks = createGenerationChunks(mockResult)
500 const adapter = createMockConnectionAdapter({ chunks })
501
502 const gen = createGenerateSpeech({
503 threadId: 'thread-1',
504 connection: adapter,
505 })
506
507 await gen.generate({ text: 'Hello world' })
508
509 expect(gen.result).toEqual(mockResult)
510 expect(gen.status).toBe('success')
511 })
512
513 it('should handle errors', async () => {
514 const onError = vi.fn()
515
516 const gen = createGenerateSpeech({
517 threadId: 'thread-1',
518 fetcher: async () => {
519 throw new Error('Speech generation failed')
520 },
521 onError,
522 })
523
524 await gen.generate({ text: 'test' })
525
526 expect(gen.status).toBe('error')
527 expect(gen.error?.message).toBe('Speech generation failed')
528 expect(onError).toHaveBeenCalled()
529 })
530
531 it('should stop and reset', async () => {
532 const gen = createGenerateSpeech({
533 threadId: 'thread-1',
534 fetcher: async () => ({
535 id: 'tts-1',
536 audio: 'base64data',
537 format: 'mp3' as const,
538 model: 'tts-1',
539 }),
540 })
541
542 await gen.generate({ text: 'Hello' })
543
544 expect(gen.result).not.toBeNull()
545
546 gen.reset()
547
548 expect(gen.result).toBeNull()
549 expect(gen.error).toBeUndefined()
550 expect(gen.status).toBe('idle')
551 })
552
553 it('restores a completed TTS result from a durable artifact url', async () => {
554 // createGenerateSpeech injects `reconstructSpeechResult`. `TTSResult.audio`
555 // is a bare base64 string that persistence never stores, so the restored
556 // clip is served from `artifacts[0].url` and `audio` stays empty.
557 const artifact: PersistedArtifactRef = {
558 role: 'output',
559 artifactId: 'artifact-speech-1',
560 threadId: 'thread-tts',
561 runId: 'run-tts',
562 name: 'speech.mp3',
563 mimeType: 'audio/mpeg',
564 size: 4096,
565 createdAt: '2026-07-06T00:00:00.000Z',
566 url: '/api/artifacts/artifact-speech-1',
567 source: {
568 activity: 'tts',
569 path: 'runs/run-tts/speech.mp3',
570 provider: 'test',
571 model: 'test-tts',
572 mediaType: 'audio',
573 },
574 }
575 const hydrateGeneration = vi.fn(async () => ({
576 resumeSnapshot: {
577 schemaVersion: 1 as const,
578 resumeState: null,
579 status: 'complete' as const,
580 activity: 'tts' as const,
581 result: {
582 id: 'tts-restored',
583 model: 'test-tts',
584 artifacts: [artifact],
585 },
586 },
587 activeRun: null,
588 }))
589
590 const gen = createGenerateSpeech({
591 threadId: 'tts-hydrate',
592 connection: { ...createMockConnectionAdapter(), hydrateGeneration },
593 persistence: true,
594 })
595
596 await flushAsync()
597
598 expect(gen.status).toBe('success')
599 expect(gen.result).toEqual({
600 id: 'tts-restored',
601 model: 'test-tts',
602 audio: '',
603 format: 'mpeg',
604 contentType: 'audio/mpeg',
605 artifacts: [artifact],
606 })
607 expect(gen.runId).toBeNull()
608 })
609})
610
611describe('createTranscription', () => {
612 beforeEach(() => {
613 vi.clearAllMocks()
614 })
615
616 it('should initialize with default state', () => {
617 const adapter = createMockConnectionAdapter()
618 const gen = createTranscription({
619 threadId: 'thread-1',
620 connection: adapter,
621 })
622
623 expect(gen.result).toBeNull()
624 expect(gen.isLoading).toBe(false)
625 expect(gen.status).toBe('idle')
626 })
627
628 it('should transcribe audio using fetcher', async () => {
629 const mockResult = {
630 id: 'tr-1',
631 text: 'Hello world',
632 model: 'whisper-1',
633 }
634
635 const gen = createTranscription({
636 threadId: 'thread-1',
637 fetcher: async () => mockResult,
638 })
639
640 await gen.generate({ audio: 'base64audio' })
641
642 expect(gen.result).toEqual(mockResult)
643 expect(gen.status).toBe('success')
644 })
645
646 it('should transcribe audio using connection', async () => {
647 const mockResult = { text: 'Hello world', model: 'whisper-1' }
648 const chunks = createGenerationChunks(mockResult)
649 const adapter = createMockConnectionAdapter({ chunks })
650
651 const gen = createTranscription({
652 threadId: 'thread-1',
653 connection: adapter,
654 })
655
656 await gen.generate({ audio: 'base64audio' })
657
658 expect(gen.result).toEqual(mockResult)
659 expect(gen.status).toBe('success')
660 })
661
662 it('should handle errors', async () => {
663 const onError = vi.fn()
664
665 const gen = createTranscription({
666 threadId: 'thread-1',
667 fetcher: async () => {
668 throw new Error('Transcription failed')
669 },
670 onError,
671 })
672
673 await gen.generate({ audio: 'base64audio' })
674
675 expect(gen.status).toBe('error')
676 expect(gen.error?.message).toBe('Transcription failed')
677 expect(onError).toHaveBeenCalled()
678 })
679
680 it('should stop and reset', async () => {
681 const gen = createTranscription({
682 threadId: 'thread-1',
683 fetcher: async () => ({
684 id: 'tr-1',
685 text: 'Hello world',
686 model: 'whisper-1',
687 }),
688 })
689
690 await gen.generate({ audio: 'base64audio' })
691
692 expect(gen.result).not.toBeNull()
693
694 gen.reset()
695
696 expect(gen.result).toBeNull()
697 expect(gen.error).toBeUndefined()
698 expect(gen.status).toBe('idle')
699 })
700})
701
702describe('createSummarize', () => {
703 beforeEach(() => {
704 vi.clearAllMocks()
705 })
706
707 it('should initialize with default state', () => {
708 const adapter = createMockConnectionAdapter()
709 const gen = createSummarize({ threadId: 'thread-1', connection: adapter })
710
711 expect(gen.result).toBeNull()
712 expect(gen.isLoading).toBe(false)
713 expect(gen.status).toBe('idle')
714 })
715
716 it('should summarize text using fetcher', async () => {
717 const mockResult = {
718 id: 'sum-1',
719 summary: 'A brief summary',
720 model: 'gpt-5.5',
721 usage: { promptTokens: 1, completionTokens: 1, totalTokens: 2 },
722 }
723
724 const gen = createSummarize({
725 threadId: 'thread-1',
726 fetcher: async () => mockResult,
727 })
728
729 await gen.generate({ text: 'Long text to summarize...' })
730
731 expect(gen.result).toEqual(mockResult)
732 expect(gen.status).toBe('success')
733 })
734
735 it('should summarize text using connection', async () => {
736 const mockResult = { summary: 'A brief summary', model: 'gpt-5.5' }
737 const chunks = createGenerationChunks(mockResult)
738 const adapter = createMockConnectionAdapter({ chunks })
739
740 const gen = createSummarize({ threadId: 'thread-1', connection: adapter })
741
742 await gen.generate({ text: 'Long text to summarize...' })
743
744 expect(gen.result).toEqual(mockResult)
745 expect(gen.status).toBe('success')
746 })
747
748 it('should handle errors', async () => {
749 const onError = vi.fn()
750
751 const gen = createSummarize({
752 threadId: 'thread-1',
753 fetcher: async () => {
754 throw new Error('Summarization failed')
755 },
756 onError,
757 })
758
759 await gen.generate({ text: 'test' })
760
761 expect(gen.status).toBe('error')
762 expect(gen.error?.message).toBe('Summarization failed')
763 expect(onError).toHaveBeenCalled()
764 })
765
766 it('should stop and reset', async () => {
767 const gen = createSummarize({
768 threadId: 'thread-1',
769 fetcher: async () => ({
770 id: 'sum-1',
771 summary: 'A brief summary',
772 model: 'gpt-5.5',
773 usage: { promptTokens: 1, completionTokens: 1, totalTokens: 2 },
774 }),
775 })
776
777 await gen.generate({ text: 'Long text...' })
778
779 expect(gen.result).not.toBeNull()
780
781 gen.reset()
782
783 expect(gen.result).toBeNull()
784 expect(gen.error).toBeUndefined()
785 expect(gen.status).toBe('idle')
786 })
787})
788
789describe('createGenerateVideo', () => {
790 beforeEach(() => {
791 vi.clearAllMocks()
792 })
793
794 it('should initialize with default state', () => {
795 const adapter = createMockConnectionAdapter()
796 const gen = createGenerateVideo({
797 threadId: 'thread-1',
798 connection: adapter,
799 })
800
801 expect(gen.result).toBeNull()
802 expect(gen.jobId).toBeNull()
803 expect(gen.videoStatus).toBeNull()
804 expect(gen.isLoading).toBe(false)
805 expect(gen.status).toBe('idle')
806 })
807
808 it('should throw if neither connection nor fetcher is provided', () => {
809 expect(() => createGenerateVideo({} as any)).toThrow(
810 'createGenerateVideo requires either a connection or fetcher option',
811 )
812 })
813
814 it('should generate video using fetcher', async () => {
815 const mockResult = {
816 jobId: 'job-1',
817 status: 'completed' as const,
818 url: 'https://example.com/video.mp4',
819 }
820
821 const gen = createGenerateVideo({
822 threadId: 'thread-1',
823 fetcher: async () => mockResult,
824 })
825
826 await gen.generate({ prompt: 'A flying car' })
827
828 expect(gen.result).toEqual(mockResult)
829 expect(gen.status).toBe('success')
830 })
831
832 it('should track video job lifecycle via connection', async () => {
833 const chunks = createVideoChunks('job-123', 'https://example.com/video.mp4')
834 const adapter = createMockConnectionAdapter({ chunks })
835 const onJobCreated = vi.fn()
836 const onStatusUpdate = vi.fn()
837
838 const gen = createGenerateVideo({
839 threadId: 'thread-1',
840 connection: adapter,
841 onJobCreated,
842 onStatusUpdate,
843 })
844
845 await gen.generate({ prompt: 'A flying car' })
846
847 expect(gen.result).toEqual(
848 expect.objectContaining({
849 jobId: 'job-123',
850 url: 'https://example.com/video.mp4',
851 }),
852 )
853 expect(gen.jobId).toBe('job-123')
854 expect(gen.status).toBe('success')
855 expect(onJobCreated).toHaveBeenCalledWith('job-123')
856 expect(onStatusUpdate).toHaveBeenCalled()
857 })
858
859 it('should handle video generation errors', async () => {
860 const chunks = createErrorChunks('Video generation failed')
861 const adapter = createMockConnectionAdapter({ chunks })
862 const onError = vi.fn()
863
864 const gen = createGenerateVideo({
865 threadId: 'thread-1',
866 connection: adapter,
867 onError,
868 })
869
870 await gen.generate({ prompt: 'test' })
871
872 expect(gen.status).toBe('error')
873 expect(gen.error?.message).toBe('Video generation failed')
874 expect(onError).toHaveBeenCalled()
875 })
876
877 it('should stop and reset', async () => {
878 const gen = createGenerateVideo({
879 threadId: 'thread-1',
880 fetcher: async () => ({
881 jobId: 'job-1',
882 status: 'completed' as const,
883 url: 'https://example.com/video.mp4',
884 }),
885 })
886
887 await gen.generate({ prompt: 'test' })
888
889 expect(gen.result).not.toBeNull()
890
891 gen.reset()
892
893 expect(gen.result).toBeNull()
894 expect(gen.jobId).toBeNull()
895 expect(gen.videoStatus).toBeNull()
896 expect(gen.status).toBe('idle')
897 })
898
899 it('does not auto-fire a video generation on setup from a hydrated running snapshot', async () => {
900 const { adapter, connect } = createRunContextCaptureAdapter([])
901 const hydrateGeneration = vi.fn(async () => ({
902 resumeSnapshot: videoResumeSnapshot,
903 activeRun: null,
904 }))
905 const gen = createGenerateVideo({
906 threadId: 'video-no-auto-fire',
907 // No `joinRun`, so the restored run cannot be tailed.
908 connection: { ...adapter, hydrateGeneration },
909 persistence: true,
910 })
911
912 await flushAsync()
913
914 // Hydration only surfaces state; it never restarts the run.
915 expect(connect).not.toHaveBeenCalled()
916 expect(gen.error?.message).toMatch(/interrupted/)
917 expect(gen.status).toBe('error')
918 expect(gen.isLoading).toBe(false)
919 expect(gen.runId).toBeNull()
920 })
921
922 it('should expose generate, stop, reset, and updateBody methods', () => {
923 const adapter = createMockConnectionAdapter()
924 const gen = createGenerateVideo({
925 threadId: 'thread-1',
926 connection: adapter,
927 })
928
929 expect(typeof gen.generate).toBe('function')
930 expect(typeof gen.stop).toBe('function')
931 expect(typeof gen.reset).toBe('function')
932 expect(typeof gen.updateBody).toBe('function')
933 })
934})
935
936describe('onResult transform', () => {
937 beforeEach(() => {
938 vi.clearAllMocks()
939 })
940
941 it('should transform result when onResult returns a value (fetcher)', async () => {
942 // Inference (issue #848): `onResult`'s parameter is contextually typed from
943 // the fetcher's return, and `result` narrows to the transform's return —
944 // no explicit type arguments needed.
945 const gen = createGeneration({
946 threadId: 'thread-1',
947 fetcher: async () => ({ id: '1', audio: 'base64data' }),
948 onResult: (raw) => ({ playable: raw.audio.length > 0 }),
949 })
950 expectTypeOf(gen.result).toEqualTypeOf<{ playable: boolean } | null>()
951
952 await gen.generate({ prompt: 'test' })
953
954 expect(gen.result).toEqual({ playable: true })
955 expect(gen.status).toBe('success')
956 })
957
958 it('should use raw result when onResult returns void', async () => {
959 const onResult = vi.fn()
960
961 const gen = createGeneration({
962 threadId: 'thread-1',
963 fetcher: async () => ({ id: '1', data: 'test' }),
964 onResult,
965 })
966
967 await gen.generate({ prompt: 'test' })
968
969 expect(onResult).toHaveBeenCalledWith({ id: '1', data: 'test' })
970 expect(gen.result).toEqual({ id: '1', data: 'test' })
971 })
972
973 it('should keep previous result when onResult returns null', async () => {
974 const gen = createGeneration({
975 threadId: 'thread-1',
976 fetcher: async () => ({ id: '1' }),
977 onResult: () => null,
978 })
979
980 await gen.generate({ prompt: 'test' })
981
982 // null return → keep previous (which was null initially)
983 expect(gen.result).toBeNull()
984 expect(gen.status).toBe('success')
985 })
986
987 it('should transform result from connection stream', async () => {
988 type StreamResult = { id: string; images: Array<string> }
989 const mockResult: StreamResult = { id: '1', images: ['img1', 'img2'] }
990 const chunks = createGenerationChunks(mockResult)
991 const adapter = createMockConnectionAdapter({ chunks })
992
993 // In connection mode there's no fetcher to infer `TResult` from, so annotate
994 // the `onResult` parameter — `TResult` infers from the annotation and
995 // `result` narrows to the transform's return. No explicit type args needed.
996 const gen = createGeneration({
997 threadId: 'thread-1',
998 connection: adapter,
999 onResult: (raw: StreamResult) => ({ count: raw.images.length }),
1000 })
1001 expectTypeOf(gen.result).toEqualTypeOf<{ count: number } | null>()
1002
1003 await gen.generate({ prompt: 'test' })
1004
1005 expect(gen.result).toEqual({ count: 2 })
1006 })
1007
1008 it('should work with createGenerateSpeech transform', async () => {
1009 const mockTTSResult: TTSResult = {
1010 id: '1',
1011 model: 'tts-1',
1012 audio: 'base64audio',
1013 format: 'mp3',
1014 contentType: 'audio/mpeg',
1015 }
1016
1017 // Inference (issue #848): the wrapper hooks infer the output type from
1018 // `onResult` with no explicit type argument. `raw` is contextually typed
1019 // as `TTSResult`.
1020 const gen = createGenerateSpeech({
1021 threadId: 'thread-1',
1022 fetcher: async () => mockTTSResult,
1023 onResult: (raw) => ({
1024 audioUrl: `data:${raw.contentType};base64,${raw.audio}`,
1025 }),
1026 })
1027 expectTypeOf(gen.result).toEqualTypeOf<{ audioUrl: string } | null>()
1028
1029 await gen.generate({ text: 'Hello' })
1030
1031 expect(gen.result).toEqual({
1032 audioUrl: 'data:audio/mpeg;base64,base64audio',
1033 })
1034 })
1035
1036 it('infers the raw result type when no onResult is provided', () => {
1037 const gen = createTranscription({
1038 threadId: 'thread-1',
1039 fetcher: async () => ({ id: '1', text: 'hi', model: 'whisper-1' }),
1040 })
1041 // Without a transform, `result` stays the raw TranscriptionResult.
1042 expectTypeOf(gen.result).toEqualTypeOf<TranscriptionResult | null>()
1043 })
1044
1045 it('narrows the wrapper result type to the transform return', () => {
1046 const gen = createTranscription({
1047 threadId: 'thread-1',
1048 fetcher: async () => ({ id: '1', text: 'hi', model: 'whisper-1' }),
1049 onResult: (res) => res.text,
1050 })
1051 expectTypeOf(gen.result).toEqualTypeOf<string | null>()
1052 })
1053})