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

inject-generation.test.ts

337 lines10.4 KB

1import { Component } from '@angular/core'
2import { getTestBed, TestBed } from '@angular/core/testing'
3import {
4 BrowserDynamicTestingModule,
5 platformBrowserDynamicTesting,
6} from '@angular/platform-browser-dynamic/testing'
7import { describe, expect, it, vi } from 'vitest'
8import { injectGeneration } from '../src/inject-generation'
9import { injectGenerateVideo } from '../src/inject-generate-video'
10import { injectGenerateImage } from '../src/inject-generate-image'
11import { injectGenerateSpeech } from '../src/inject-generate-speech'
12import type { PersistedArtifactRef, StreamChunk } from '@tanstack/ai'
13import type {
14 ConnectConnectionAdapter,
15 RunAgentInputContext,
16} from '@tanstack/ai-client'
17​
18// Ensure TestBed is initialized in this module's scope, regardless of whether
19// the setup file's initialization was in a different module context (possible
20// when the Angular plugin creates separate ESM module instances for compiled
21// and setup files in Vitest).
22const testBedInstance = getTestBed() as any
23if (
24 testBedInstance._compiler === null ||
25 testBedInstance._compiler === undefined
26) {
27 getTestBed().initTestEnvironment(
28 BrowserDynamicTestingModule,
29 platformBrowserDynamicTesting(),
30 )
32​
33function renderInjectGeneration(options: any) {
34 @Component({ standalone: true, template: '' })
35 class Host {
36 gen = injectGeneration(options)
37 }
38 const fixture = TestBed.createComponent(Host)
39 fixture.detectChanges()
40 return {
41 get result() {
42 return fixture.componentInstance.gen
43 },
44 flush: () => fixture.detectChanges(),
45 destroy: () => fixture.destroy(),
46 }
48​
49function renderInjectGenerateVideo(options: any) {
50 @Component({ standalone: true, template: '' })
51 class Host {
52 gen = injectGenerateVideo(options)
53 }
54 const fixture = TestBed.createComponent(Host)
55 fixture.detectChanges()
56 return {
57 get result() {
58 return fixture.componentInstance.gen
59 },
60 flush: () => fixture.detectChanges(),
61 destroy: () => fixture.destroy(),
62 }
64​
65function renderInjectGenerateImage(options: any) {
66 @Component({ standalone: true, template: '' })
67 class Host {
68 gen = injectGenerateImage(options)
69 }
70 const fixture = TestBed.createComponent(Host)
71 fixture.detectChanges()
72 return {
73 get result() {
74 return fixture.componentInstance.gen
75 },
76 flush: () => fixture.detectChanges(),
77 destroy: () => fixture.destroy(),
78 }
80​
81function renderInjectGenerateSpeech(options: any) {
82 @Component({ standalone: true, template: '' })
83 class Host {
84 gen = injectGenerateSpeech(options)
85 }
86 const fixture = TestBed.createComponent(Host)
87 fixture.detectChanges()
88 return {
89 get result() {
90 return fixture.componentInstance.gen
91 },
92 flush: () => fixture.detectChanges(),
93 destroy: () => fixture.destroy(),
94 }
96​
97const videoResumeSnapshot = {
98 schemaVersion: 1 as const,
99 resumeState: { threadId: 'thread-resume', runId: 'run-resume' },
100 status: 'running' as const,
102​
103// Hydration and snapshot removal both run through awaited promise chains, so
104// drain the microtask queue rather than awaiting a single tick.
105async function flushPromises(): Promise<void> {
106 for (let i = 0; i < 5; i++) {
107 await Promise.resolve()
108 }
110​
111function createRunContextCaptureAdapter(chunks: Array<StreamChunk>): {
112 adapter: ConnectConnectionAdapter
113 connect: ReturnType<typeof vi.fn>
114 runContexts: Array<RunAgentInputContext | undefined>
115} {
116 const runContexts: Array<RunAgentInputContext | undefined> = []
117 const connect = vi.fn()
118 const adapter: ConnectConnectionAdapter = {
119 async *connect(_messages, _data, _signal, runContext) {
120 connect(runContext)
121 runContexts.push(runContext)
122 for (const chunk of chunks) {
123 yield chunk
124 }
125 },
126 }
127 return { adapter, connect, runContexts }
129​
130describe('injectGeneration', () => {
131 it('initializes idle with a fetcher and generates a result', async () => {
132 const fetcher = vi.fn(async () => ({ value: 42 }))
133 const { result, flush } = renderInjectGeneration({ fetcher })
134​
135 expect(result.status()).toBe('idle')
136 expect(result.result()).toBeNull()
137​
138 await result.generate({ prompt: 'x' })
139 flush()
140 expect(result.result()).toEqual({ value: 42 })
141 expect(fetcher).toHaveBeenCalled()
142 })
143​
144 it('throws without connection or fetcher', () => {
145 expect(() => renderInjectGeneration({})).toThrow()
146 })
147​
148 it('transforms the result when onResult returns a value', async () => {
149 const { result, flush } = renderInjectGeneration({
150 fetcher: async () => ({ id: '1', audio: 'base64data' }),
151 onResult: (raw: { id: string; audio: string }) => ({
152 playable: raw.audio.length > 0,
153 }),
154 })
155​
156 await result.generate({ prompt: 'x' })
157 flush()
158 expect(result.result()).toEqual({ playable: true })
159 expect(result.status()).toBe('success')
160 })
161 it('hydrates a snapshot from the server on mount', async () => {
162 const { adapter, connect } = createRunContextCaptureAdapter([])
163 const hydrateGeneration = vi.fn(async () => ({
164 resumeSnapshot: {
165 schemaVersion: 1 as const,
166 resumeState: { threadId: 'thread-stored', runId: 'run-stored' },
167 status: 'running' as const,
168 },
169 activeRun: null,
170 }))
171 const { result } = renderInjectGeneration({
172 threadId: 'hydrate-me',
173 connection: { ...adapter, hydrateGeneration },
174 persistence: true,
175 })
176​
177 await flushPromises()
178​
179 expect(hydrateGeneration).toHaveBeenCalledWith('hydrate-me')
180 // Hydration only surfaces state; it never restarts the run.
181 expect(connect).not.toHaveBeenCalled()
182 // Without a `joinRun` handler the restored run cannot be tailed, so it
183 // surfaces as an interrupted error instead of a `generating` status
184 // that would never settle.
185 expect(result.error()?.message).toMatch(/interrupted/)
186 expect(result.status()).toBe('error')
187 expect(result.isLoading()).toBe(false)
188 expect(result.runId()).toBeNull()
189 })
190})
191​
192describe('injectGenerateVideo', () => {
193 it('does not auto-fire a video generation after render from a hydrated running snapshot', async () => {
194 const { adapter, connect } = createRunContextCaptureAdapter([])
195 const hydrateGeneration = vi.fn(async () => ({
196 resumeSnapshot: videoResumeSnapshot,
197 activeRun: null,
198 }))
199 const { result } = renderInjectGenerateVideo({
200 threadId: 'video-no-auto-fire',
201 // No `joinRun`, so the restored run cannot be tailed.
202 connection: { ...adapter, hydrateGeneration },
203 persistence: true,
204 })
205​
206 await flushPromises()
207​
208 // Hydration only surfaces state; it never restarts the run.
209 expect(connect).not.toHaveBeenCalled()
210 expect(result.error()?.message).toMatch(/interrupted/)
211 expect(result.status()).toBe('error')
212 expect(result.isLoading()).toBe(false)
213 expect(result.runId()).toBeNull()
214 })
215})
216​
217describe('injectGenerateImage', () => {
218 it('restores a completed image result from a durable artifact url', async () => {
219 // injectGenerateImage injects `reconstructImageResult`, so a restored
220 // complete snapshot repaints `result` with the durable serve url — as if the
221 // run had just finished.
222 const artifact: PersistedArtifactRef = {
223 role: 'output',
224 artifactId: 'artifact-image-1',
225 threadId: 'thread-img',
226 runId: 'run-img',
227 name: 'image.png',
228 mimeType: 'image/png',
229 size: 2048,
230 createdAt: '2026-07-06T00:00:00.000Z',
231 url: '/api/artifacts/artifact-image-1',
232 source: {
233 activity: 'image',
234 path: 'runs/run-img/image.png',
235 provider: 'test',
236 model: 'test-image',
237 mediaType: 'image',
238 },
239 }
240 const { adapter, connect } = createRunContextCaptureAdapter([])
241 const hydrateGeneration = vi.fn(async () => ({
242 resumeSnapshot: {
243 schemaVersion: 1 as const,
244 resumeState: null,
245 status: 'complete' as const,
246 activity: 'image' as const,
247 result: {
248 id: 'img-restored',
249 model: 'test-image',
250 artifacts: [artifact],
251 },
252 },
253 activeRun: null,
254 }))
255 const { result } = renderInjectGenerateImage({
256 threadId: 'img-hydrate',
257 connection: { ...adapter, hydrateGeneration },
258 persistence: true,
259 })
260​
261 await flushPromises()
262​
263 expect(hydrateGeneration).toHaveBeenCalledWith('img-hydrate')
264​
265 // A completed snapshot repaints the normal `status` field to `success`.
266 expect(result.status()).toBe('success')
267 expect(connect).not.toHaveBeenCalled()
268 expect(result.result()).toEqual({
269 id: 'img-restored',
270 model: 'test-image',
271 images: [{ url: '/api/artifacts/artifact-image-1' }],
272 artifacts: [artifact],
273 })
274 expect(result.runId()).toBeNull()
275 })
276})
277​
278describe('injectGenerateSpeech', () => {
279 it('restores a completed TTS result from a durable artifact url', async () => {
280 // injectGenerateSpeech injects `reconstructSpeechResult`. `TTSResult.audio`
281 // is a bare base64 string that persistence never stores, so the restored
282 // clip is served from `artifacts[0].url` and `audio` stays empty.
283 const artifact: PersistedArtifactRef = {
284 role: 'output',
285 artifactId: 'artifact-speech-1',
286 threadId: 'thread-tts',
287 runId: 'run-tts',
288 name: 'speech.mp3',
289 mimeType: 'audio/mpeg',
290 size: 4096,
291 createdAt: '2026-07-06T00:00:00.000Z',
292 url: '/api/artifacts/artifact-speech-1',
293 source: {
294 activity: 'tts',
295 path: 'runs/run-tts/speech.mp3',
296 provider: 'test',
297 model: 'test-tts',
298 mediaType: 'audio',
299 },
300 }
301 const { adapter, connect } = createRunContextCaptureAdapter([])
302 const hydrateGeneration = vi.fn(async () => ({
303 resumeSnapshot: {
304 schemaVersion: 1 as const,
305 resumeState: null,
306 status: 'complete' as const,
307 activity: 'tts' as const,
308 result: {
309 id: 'tts-restored',
310 model: 'test-tts',
311 artifacts: [artifact],
312 },
313 },
314 activeRun: null,
315 }))
316 const { result } = renderInjectGenerateSpeech({
317 threadId: 'tts-hydrate',
318 connection: { ...adapter, hydrateGeneration },
319 persistence: true,
320 })
321​
322 await flushPromises()
323​
324 expect(hydrateGeneration).toHaveBeenCalledWith('tts-hydrate')
325 expect(result.status()).toBe('success')
326 expect(connect).not.toHaveBeenCalled()
327 expect(result.result()).toEqual({
328 id: 'tts-restored',
329 model: 'test-tts',
330 audio: '',
331 format: 'mpeg',
332 contentType: 'audio/mpeg',
333 artifacts: [artifact],
334 })
335 expect(result.runId()).toBeNull()
336 })
337})