Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 EventType,
4 chat,
5 chatParamsFromRequestBody,
6 memoryStream,
7 resumeServerSentEventsResponse,
8 toolDefinition,
9 toServerSentEventsResponse,
10} from '@tanstack/ai'
11import { z } from 'zod'
12import type {
13 AnyTextAdapter,
14 ModelMessage,
15 AdapterYieldChunk,
16} from '@tanstack/ai'
17
18/**
19 * Provider-free harness for issue #1058: a `joinRun` replay that ends on a
20 * client tool must drain the queued resume after replay, same as a live stream.
21 *
22 * The first POST emits a client-tool interrupt, then holds the producer until
23 * the client disconnects (the spec reload) plus a short settle. That keeps
24 * `activeRun` visible so the remount `joinRun`s the log while it is still
25 * open. The client tool finishes during that hold; without the drain, the
26 * continuation POST never happens and `JOIN_OK` never appears.
27 *
28 * Exempt from the aimock policy: a fixed AG-UI sequence, never an LLM provider.
29 */
30
31const JOIN_OK = 'JOIN_OK the lookup is 42'
32const LATER_OK = 'LATER_OK the follow-up ran'
33const DISCONNECT_FALLBACK_MS = 3000
34const SETTLE_AFTER_DISCONNECT_MS = 1500
35
36const lookupTool = toolDefinition({
37 name: 'lookup',
38 description: 'Look up',
39 inputSchema: z.object({ query: z.string() }),
40 outputSchema: z.object({ answer: z.number() }),
41}).client()
42
43const runningByThread = new Map<string, string>()
44// Issue #1429: the pending interrupt of the run that the held continuation
45// answers. The persistence store commits it only when the continuation ends.
46const parentInterruptByThread = new Map<
47 string,
48 { runId: string; pending: Array<unknown> }
49>()
50
51// User text for the #1429 scenario: the first run pauses on the client tool,
52// and the continuation run (not the first run) is held open.
53const CONTINUATION_SCENARIO = 'continue'
54
55async function* recordInterrupt(
56 stream: AsyncIterable<AdapterYieldChunk>,
57 threadId: string,
58): AsyncGenerator<AdapterYieldChunk> {
59 for await (const chunk of stream) {
60 if (
61 chunk.type === EventType.RUN_FINISHED &&
62 chunk.outcome?.type === 'interrupt'
63 ) {
64 parentInterruptByThread.set(threadId, {
65 runId: chunk.runId,
66 pending: chunk.outcome.interrupts,
67 })
68 }
69 yield chunk
70 }
71}
72
73function delay(ms: number): Promise<void> {
74 return new Promise((resolve) => setTimeout(resolve, ms))
75}
76
77function waitForDisconnect(signal: AbortSignal): Promise<void> {
78 if (signal.aborted) return Promise.resolve()
79 return new Promise((resolve) => {
80 const finish = () => {
81 clearTimeout(timer)
82 signal.removeEventListener('abort', finish)
83 resolve()
84 }
85 const timer = setTimeout(finish, DISCONNECT_FALLBACK_MS)
86 signal.addEventListener('abort', finish, { once: true })
87 })
88}
89
90async function* holdAfter(
91 stream: AsyncIterable<AdapterYieldChunk>,
92 signal: AbortSignal,
93 onRelease: () => void,
94): AsyncGenerator<AdapterYieldChunk> {
95 try {
96 for await (const chunk of stream) {
97 yield chunk
98 }
99 await waitForDisconnect(signal)
100 await delay(SETTLE_AFTER_DISCONNECT_MS)
101 } finally {
102 onRelease()
103 }
104}
105
106function lastUserText(messages: Array<ModelMessage>): string {
107 for (let i = messages.length - 1; i >= 0; i--) {
108 const message = messages[i]
109 if (!message || message.role !== 'user') continue
110 if (typeof message.content === 'string') return message.content
111 }
112 return ''
113}
114
115function paramsLastUserText(
116 messages: Awaited<ReturnType<typeof chatParamsFromRequestBody>>['messages'],
117): string {
118 for (let i = messages.length - 1; i >= 0; i--) {
119 const message = messages[i]
120 if (!message || message.role !== 'user') continue
121 if ('parts' in message && Array.isArray(message.parts)) {
122 let text = ''
123 for (const part of message.parts) {
124 if (part.type === 'text') text += part.content
125 }
126 return text
127 }
128 if ('content' in message && typeof message.content === 'string') {
129 return message.content
130 }
131 }
132 return ''
133}
134
135const adapter: AnyTextAdapter = {
136 kind: 'text',
137 name: 'join-run-client-tool',
138 model: 'join-run-client-tool',
139 '~types': {
140 providerOptions: {},
141 inputModalities: ['text'],
142 messageMetadataByModality: {},
143 toolCapabilities: [],
144 toolCallMetadata: undefined,
145 systemPromptMetadata: undefined,
146 },
147 async *chatStream(options): AsyncGenerator<AdapterYieldChunk> {
148 const model = 'join-run-client-tool'
149 const runId = options.runId ?? 'join-run-client-tool-run'
150 const threadId = options.threadId ?? 'join-run-client-tool-thread'
151 const messageId = `${runId}-message`
152 const hasToolResult = options.messages.some(
153 (message) => message.role === 'tool',
154 )
155 const userText = lastUserText(options.messages)
156 const reply =
157 userText === 'later' ? LATER_OK : hasToolResult ? JOIN_OK : null
158
159 yield {
160 type: EventType.RUN_STARTED,
161 runId,
162 threadId,
163 model,
164 timestamp: Date.now(),
165 }
166
167 if (reply !== null) {
168 yield {
169 type: EventType.TEXT_MESSAGE_START,
170 messageId,
171 role: 'assistant',
172 model,
173 timestamp: Date.now(),
174 }
175 yield {
176 type: EventType.TEXT_MESSAGE_CONTENT,
177 messageId,
178 delta: reply,
179 model,
180 timestamp: Date.now(),
181 }
182 yield {
183 type: EventType.TEXT_MESSAGE_END,
184 messageId,
185 model,
186 timestamp: Date.now(),
187 }
188 yield {
189 type: EventType.RUN_FINISHED,
190 runId,
191 threadId,
192 model,
193 finishReason: 'stop',
194 timestamp: Date.now(),
195 }
196 return
197 }
198
199 const toolCallId = 'join-run-lookup-1'
200 yield {
201 type: EventType.TOOL_CALL_START,
202 toolCallId,
203 toolCallName: 'lookup',
204 model,
205 timestamp: Date.now(),
206 }
207 yield {
208 type: EventType.TOOL_CALL_ARGS,
209 toolCallId,
210 delta: '{"query":"first"}',
211 model,
212 timestamp: Date.now(),
213 }
214 yield {
215 type: EventType.TOOL_CALL_END,
216 toolCallId,
217 toolCallName: 'lookup',
218 input: { query: 'first' },
219 model,
220 timestamp: Date.now(),
221 }
222 yield {
223 type: EventType.RUN_FINISHED,
224 runId,
225 threadId,
226 model,
227 finishReason: 'tool_calls',
228 timestamp: Date.now(),
229 }
230 },
231 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
232}
233
234export const Route = createFileRoute('/api/join-run-client-tool')({
235 server: {
236 handlers: {
237 POST: async ({ request }) => {
238 let params
239 try {
240 params = await chatParamsFromRequestBody(await request.json())
241 } catch (error) {
242 return new Response(
243 error instanceof Error ? error.message : 'Bad request',
244 { status: 400 },
245 )
246 }
247
248 const isResume = (params.resume?.length ?? 0) > 0
249 const userText = paramsLastUserText(params.messages)
250 const isContinuationScenario = userText === CONTINUATION_SCENARIO
251 const shouldHold = isContinuationScenario
252 ? isResume
253 : !isResume && userText !== 'later'
254
255 if (shouldHold) {
256 runningByThread.set(params.threadId, params.runId)
257 } else {
258 runningByThread.delete(params.threadId)
259 }
260
261 const stream = chat({
262 adapter,
263 messages: params.messages,
264 tools: [lookupTool],
265 stream: true,
266 threadId: params.threadId,
267 runId: params.runId,
268 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
269 ...(params.resume ? { resume: params.resume } : {}),
270 })
271
272 const body = shouldHold
273 ? holdAfter(stream, request.signal, () => {
274 runningByThread.delete(params.threadId)
275 parentInterruptByThread.delete(params.threadId)
276 })
277 : isContinuationScenario
278 ? recordInterrupt(stream, params.threadId)
279 : stream
280
281 return toServerSentEventsResponse(body, {
282 durability: { adapter: memoryStream(request) },
283 })
284 },
285
286 GET: ({ request }) => {
287 const durability = memoryStream(request)
288 if (durability.resumeFrom() !== null) {
289 return resumeServerSentEventsResponse({ adapter: durability })
290 }
291
292 const threadId = new URL(request.url).searchParams.get('threadId') ?? ''
293 const runningRunId = threadId
294 ? runningByThread.get(threadId)
295 : undefined
296 const body = runningRunId
297 ? {
298 messages: [],
299 activeRun: { runId: runningRunId },
300 interrupts: parentInterruptByThread.get(threadId) ?? null,
301 }
302 : { messages: [], activeRun: null, interrupts: null }
303 return new Response(JSON.stringify(body), {
304 headers: {
305 'content-type': 'application/json',
306 'cache-control': 'no-store',
307 },
308 })
309 },
310 },
311 },
312})