Open History to see the last commit
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 }
43}
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 },
58}
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 connection,
66 onChunk,
67 initialResumeSnapshot: {
68 resumeState: { threadId: 'thread-1', runId: interruptedRunId },
69 pendingInterrupts: [pendingInterrupt],
70 },
71 })
72 const interrupt = client.getInterrupts()[0]
73 if (interrupt?.kind !== 'generic') {
74 throw new Error('Expected a generic interrupt')
75 }
76
77 interrupt.resolveInterrupt({ answer: 'continue' })
78 await vi.waitFor(() => expect(contexts).toHaveLength(1))
79 publish({
80 type: EventType.RUN_ERROR,
81 threadId: 'foreign-thread',
82 runId: 'foreign-child-run',
83 timestamp: Date.now(),
84 message: 'foreign run failed',
85 metadata: {
86 tanstack: {
87 interruptErrors: [
88 {
89 scope: 'item',
90 interruptId: 'generic-1',
91 code: 'invalid-payload',
92 message: 'foreign item error',
93 source: 'server',
94 retryable: false,
95 threadId: 'foreign-thread',
96 interruptedRunId: 'foreign-parent-run',
97 generation: 7,
98 },
99 {
100 scope: 'batch',
101 code: 'item-validation-failed',
102 message: 'foreign batch error',
103 source: 'server',
104 retryable: false,
105 interruptIds: ['generic-1'],
106 threadId: 'foreign-thread',
107 interruptedRunId: 'foreign-parent-run',
108 generation: 7,
109 },
110 ],
111 },
112 },
113 })
114
115 await vi.waitFor(() =>
116 expect(client.getInterruptState().resuming).toBe(false),
117 )
118 expect(onChunk).toHaveBeenCalledWith(
119 expect.objectContaining({ runId: 'foreign-child-run' }),
120 )
121 expect(client.getError()?.message).toBe('foreign run failed')
122 expect(client.getInterrupts()[0]?.errors).toEqual([])
123 expect(client.getInterruptState().interruptErrors).toEqual([
124 expect.objectContaining({ code: 'transport', source: 'transport' }),
125 ])
126
127 client.retryInterrupts()
128 await vi.waitFor(() => expect(contexts).toHaveLength(2))
129 const localRunId = contexts[1]?.runId
130 if (!localRunId) throw new Error('Expected a local continuation run ID')
131 publish({
132 type: EventType.RUN_ERROR,
133 threadId: 'thread-1',
134 runId: localRunId,
135 timestamp: Date.now(),
136 message: 'local validation failed',
137 metadata: {
138 tanstack: {
139 interruptErrors: [
140 {
141 scope: 'item',
142 interruptId: 'generic-1',
143 code: 'invalid-payload',
144 message: 'local item error',
145 source: 'server',
146 retryable: false,
147 threadId: 'thread-1',
148 interruptedRunId,
149 generation: 1,
150 },
151 {
152 scope: 'batch',
153 code: 'item-validation-failed',
154 message: 'local batch error',
155 source: 'server',
156 retryable: false,
157 interruptIds: ['generic-1'],
158 threadId: 'thread-1',
159 interruptedRunId,
160 generation: 1,
161 },
162 ],
163 },
164 },
165 })
166
167 await vi.waitFor(() =>
168 expect(client.getInterrupts()[0]?.errors).toMatchObject([
169 { message: 'local item error', source: 'server' },
170 ]),
171 )
172 expect(client.getInterruptState().interruptErrors).toEqual(
173 expect.arrayContaining([
174 expect.objectContaining({ code: 'transport', source: 'transport' }),
175 expect.objectContaining({
176 code: 'item-validation-failed',
177 message: 'local batch error',
178 source: 'server',
179 }),
180 ]),
181 )
182 expect(JSON.stringify(client.getInterruptState())).not.toContain('foreign')
183 client.dispose()
184 })
185})