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 thinking(index: number, value: string, signature: string) {
32 return [
33 {
34 type: 'content_block_start',
35 index,
36 content_block: { type: 'thinking', thinking: '', signature: '' },
37 },
38 {
39 type: 'content_block_delta',
40 index,
41 delta: { type: 'thinking_delta', thinking: value },
42 },
43 {
44 type: 'content_block_delta',
45 index,
46 delta: { type: 'signature_delta', signature },
47 },
48 { type: 'content_block_stop', index },
49 ]
50}
51
52function text(index: number, value: string) {
53 return [
54 {
55 type: 'content_block_start',
56 index,
57 content_block: { type: 'text', text: '' },
58 },
59 {
60 type: 'content_block_delta',
61 index,
62 delta: { type: 'text_delta', text: value },
63 },
64 { type: 'content_block_stop', index },
65 ]
66}
67
68function lookupToolUse(index: number) {
69 return [
70 {
71 type: 'content_block_start',
72 index,
73 content_block: {
74 type: 'tool_use',
75 id: 'toolu_lookup',
76 name: 'lookup',
77 input: {},
78 },
79 },
80 {
81 type: 'content_block_delta',
82 index,
83 delta: { type: 'input_json_delta', partial_json: '{}' },
84 },
85 { type: 'content_block_stop', index },
86 ]
87}
88
89function end(stopReason: string) {
90 return [
91 {
92 type: 'message_delta',
93 delta: { stop_reason: stopReason, stop_sequence: null },
94 usage: { output_tokens: 20 },
95 },
96 { type: 'message_stop' },
97 ]
98}
99
100function sse(events: Array<SseEvent>): Response {
101 return new Response(
102 events
103 .map(
104 (event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
105 )
106 .join(''),
107 { status: 200, headers: { 'Content-Type': 'text/event-stream' } },
108 )
109}
110
111/** Answers each call with the next scripted stream and records its body. */
112function scriptedFetch(streams: Array<Array<SseEvent>>) {
113 const bodies: Array<{
114 messages: Array<{ role: string; content: unknown }>
115 }> = []
116 const fetchImpl: typeof fetch = async (input, init) => {
117 const req = input instanceof Request ? input : new Request(input, init)
118 bodies.push(JSON.parse(await req.text()))
119 return sse(streams[bodies.length - 1] ?? [])
120 }
121 return { bodies, fetchImpl }
122}
123
124/** Every `tool_use` id the request sends back to Claude. */
125function toolUseIds(body: { messages: Array<{ content: unknown }> }) {
126 return body.messages.flatMap((message) =>
127 Array.isArray(message.content)
128 ? message.content
129 .filter((block: { type: string }) => block.type === 'tool_use')
130 .map((block: { id: string }) => block.id)
131 : [],
132 )
133}
134
135/**
136 * Claude thinks, then calls a server tool with no text first. The engine runs
137 * the tool, and Claude thinks again and answers. The browser keeps that answer
138 * and sends it back on the next turn, and `withPersistence` merges it with the
139 * stored transcript.
140 *
141 * Before the fix, the client renamed the first call's message to the second
142 * call's id, so the merge stored the tool call twice and turn 2 sent Claude a
143 * second `tool_use` with no `tool_result` after it.
144 *
145 * Two turns through `StreamProcessor` → `uiMessagesToWire` →
146 * `chatParamsFromRequestBody` → `chat()`, as a browser client and `/api/chat`
147 * do, answered by a capturing `fetch` (no aimock fixture).
148 */
149export const Route = createFileRoute('/api/server-tool-store-wire')({
150 server: {
151 handlers: {
152 POST: async () => {
153 try {
154 const claude = scriptedFetch([
155 [
156 messageStart('msg_call_1'),
157 ...thinking(0, 'Look it up first.', 'sig-a'),
158 ...lookupToolUse(1),
159 ...end('tool_use'),
160 ],
161 [
162 messageStart('msg_call_2'),
163 ...thinking(0, 'Now answer.', 'sig-b'),
164 ...text(1, 'It is 42.'),
165 ...end('end_turn'),
166 ],
167 [
168 messageStart('msg_call_3'),
169 ...text(0, 'Still 42.'),
170 ...end('end_turn'),
171 ],
172 ])
173 const adapter = createAnthropicChat('claude-sonnet-4-5', DUMMY_KEY, {
174 fetch: claude.fetchImpl,
175 })
176 const persistence = memoryPersistence()
177 const lookup = {
178 name: 'lookup',
179 description: 'Look up the answer.',
180 execute: () => ({ answer: 42 }),
181 }
182 const client = new StreamProcessor({})
183 for (const [index, prompt] of [
184 'What is the answer?',
185 'Check again?',
186 ].entries()) {
187 client.addUserMessage(prompt)
188 const runId = `server-tool-store-${index + 1}`
189 const params = await chatParamsFromRequestBody({
190 threadId: 'server-tool-store',
191 runId,
192 // `JSON.parse(JSON.stringify(...))` stands in for the HTTP hop.
193 messages: JSON.parse(
194 JSON.stringify(uiMessagesToWire(client.getMessages())),
195 ),
196 tools: [],
197 context: [],
198 })
199 client.prepareAssistantMessage()
200 for await (const chunk of chat({
201 ...createChatOptions({ adapter }),
202 messages: params.messages,
203 tools: [lookup],
204 threadId: 'server-tool-store',
205 runId,
206 middleware: [withPersistence(persistence)],
207 stream: true,
208 })) {
209 client.processChunk(chunk)
210 }
211 client.finalizeStream()
212 }
213
214 const stored =
215 (await persistence.stores.messages?.loadThread(
216 'server-tool-store',
217 )) ?? []
218 return Response.json({
219 ok: true,
220 turn2ToolUseIds: claude.bodies[2]
221 ? toolUseIds(claude.bodies[2])
222 : [],
223 storedToolCallIds: stored.flatMap((message) =>
224 'toolCalls' in message && Array.isArray(message.toolCalls)
225 ? message.toolCalls.map((call) => call.id)
226 : [],
227 ),
228 })
229 } catch (error) {
230 return Response.json({
231 ok: false,
232 error: error instanceof Error ? error.message : String(error),
233 })
234 }
235 },
236 },
237 },
238})