Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { toServerSentEventsResponse } from '@tanstack/ai'
3import type { StreamChunk } from '@tanstack/ai'
4
5/**
6 * Wire-format regression for issue #1247, in the other event order.
7 *
8 * Here the message's `TEXT_MESSAGE_START` arrives *before* the tool call, as
9 * providers that open the assistant message first emit it. The two
10 * `TEXT_MESSAGE_CONTENT` deltas after the tool result are the assertion: the
11 * first one is the one that used to be overwritten, and only once a second
12 * delta arrived to displace it.
13 */
14function textFirstRun(
15 threadId: string,
16 runId: string,
17): AsyncIterable<StreamChunk> {
18 const messageId = 'msg-1'
19 const toolCallId = 'call-1'
20 return (async function* () {
21 yield { type: 'RUN_STARTED', threadId, runId, timestamp: Date.now() }
22 yield {
23 type: 'TEXT_MESSAGE_START',
24 messageId,
25 role: 'assistant',
26 timestamp: Date.now(),
27 }
28 yield {
29 type: 'TOOL_CALL_START',
30 toolCallId,
31 toolCallName: 'lookupWeather',
32 parentMessageId: messageId,
33 timestamp: Date.now(),
34 }
35 yield {
36 type: 'TOOL_CALL_ARGS',
37 toolCallId,
38 delta: '{}',
39 timestamp: Date.now(),
40 }
41 yield { type: 'TOOL_CALL_END', toolCallId, timestamp: Date.now() }
42 yield {
43 type: 'TOOL_CALL_RESULT',
44 messageId: 'tool-1',
45 toolCallId,
46 role: 'tool',
47 content: '{"ok":true}',
48 timestamp: Date.now(),
49 }
50 yield {
51 type: 'TEXT_MESSAGE_CONTENT',
52 messageId,
53 delta: 'Hello, ',
54 timestamp: Date.now(),
55 }
56 yield {
57 type: 'TEXT_MESSAGE_CONTENT',
58 messageId,
59 delta: 'world.',
60 timestamp: Date.now(),
61 }
62 yield { type: 'TEXT_MESSAGE_END', messageId, timestamp: Date.now() }
63 yield {
64 type: 'RUN_FINISHED',
65 threadId,
66 runId,
67 timestamp: Date.now(),
68 outcome: { type: 'success' },
69 }
70 })() as AsyncIterable<StreamChunk>
71}
72
73export const Route = createFileRoute('/api/text-first-tool-wire')({
74 server: {
75 handlers: {
76 POST: async ({ request }) => {
77 const body: unknown = await request.json()
78 const threadId =
79 typeof body === 'object' && body !== null && 'threadId' in body
80 ? String((body as Record<string, unknown>).threadId)
81 : 'thread-1'
82 const runId = `run-${threadId}`
83 return toServerSentEventsResponse(textFirstRun(threadId, runId))
84 },
85 },
86 },
87})