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 with the deprecated pending alias', () => {
24 const onInterruptStateChange = vi.fn()
25 const { result, flush } = renderInjectChat({
26 connection: createMockConnectionAdapter(),
27 initialResumeSnapshot: createInterruptResumeSnapshot(),
28 onInterruptStateChange,
29 })
30
31 expect(Object.isFrozen(result.interrupts())).toBe(true)
32 expect(result.pendingInterrupts()).toBe(result.interrupts())
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 connection: createMockConnectionAdapter(),
81 })
82 const resolver = () => undefined
83 const resume = [{ interruptId: 'one', status: 'cancelled' as const }]
84
85 result.resolveInterrupts(resolver)
86 result.cancelInterrupts()
87 result.retryInterrupts()
88 await expect(result.resumeInterruptsUnsafe(resume)).resolves.toBe(true)
89
90 expect(resolve).toHaveBeenCalledWith(resolver)
91 expect(cancel).toHaveBeenCalledOnce()
92 expect(retry).toHaveBeenCalledOnce()
93 expect(unsafe).toHaveBeenCalledWith(resume, undefined)
94 })
95 })
96
97 it('initializes with default state', () => {
98 const adapter = createMockConnectionAdapter()
99 const { result } = renderInjectChat({ connection: adapter })
100
101 expect(result.messages()).toEqual([])
102 expect(result.isLoading()).toBe(false)
103 expect(result.error()).toBeUndefined()
104 expect(result.status()).toBe('ready')
105 expect(result.isSubscribed()).toBe(false)
106 expect(result.connectionStatus()).toBe('disconnected')
107 expect(result.sessionGenerating()).toBe(false)
108 })
109})
110
111describe('injectChat — streaming', () => {
112 it('streams assistant text into messages', async () => {
113 const adapter = createMockConnectionAdapter({
114 chunks: createTextChunks('Hello there'),
115 })
116 const { result, flush } = renderInjectChat({ connection: adapter })
117
118 await result.sendMessage('Hi')
119 await tick()
120 flush()
121
122 const assistant = result.messages().find((m) => m.role === 'assistant')
123 expect(assistant).toBeDefined()
124 expect(result.isLoading()).toBe(false)
125 })
126
127 it('merges sendMessage options.body into the request', async () => {
128 let capturedData: Record<string, unknown> | undefined
129 const adapter = createMockConnectionAdapter({
130 chunks: createTextChunks('Hello there'),
131 onConnect: (_messages, data) => {
132 capturedData = data
133 },
134 })
135 const { result, flush } = renderInjectChat({
136 connection: adapter,
137 body: { provider: 'openai' },
138 })
139
140 await result.sendMessage('Hi', {
141 whenBusy: 'queue',
142 body: { provider: 'anthropic', attachmentIds: ['a1', 'a2'] },
143 })
144 await tick()
145 flush()
146
147 expect(capturedData?.['provider']).toBe('anthropic')
148 expect(capturedData?.['attachmentIds']).toEqual(['a1', 'a2'])
149 expect(capturedData?.['whenBusy']).toBeUndefined()
150 })
151
152 it('initializes with provided messages', () => {
153 const adapter = createMockConnectionAdapter()
154 const initialMessages = [
155 {
156 id: 'msg-1',
157 role: 'user' as const,
158 parts: [{ type: 'text' as const, content: 'Hello' }],
159 createdAt: new Date(),
160 },
161 ]
162 const { result } = renderInjectChat({
163 connection: adapter,
164 initialMessages,
165 })
166 expect(result.messages()).toEqual(initialMessages)
167 })
168
169 it('clear() empties messages', async () => {
170 const adapter = createMockConnectionAdapter({
171 chunks: createTextChunks('Hi'),
172 })
173 const { result, flush } = renderInjectChat({ connection: adapter })
174 await result.sendMessage('Hi')
175 await tick()
176 result.clear()
177 flush()
178 expect(result.messages()).toEqual([])
179 })
180})
181
182describe('injectChat — reactive options', () => {
183 it('subscribes/unsubscribes when a live signal flips', async () => {
184 const adapter = createMockConnectionAdapter()
185 const live = signal(false)
186 const { result, flush } = renderInjectChat({ connection: adapter, live })
187
188 await tick()
189 flush()
190 expect(result.isSubscribed()).toBe(false)
191
192 live.set(true)
193 flush()
194 await tick()
195 expect(result.isSubscribed()).toBe(true)
196
197 live.set(false)
198 flush()
199 await tick()
200 expect(result.isSubscribed()).toBe(false)
201 })
202
203 it('pushes body-signal changes to the client', async () => {
204 const updateSpy = vi.spyOn(ChatClient.prototype, 'updateOptions')
205 try {
206 const adapter = createMockConnectionAdapter()
207 const body = signal<Record<string, any>>({ model: 'a' })
208 const { flush } = renderInjectChat({ connection: adapter, body })
209
210 // initial effect run picks up { model: 'a' }
211 flush()
212 await tick()
213 updateSpy.mockClear()
214
215 body.set({ model: 'b' })
216 flush()
217 await tick()
218
219 expect(updateSpy).toHaveBeenCalled()
220 expect(updateSpy).toHaveBeenCalledWith(
221 expect.objectContaining({ body: { model: 'b' } }),
222 )
223 } finally {
224 updateSpy.mockRestore()
225 }
226 })
227})
228
229describe('injectChat — resume', () => {
230 it('surfaces a run that pauses on an interrupt through the public signals', async () => {
231 // `onResumeStateChange` is NOT an `injectChat` option (it is omitted here
232 // exactly as in React / Solid / Vue / Svelte / Preact). The same
233 // information reaches the caller as reactive state: the pending interrupts
234 // through `interrupts` / `pendingInterrupts` (and the
235 // `onInterruptStateChange` callback), and the run identity through the
236 // `runId` signal while a run is in flight.
237 const onInterruptStateChange = vi.fn()
238 const adapter = createMockConnectionAdapter({
239 chunks: [
240 {
241 type: EventType.RUN_STARTED,
242 runId: 'run-1',
243 threadId: 'thread-1',
244 timestamp: Date.now(),
245 },
246 {
247 type: EventType.TEXT_MESSAGE_CONTENT,
248 messageId: 'msg-1',
249 timestamp: Date.now(),
250 delta: 'Hi',
251 },
252 {
253 type: EventType.RUN_FINISHED,
254 runId: 'run-1',
255 threadId: 'thread-1',
256 timestamp: Date.now(),
257 outcome: {
258 type: 'interrupt',
259 interrupts: [{ id: 'interrupt-1', reason: 'client_tool_input' }],
260 },
261 },
262 ],
263 })
264 const { result, flush } = renderInjectChat({
265 connection: adapter,
266 threadId: 'thread-1',
267 onInterruptStateChange,
268 })
269
270 await result.sendMessage('Hi')
271 flush()
272
273 expect(result.interrupts()).toEqual(
274 expect.arrayContaining([expect.objectContaining({ id: 'interrupt-1' })]),
275 )
276 expect(result.pendingInterrupts()).toBe(result.interrupts())
277 expect(onInterruptStateChange).toHaveBeenCalledWith(
278 expect.objectContaining({
279 interrupts: expect.arrayContaining([
280 expect.objectContaining({ id: 'interrupt-1' }),
281 ]),
282 }),
283 { source: 'live' },
284 )
285 })
286})
287
288describe('injectChat — structured output', () => {
289 // Mount injectChat directly so the `outputSchema` generic flows through and
290 // the schema-gated `partial` / `final` signals are present on the result.
291 // The shared renderInjectChat harness erases the schema type.
292 function mountStructuredHost(schema: z.ZodTypeAny) {
293 const adapter = createMockConnectionAdapter()
294
295 @Component({ standalone: true, template: '' })
296 class StructuredHost {
297 chat = injectChat({ connection: adapter, outputSchema: schema })
298 }
299 const fixture = TestBed.createComponent(StructuredHost)
300 fixture.detectChanges()
301 return {
302 result: fixture.componentInstance.chat,
303 flush: () => fixture.detectChanges(),
304 }
305 }
306
307 it('partial → final transition via setMessages', () => {
308 const schema = z.object({ title: z.string() })
309 const { result, flush } = mountStructuredHost(schema)
310
311 // Feed a partial structured-output part (status: 'streaming').
312 result.setMessages([
313 {
314 id: 'u1',
315 role: 'user',
316 parts: [{ type: 'text', content: 'go' }],
317 createdAt: new Date(),
318 },
319 {
320 id: 'a1',
321 role: 'assistant',
322 parts: [
323 {
324 type: 'structured-output',
325 status: 'streaming',
326 partial: { title: 'Hi' },
327 raw: '{"title":"Hi"',
328 },
329 ],
330 createdAt: new Date(),
331 },
332 ])
333 flush()
334
335 expect(result.partial()).toEqual({ title: 'Hi' })
336 expect(result.final()).toBeNull()
337
338 // Transition to complete: status becomes 'complete' and data is populated.
339 result.setMessages([
340 {
341 id: 'u1',
342 role: 'user',
343 parts: [{ type: 'text', content: 'go' }],
344 createdAt: new Date(),
345 },
346 {
347 id: 'a1',
348 role: 'assistant',
349 parts: [
350 {
351 type: 'structured-output',
352 status: 'complete',
353 partial: { title: 'Hi' },
354 data: { title: 'Hi' },
355 raw: '{"title":"Hi"}',
356 },
357 ],
358 createdAt: new Date(),
359 },
360 ])
361 flush()
362
363 expect(result.final()).toEqual({ title: 'Hi' })
364 // partial() falls back to data when status is complete
365 expect(result.partial()).toMatchObject({ title: 'Hi' })
366 })
367
368 it('guard case: no preceding user message → final() is null', () => {
369 const schema = z.object({ title: z.string() })
370 const { result, flush } = mountStructuredHost(schema)
371
372 // Only an assistant message — no preceding user message.
373 result.setMessages([
374 {
375 id: 'a1',
376 role: 'assistant',
377 parts: [
378 {
379 type: 'structured-output',
380 status: 'complete',
381 data: { title: 'Hi' },
382 raw: '{"title":"Hi"}',
383 },
384 ],
385 createdAt: new Date(),
386 },
387 ])
388 flush()
389
390 // activeStructuredPart returns null when lastUserIndex === -1, so final() must be null.
391 expect(result.final()).toBeNull()
392 })
393})