Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 createChatOptions,
6} from '@tanstack/ai'
7import { StreamProcessor, uiMessagesToWire } from '@tanstack/ai/client'
8import { createAnthropicChat } from '@tanstack/ai-anthropic'
9import { memoryPersistence, withPersistence } from '@tanstack/ai-persistence'
10
11const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
12
13type SseEvent = Record<string, unknown> & { type: string }
14
15function messageStart(id: string): SseEvent {
16 return {
17 type: 'message_start',
18 message: {
19 id,
20 type: 'message',
21 role: 'assistant',
22 content: [],
23 model: 'claude-sonnet-4-5',
24 stop_reason: null,
25 stop_sequence: null,
26 usage: { input_tokens: 5, output_tokens: 0 },
27 },
28 }
29}
30
31function text(index: number, value: string) {
32 return [
33 {
34 type: 'content_block_start',
35 index,
36 content_block: { type: 'text', text: '' },
37 },
38 {
39 type: 'content_block_delta',
40 index,
41 delta: { type: 'text_delta', text: value },
42 },
43 { type: 'content_block_stop', index },
44 ]
45}
46
47function toolUse(index: number, id: string, name: string) {
48 return [
49 {
50 type: 'content_block_start',
51 index,
52 content_block: { type: 'tool_use', id, name, input: {} },
53 },
54 {
55 type: 'content_block_delta',
56 index,
57 delta: { type: 'input_json_delta', partial_json: '{}' },
58 },
59 { type: 'content_block_stop', index },
60 ]
61}
62
63function end(stopReason: string) {
64 return [
65 {
66 type: 'message_delta',
67 delta: { stop_reason: stopReason, stop_sequence: null },
68 usage: { output_tokens: 20 },
69 },
70 { type: 'message_stop' },
71 ]
72}
73
74function sse(events: Array<SseEvent>): Response {
75 return new Response(
76 events
77 .map(
78 (event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
79 )
80 .join(''),
81 { status: 200, headers: { 'Content-Type': 'text/event-stream' } },
82 )
83}
84
85/** Answers each call with the next scripted stream and records its body. */
86function scriptedFetch(streams: Array<Array<SseEvent>>) {
87 const bodies: Array<{
88 messages: Array<{ role: string; content: unknown }>
89 }> = []
90 const fetchImpl: typeof fetch = async (input, init) => {
91 const req = input instanceof Request ? input : new Request(input, init)
92 bodies.push(JSON.parse(await req.text()))
93 return sse(streams[bodies.length - 1] ?? [])
94 }
95 return { bodies, fetchImpl }
96}
97
98/** Every `tool_result` id the request sends back to Claude. */
99function toolResultIds(body: { messages: Array<{ content: unknown }> }) {
100 return body.messages.flatMap((message) =>
101 Array.isArray(message.content)
102 ? message.content
103 .filter((block: { type: string }) => block.type === 'tool_result')
104 .map((block: { tool_use_id: string }) => block.tool_use_id)
105 : [],
106 )
107}
108
109/**
110 * Claude calls a server tool, then a client tool, and the run stops on the
111 * client-tool interrupt. The browser takes the interrupt `MESSAGES_SNAPSHOT`,
112 * which gives the stored server tool result a snapshot id, adds the client
113 * tool's output, and resumes the run. `withPersistence` merges what it posts
114 * with the stored transcript.
115 *
116 * Before the fix, the store had never seen the snapshot id, so the merge
117 * appended the server tool result a second time and the resumed call sent
118 * Claude a second `tool_result` for `toolu_lookup`, with no matching `tool_use`
119 * in the assistant turn before it.
120 *
121 * `StreamProcessor` → `uiMessagesToWire` → `chatParamsFromRequestBody` →
122 * `chat()`, as a browser client and `/api/chat` do, answered by a capturing
123 * `fetch` (no aimock fixture).
124 */
125export const Route = createFileRoute('/api/client-tool-resume-store')({
126 server: {
127 handlers: {
128 POST: async () => {
129 try {
130 const claude = scriptedFetch([
131 [
132 messageStart('msg_call_1'),
133 ...toolUse(0, 'toolu_lookup', 'lookup'),
134 ...end('tool_use'),
135 ],
136 [
137 messageStart('msg_call_2'),
138 ...toolUse(0, 'toolu_ask', 'ask'),
139 ...end('tool_use'),
140 ],
141 [
142 messageStart('msg_call_3'),
143 ...text(0, 'It is 42.'),
144 ...end('end_turn'),
145 ],
146 ])
147 const adapter = createAnthropicChat('claude-sonnet-4-5', DUMMY_KEY, {
148 fetch: claude.fetchImpl,
149 })
150 const persistence = memoryPersistence()
151 const tools = [
152 {
153 name: 'lookup',
154 description: 'Look up the answer.',
155 execute: () => ({ answer: 42 }),
156 },
157 { name: 'ask', description: 'Ask the user.' },
158 ]
159 const threadId = 'client-tool-resume-store'
160 const runId = 'client-tool-resume-store-1'
161 const client = new StreamProcessor({})
162 client.addUserMessage('What is the answer?')
163
164 const send = async (
165 resume?: Array<{
166 interruptId: string
167 status: 'resolved'
168 payload: unknown
169 }>,
170 ) => {
171 const params = await chatParamsFromRequestBody({
172 threadId,
173 runId,
174 // `JSON.parse(JSON.stringify(...))` stands in for the HTTP hop.
175 messages: JSON.parse(
176 JSON.stringify(uiMessagesToWire(client.getMessages())),
177 ),
178 tools: [],
179 context: [],
180 ...(resume && { resume }),
181 })
182 client.prepareAssistantMessage()
183 for await (const chunk of chat({
184 ...createChatOptions({ adapter }),
185 messages: params.messages,
186 ...(params.resume && { resume: params.resume }),
187 tools,
188 threadId,
189 runId,
190 middleware: [withPersistence(persistence)],
191 stream: true,
192 })) {
193 client.processChunk(chunk)
194 }
195 client.finalizeStream()
196 }
197
198 await send()
199 client.addToolResult('toolu_ask', { confirmed: true })
200 await send([
201 {
202 interruptId: 'client_tool_toolu_ask',
203 status: 'resolved',
204 payload: { confirmed: true },
205 },
206 ])
207
208 const stored =
209 (await persistence.stores.messages?.loadThread(threadId)) ?? []
210 return Response.json({
211 ok: true,
212 resumedToolResultIds: claude.bodies[2]
213 ? toolResultIds(claude.bodies[2])
214 : [],
215 storedToolResultIds: stored.flatMap((message) =>
216 message.role === 'tool' && message.toolCallId
217 ? [message.toolCallId]
218 : [],
219 ),
220 })
221 } catch (error) {
222 return Response.json({
223 ok: false,
224 error: error instanceof Error ? error.message : String(error),
225 })
226 }
227 },
228 },
229 },
230})