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