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

chat-client-interrupt-correlation.test.ts

186 lines5.5 KB

1import { describe, expect, it, vi } from 'vitest'
2import { EventType } from '@tanstack/ai/client'
3import { ChatClient } from '../src/chat-client'
4import type { Interrupt, StreamChunk } from '@tanstack/ai/client'
5import type {
6 RunAgentInputContext,
7 SubscribeConnectionAdapter,
8} from '../src/connection-adapters'
9​
10function createNativeQueue() {
11 const chunks: Array<StreamChunk> = []
12 const contexts: Array<RunAgentInputContext | undefined> = []
13 let wake: (() => void) | undefined
14 const connection: SubscribeConnectionAdapter = {
15 async *subscribe(signal) {
16 while (!signal?.aborted) {
17 const chunk = chunks.shift()
18 if (chunk) {
19 yield chunk
20 continue
21 }
22 await new Promise<void>((resolve) => {
23 wake = resolve
24 signal?.addEventListener('abort', () => resolve(), { once: true })
25 })
26 }
27 },
28 send: (_messages, _data, _signal, context) => {
29 contexts.push(context)
30 return Promise.resolve()
31 },
32 }
33 return {
34 connection,
35 contexts,
36 publish(chunk: StreamChunk) {
37 chunks.push(chunk)
38 const resolve = wake
39 wake = undefined
40 resolve?.()
41 },
42 }
44​
45const interruptedRunId = 'interrupted-run'
46const pendingInterrupt: Interrupt = {
47 id: 'generic-1',
48 reason: 'confirmation',
49 metadata: {
50 'tanstack:interruptBinding': {
51 kind: 'generic',
52 interruptId: 'generic-1',
53 interruptedRunId,
54 generation: 1,
55 responseSchemaHash: 'none',
56 },
57 },
59​
60describe('ChatClient interrupt error correlation', () => {
61 it('does not apply a foreign shared RUN_ERROR to a local interrupt submission', async () => {
62 const { connection, contexts, publish } = createNativeQueue()
63 const onChunk = vi.fn()
64 const client = new ChatClient({
65 threadId: 'thread-1',
66 connection,
67 onChunk,
68 initialResumeSnapshot: {
69 resumeState: { threadId: 'thread-1', runId: interruptedRunId },
70 pendingInterrupts: [pendingInterrupt],
71 },
72 })
73 const interrupt = client.getInterrupts()[0]
74 if (interrupt?.kind !== 'generic') {
75 throw new Error('Expected a generic interrupt')
76 }
77​
78 interrupt.resolveInterrupt({ answer: 'continue' })
79 await vi.waitFor(() => expect(contexts).toHaveLength(1))
80 publish({
81 type: EventType.RUN_ERROR,
82 threadId: 'foreign-thread',
83 runId: 'foreign-child-run',
84 timestamp: Date.now(),
85 message: 'foreign run failed',
86 metadata: {
87 tanstack: {
88 interruptErrors: [
89 {
90 scope: 'item',
91 interruptId: 'generic-1',
92 code: 'invalid-payload',
93 message: 'foreign item error',
94 source: 'server',
95 retryable: false,
96 threadId: 'foreign-thread',
97 interruptedRunId: 'foreign-parent-run',
98 generation: 7,
99 },
100 {
101 scope: 'batch',
102 code: 'item-validation-failed',
103 message: 'foreign batch error',
104 source: 'server',
105 retryable: false,
106 interruptIds: ['generic-1'],
107 threadId: 'foreign-thread',
108 interruptedRunId: 'foreign-parent-run',
109 generation: 7,
110 },
111 ],
112 },
113 },
114 })
115​
116 await vi.waitFor(() =>
117 expect(client.getInterruptState().resuming).toBe(false),
118 )
119 expect(onChunk).toHaveBeenCalledWith(
120 expect.objectContaining({ runId: 'foreign-child-run' }),
121 )
122 expect(client.getError()?.message).toBe('foreign run failed')
123 expect(client.getInterrupts()[0]?.errors).toEqual([])
124 expect(client.getInterruptState().interruptErrors).toEqual([
125 expect.objectContaining({ code: 'transport', source: 'transport' }),
126 ])
127​
128 client.retryInterrupts()
129 await vi.waitFor(() => expect(contexts).toHaveLength(2))
130 const localRunId = contexts[1]?.runId
131 if (!localRunId) throw new Error('Expected a local continuation run ID')
132 publish({
133 type: EventType.RUN_ERROR,
134 threadId: 'thread-1',
135 runId: localRunId,
136 timestamp: Date.now(),
137 message: 'local validation failed',
138 metadata: {
139 tanstack: {
140 interruptErrors: [
141 {
142 scope: 'item',
143 interruptId: 'generic-1',
144 code: 'invalid-payload',
145 message: 'local item error',
146 source: 'server',
147 retryable: false,
148 threadId: 'thread-1',
149 interruptedRunId,
150 generation: 1,
151 },
152 {
153 scope: 'batch',
154 code: 'item-validation-failed',
155 message: 'local batch error',
156 source: 'server',
157 retryable: false,
158 interruptIds: ['generic-1'],
159 threadId: 'thread-1',
160 interruptedRunId,
161 generation: 1,
162 },
163 ],
164 },
165 },
166 })
167​
168 await vi.waitFor(() =>
169 expect(client.getInterrupts()[0]?.errors).toMatchObject([
170 { message: 'local item error', source: 'server' },
171 ]),
172 )
173 expect(client.getInterruptState().interruptErrors).toEqual(
174 expect.arrayContaining([
175 expect.objectContaining({ code: 'transport', source: 'transport' }),
176 expect.objectContaining({
177 code: 'item-validation-failed',
178 message: 'local batch error',
179 source: 'server',
180 }),
181 ]),
182 )
183 expect(JSON.stringify(client.getInterruptState())).not.toContain('foreign')
184 client.dispose()
185 })
186})