Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { z } from 'zod'
3import { EventType } from '@tanstack/ai/client'
4import { Component, signal } from '@angular/core'
5import { TestBed } from '@angular/core/testing'
6import { ChatClient } from '@tanstack/ai-client'
7import { injectChat } from '../src/inject-chat'
8import {
9 createInterruptResumeSnapshot,
10 createMockConnectionAdapter,
11 createTextChunks,
12 renderInjectChat,
13} from './test-utils'
14
15const tick = () => new Promise((r) => setTimeout(r, 0))
16
17afterEach(() => {
18 vi.restoreAllMocks()
19})
20
21describe('injectChat', () => {
22 describe('interrupt state', () => {
23 it('projects one immutable reactive snapshot', () => {
24 const onInterruptStateChange = vi.fn()
25 const { result, flush } = renderInjectChat({
26 threadId: 'thread-1',
27 connection: createMockConnectionAdapter(),
28 initialResumeSnapshot: createInterruptResumeSnapshot(),
29 onInterruptStateChange,
30 })
31
32 expect(Object.isFrozen(result.interrupts())).toBe(true)
33 expect(result.interrupts()[0]).toMatchObject({
34 id: 'staged-interrupt',
35 status: 'pending',
36 })
37 expect(result.interrupts()[1]).toMatchObject({
38 id: 'invalid-interrupt',
39 status: 'pending',
40 })
41 expect(result.interruptErrors()).toEqual([])
42 expect(result.resuming()).toBe(false)
43 expect(result.interrupts()[0]).toEqual(
44 expect.objectContaining({
45 resolveInterrupt: expect.any(Function),
46 cancel: expect.any(Function),
47 clearResolution: expect.any(Function),
48 }),
49 )
50
51 result.resolveInterrupts(false)
52 TestBed.flushEffects()
53 flush()
54 expect(result.interruptErrors()[0]?.code).toBe(
55 'unsupported-bulk-operation',
56 )
57 expect(onInterruptStateChange).toHaveBeenLastCalledWith(
58 expect.objectContaining({
59 interrupts: result.interrupts(),
60 interruptErrors: result.interruptErrors(),
61 }),
62 { source: 'live' },
63 )
64 })
65
66 it('delegates every root interrupt control to ChatClient', async () => {
67 const resolve = vi
68 .spyOn(ChatClient.prototype, 'resolveInterrupts')
69 .mockImplementation(() => {})
70 const cancel = vi
71 .spyOn(ChatClient.prototype, 'cancelInterrupts')
72 .mockImplementation(() => {})
73 const retry = vi
74 .spyOn(ChatClient.prototype, 'retryInterrupts')
75 .mockImplementation(() => {})
76 const unsafe = vi
77 .spyOn(ChatClient.prototype, 'resumeInterruptsUnsafe')
78 .mockResolvedValue(true)
79 const { result } = renderInjectChat({
80 threadId: 'thread-1',
81 connection: createMockConnectionAdapter(),
82 })
83 const resolver = () => undefined
84 const resume = [{ interruptId: 'one', status: 'cancelled' as const }]
85
86 result.resolveInterrupts(resolver)
87 result.cancelInterrupts()
88 result.retryInterrupts()
89 await expect(result.resumeInterruptsUnsafe(resume)).resolves.toBe(true)
90
91 expect(resolve).toHaveBeenCalledWith(resolver)
92 expect(cancel).toHaveBeenCalledOnce()
93 expect(retry).toHaveBeenCalledOnce()
94 expect(unsafe).toHaveBeenCalledWith(resume, undefined)
95 })
96 })
97
98 it('initializes with default state', () => {
99 const adapter = createMockConnectionAdapter()
100 const { result } = renderInjectChat({
101 threadId: 'thread-1',
102 connection: adapter,
103 })
104
105 expect(result.messages()).toEqual([])
106 expect(result.isLoading()).toBe(false)
107 expect(result.error()).toBeUndefined()
108 expect(result.status()).toBe('ready')
109 expect(result.isSubscribed()).toBe(false)
110 expect(result.connectionStatus()).toBe('disconnected')
111 expect(result.sessionGenerating()).toBe(false)
112 })
113})
114
115describe('injectChat — streaming', () => {
116 it('streams assistant text into messages', async () => {
117 const adapter = createMockConnectionAdapter({
118 chunks: createTextChunks('Hello there'),
119 })
120 const { result, flush } = renderInjectChat({
121 threadId: 'thread-1',
122 connection: adapter,
123 })
124
125 await result.sendMessage('Hi')
126 await tick()
127 flush()
128
129 const assistant = result.messages().find((m) => m.role === 'assistant')
130 expect(assistant).toBeDefined()
131 expect(result.isLoading()).toBe(false)
132 })
133
134 it('merges sendMessage options.body into the request', async () => {
135 let capturedData: Record<string, unknown> | undefined
136 const adapter = createMockConnectionAdapter({
137 chunks: createTextChunks('Hello there'),
138 onConnect: (_messages, data) => {
139 capturedData = data
140 },
141 })
142 const { result, flush } = renderInjectChat({
143 threadId: 'thread-1',
144 connection: adapter,
145 forwardedProps: { provider: 'openai' },
146 })
147
148 await result.sendMessage('Hi', {
149 whenBusy: 'queue',
150 body: { provider: 'anthropic', attachmentIds: ['a1', 'a2'] },
151 })
152 await tick()
153 flush()
154
155 expect(capturedData?.['provider']).toBe('anthropic')
156 expect(capturedData?.['attachmentIds']).toEqual(['a1', 'a2'])
157 expect(capturedData?.['whenBusy']).toBeUndefined()
158 })
159
160 it('initializes with provided messages', () => {
161 const adapter = createMockConnectionAdapter()
162 const initialMessages = [
163 {
164 id: 'msg-1',
165 role: 'user' as const,
166 parts: [{ type: 'text' as const, content: 'Hello' }],
167 createdAt: new Date(),
168 },
169 ]
170 const { result } = renderInjectChat({
171 threadId: 'thread-1',
172 connection: adapter,
173 initialMessages,
174 })
175 expect(result.messages()).toEqual(initialMessages)
176 })
177
178 it('clear() empties messages', async () => {
179 const adapter = createMockConnectionAdapter({
180 chunks: createTextChunks('Hi'),
181 })
182 const { result, flush } = renderInjectChat({
183 threadId: 'thread-1',
184 connection: adapter,
185 })
186 await result.sendMessage('Hi')
187 await tick()
188 result.clear()
189 flush()
190 expect(result.messages()).toEqual([])
191 })
192})
193
194describe('injectChat — reactive options', () => {
195 it('subscribes/unsubscribes when a live signal flips', async () => {
196 const adapter = createMockConnectionAdapter()
197 const live = signal(false)
198 const { result, flush } = renderInjectChat({
199 threadId: 'thread-1',
200 connection: adapter,
201 live,
202 })
203
204 await tick()
205 flush()
206 expect(result.isSubscribed()).toBe(false)
207
208 live.set(true)
209 flush()
210 await tick()
211 expect(result.isSubscribed()).toBe(true)
212
213 live.set(false)
214 flush()
215 await tick()
216 expect(result.isSubscribed()).toBe(false)
217 })
218
219 it('pushes forwardedProps-signal changes to the client', async () => {
220 const updateSpy = vi.spyOn(ChatClient.prototype, 'updateOptions')
221 try {
222 const adapter = createMockConnectionAdapter()
223 const forwardedProps = signal<Record<string, any>>({ model: 'a' })
224 const { flush } = renderInjectChat({
225 threadId: 'thread-1',
226 connection: adapter,
227 forwardedProps,
228 })
229
230 // initial effect run picks up { model: 'a' }
231 flush()
232 await tick()
233 updateSpy.mockClear()
234
235 forwardedProps.set({ model: 'b' })
236 flush()
237 await tick()
238
239 expect(updateSpy).toHaveBeenCalled()
240 expect(updateSpy).toHaveBeenCalledWith(
241 expect.objectContaining({ forwardedProps: { model: 'b' } }),
242 )
243 } finally {
244 updateSpy.mockRestore()
245 }
246 })
247})
248
249describe('injectChat — resume', () => {
250 it('surfaces a run that pauses on an interrupt through the public signals', async () => {
251 // `onResumeStateChange` is NOT an `injectChat` option (it is omitted here
252 // exactly as in React / Solid / Vue / Svelte / Preact). The same
253 // information reaches the caller as reactive state: the pending interrupts
254 // through `interrupts` (and the
255 // `onInterruptStateChange` callback), and the run identity through the
256 // `runId` signal while a run is in flight.
257 const onInterruptStateChange = vi.fn()
258 const adapter = createMockConnectionAdapter({
259 chunks: [
260 {
261 type: EventType.RUN_STARTED,
262 runId: 'run-1',
263 threadId: 'thread-1',
264 timestamp: Date.now(),
265 },
266 {
267 type: EventType.TEXT_MESSAGE_CONTENT,
268 messageId: 'msg-1',
269 timestamp: Date.now(),
270 delta: 'Hi',
271 },
272 {
273 type: EventType.RUN_FINISHED,
274 runId: 'run-1',
275 threadId: 'thread-1',
276 timestamp: Date.now(),
277 outcome: {
278 type: 'interrupt',
279 interrupts: [{ id: 'interrupt-1', reason: 'client_tool_input' }],
280 },
281 },
282 ],
283 })
284 const { result, flush } = renderInjectChat({
285 connection: adapter,
286 threadId: 'thread-1',
287 onInterruptStateChange,
288 })
289
290 await result.sendMessage('Hi')
291 flush()
292
293 expect(result.interrupts()).toEqual(
294 expect.arrayContaining([expect.objectContaining({ id: 'interrupt-1' })]),
295 )
296 expect(onInterruptStateChange).toHaveBeenCalledWith(
297 expect.objectContaining({
298 interrupts: expect.arrayContaining([
299 expect.objectContaining({ id: 'interrupt-1' }),
300 ]),
301 }),
302 { source: 'live' },
303 )
304 })
305})
306
307describe('injectChat — structured output', () => {
308 // Mount injectChat directly so the `outputSchema` generic flows through and
309 // the schema-gated `partial` / `final` signals are present on the result.
310 // The shared renderInjectChat harness erases the schema type.
311 function mountStructuredHost(schema: z.ZodTypeAny) {
312 const adapter = createMockConnectionAdapter()
313
314 @Component({ standalone: true, template: '' })
315 class StructuredHost {
316 chat = injectChat({
317 threadId: 'thread-1',
318 connection: adapter,
319 outputSchema: schema,
320 })
321 }
322 const fixture = TestBed.createComponent(StructuredHost)
323 fixture.detectChanges()
324 return {
325 result: fixture.componentInstance.chat,
326 flush: () => fixture.detectChanges(),
327 }
328 }
329
330 it('partial → final transition via setMessages', () => {
331 const schema = z.object({ title: z.string() })
332 const { result, flush } = mountStructuredHost(schema)
333
334 // Feed a partial structured-output part (status: 'streaming').
335 result.setMessages([
336 {
337 id: 'u1',
338 role: 'user',
339 parts: [{ type: 'text', content: 'go' }],
340 createdAt: new Date(),
341 },
342 {
343 id: 'a1',
344 role: 'assistant',
345 parts: [
346 {
347 type: 'structured-output',
348 status: 'streaming',
349 partial: { title: 'Hi' },
350 raw: '{"title":"Hi"',
351 },
352 ],
353 createdAt: new Date(),
354 },
355 ])
356 flush()
357
358 expect(result.partial()).toEqual({ title: 'Hi' })
359 expect(result.final()).toBeNull()
360
361 // Transition to complete: status becomes 'complete' and data is populated.
362 result.setMessages([
363 {
364 id: 'u1',
365 role: 'user',
366 parts: [{ type: 'text', content: 'go' }],
367 createdAt: new Date(),
368 },
369 {
370 id: 'a1',
371 role: 'assistant',
372 parts: [
373 {
374 type: 'structured-output',
375 status: 'complete',
376 partial: { title: 'Hi' },
377 data: { title: 'Hi' },
378 raw: '{"title":"Hi"}',
379 },
380 ],
381 createdAt: new Date(),
382 },
383 ])
384 flush()
385
386 expect(result.final()).toEqual({ title: 'Hi' })
387 // partial() falls back to data when status is complete
388 expect(result.partial()).toMatchObject({ title: 'Hi' })
389 })
390
391 it('guard case: no preceding user message → final() is null', () => {
392 const schema = z.object({ title: z.string() })
393 const { result, flush } = mountStructuredHost(schema)
394
395 // Only an assistant message — no preceding user message.
396 result.setMessages([
397 {
398 id: 'a1',
399 role: 'assistant',
400 parts: [
401 {
402 type: 'structured-output',
403 status: 'complete',
404 data: { title: 'Hi' },
405 raw: '{"title":"Hi"}',
406 },
407 ],
408 createdAt: new Date(),
409 },
410 ])
411 flush()
412
413 // activeStructuredPart returns null when lastUserIndex === -1, so final() must be null.
414 expect(result.final()).toBeNull()
415 })
416})
417
418describe('injectChat snapshot', () => {
419 it('reads one frozen client snapshot and drops it on destroy', async () => {
420 let resolveRead!: (value: {
421 messages: Array<{
422 id: string
423 role: 'user'
424 parts: Array<{ type: 'text'; content: string }>
425 }>
426 }) => void
427 const read = new Promise<Parameters<typeof resolveRead>[0]>((resolve) => {
428 resolveRead = resolve
429 })
430 const { result, flush, destroy } = renderInjectChat({
431 connection: createMockConnectionAdapter({
432 chunks: createTextChunks('Hi'),
433 }),
434 threadId: 'angular-snapshot',
435 persistence: {
436 getItem: () => read,
437 setItem: async () => {},
438 removeItem: async () => {},
439 },
440 })
441 flush()
442
443 expect(result.isHydrating()).toBe(true)
444 resolveRead({
445 messages: [
446 { id: 'm1', role: 'user', parts: [{ type: 'text', content: 'hi' }] },
447 ],
448 })
449 await vi.waitFor(() => expect(result.isHydrating()).toBe(false))
450 expect(result.messages()).toHaveLength(1)
451
452 await result.sendMessage('Hello')
453 expect(result.isLoading()).toBe(false)
454 expect(result.status()).toBe('ready')
455 const messages = result.messages()
456 expect(messages).toHaveLength(3)
457 expect(Object.isFrozen(messages)).toBe(true)
458 expect(() => (messages as Array<unknown>).push({})).toThrow(TypeError)
459
460 destroy()
461 result.setMessages([])
462 expect(result.messages()).toBe(messages)
463 })
464})