Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.tool-first-text-wire.ts

88 lines2.5 KB

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.
7 *
8 * A provider-free harness run where `TOOL_CALL_START` carries a
9 * `parentMessageId` that has not had a `TEXT_MESSAGE_START` yet — the normal
10 * AG-UI shape for "call a tool, then explain the result" as one assistant
11 * turn. The two `TEXT_MESSAGE_CONTENT` deltas below are the assertion: the
12 * bug only surfaces once a *second* delta arrives after the tool-first
13 * message's real `TEXT_MESSAGE_START`.
14 */
15function toolFirstRun(
16 threadId: string,
17 runId: string,
18): AsyncIterable<StreamChunk> {
19 const messageId = 'msg-1'
20 const toolCallId = 'call-1'
21 return (async function* () {
22 yield { type: 'RUN_STARTED', threadId, runId, timestamp: Date.now() }
23 yield {
24 type: 'TOOL_CALL_START',
25 toolCallId,
26 toolCallName: 'lookupWeather',
27 parentMessageId: messageId,
28 timestamp: Date.now(),
29 }
30 yield {
31 type: 'TOOL_CALL_ARGS',
32 toolCallId,
33 delta: '{}',
34 timestamp: Date.now(),
35 }
36 yield { type: 'TOOL_CALL_END', toolCallId, timestamp: Date.now() }
37 yield {
38 type: 'TOOL_CALL_RESULT',
39 messageId: 'tool-1',
40 toolCallId,
41 role: 'tool',
42 content: '{"ok":true}',
43 timestamp: Date.now(),
44 }
45 yield {
46 type: 'TEXT_MESSAGE_START',
47 messageId,
48 role: 'assistant',
49 timestamp: Date.now(),
50 }
51 yield {
52 type: 'TEXT_MESSAGE_CONTENT',
53 messageId,
54 delta: 'Hello, ',
55 timestamp: Date.now(),
56 }
57 yield {
58 type: 'TEXT_MESSAGE_CONTENT',
59 messageId,
60 delta: 'world.',
61 timestamp: Date.now(),
62 }
63 yield { type: 'TEXT_MESSAGE_END', messageId, timestamp: Date.now() }
64 yield {
65 type: 'RUN_FINISHED',
66 threadId,
67 runId,
68 timestamp: Date.now(),
69 outcome: { type: 'success' },
70 }
71 })() as AsyncIterable<StreamChunk>
73​
74export const Route = createFileRoute('/api/tool-first-text-wire')({
75 server: {
76 handlers: {
77 POST: async ({ request }) => {
78 const body: unknown = await request.json()
79 const threadId =
80 typeof body === 'object' && body !== null && 'threadId' in body
81 ? String((body as Record<string, unknown>).threadId)
82 : 'thread-1'
83 const runId = `run-${threadId}`
84 return toServerSentEventsResponse(toolFirstRun(threadId, runId))
85 },
86 },
87 },
88})