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

use-generation.test.ts

1,217 lines35.3 KB

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