Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 memoryStream,
4 resumeHttpResponse,
5 resumeServerSentEventsResponse,
6 toHttpResponse,
7 toServerSentEventsResponse,
8} from '@tanstack/ai'
9import type { StreamChunk } from '@tanstack/ai'
10
11/**
12 * A provider-free delivery-durability harness route. It streams a FIXED
13 * sequence of AG-UI events through the transport helper's `durability` sink
14 * (`memoryStream`), so the delivery e2e can assert disconnect→reconnect→ordered
15 * resume and second-tab join deterministically, with no LLM in the loop.
16 *
17 * - `POST` with no offset → fresh run: produce + append the fixed sequence,
18 * tagging each event with an opaque adapter-owned offset.
19 * - `POST` with `Last-Event-ID` → reconnect: replay strictly after the offset
20 * from the log (the fixed sequence is never re-produced).
21 * - `GET ?offset=-1&runId=…` → second-tab join: replay from the start.
22 *
23 * `?transport=ndjson` switches the wire encoding from SSE to newline-delimited
24 * JSON (each durable line is an `{ id, chunk }` envelope). The durability layer
25 * — logging, offsets, resume, terminalization — is identical for both.
26 *
27 * `?scenario=slow` spaces the content chunks 300ms apart and keeps the default
28 * batch size, so a test can check that text reaches the client while the run
29 * is still going.
30 */
31// Emits bare TEXT_MESSAGE_CONTENT chunks without TEXT_MESSAGE_START/END
32// bracketing: this harness deliberately exercises raw chunk delivery + resume,
33// not UIMessage reassembly. The durability layer terminalizes on RUN_FINISHED
34// (emitted below), which is all resume/join needs.
35//
36// `delayMs` waits before each content chunk, like a model that is still
37// producing tokens. The `slow` scenario uses it to prove that the durability
38// batch does not hold live text until the run ends.
39export function fixedRun(
40 threadId: string,
41 runId: string,
42 delayMs = 0,
43): AsyncIterable<StreamChunk> {
44 return (async function* () {
45 yield {
46 type: 'RUN_STARTED',
47 threadId,
48 runId,
49 timestamp: Date.now(),
50 } as StreamChunk
51 for (let i = 1; i <= 5; i++) {
52 if (delayMs > 0) {
53 await new Promise((resolve) => setTimeout(resolve, delayMs))
54 }
55 yield {
56 type: 'TEXT_MESSAGE_CONTENT',
57 messageId: 'm',
58 model: 'fixed',
59 delta: String(i),
60 content: String(i),
61 timestamp: Date.now(),
62 } as StreamChunk
63 }
64 yield {
65 type: 'RUN_FINISHED',
66 threadId,
67 runId,
68 model: 'fixed',
69 finishReason: 'stop',
70 timestamp: Date.now(),
71 } as StreamChunk
72 })()
73}
74
75/**
76 * An agent-loop run: one RUN_STARTED/RUN_FINISHED pair PER iteration. The first
77 * terminal carries `finishReason: 'tool_calls'` (the model paused to call a
78 * tool); the tool result and a second iteration (the real answer) follow, ending
79 * on a `'stop'` terminal. This is the shape a tool-calling run takes on the
80 * wire, and the case that regressed: a durability sink that ended the log on the
81 * FIRST terminal truncated the run at the tool call.
82 */
83function agentLoopRun(
84 threadId: string,
85 runId: string,
86): AsyncIterable<StreamChunk> {
87 return (async function* () {
88 const now = () => Date.now()
89 yield {
90 type: 'RUN_STARTED',
91 threadId,
92 runId,
93 timestamp: now(),
94 } as StreamChunk
95 yield {
96 type: 'TOOL_CALL_START',
97 toolCallId: 'call-1',
98 toolCallName: 'rollDice',
99 toolName: 'rollDice',
100 timestamp: now(),
101 } as StreamChunk
102 yield {
103 type: 'TOOL_CALL_ARGS',
104 toolCallId: 'call-1',
105 delta: '{"sides":20}',
106 timestamp: now(),
107 } as StreamChunk
108 yield {
109 type: 'TOOL_CALL_END',
110 toolCallId: 'call-1',
111 timestamp: now(),
112 } as StreamChunk
113 // First per-iteration terminal. A sink that stops here drops everything below.
114 yield {
115 type: 'RUN_FINISHED',
116 threadId,
117 runId,
118 model: 'fixed',
119 finishReason: 'tool_calls',
120 timestamp: now(),
121 } as StreamChunk
122 // The tool result and the second iteration must survive the first terminal.
123 yield {
124 type: 'TOOL_CALL_RESULT',
125 toolCallId: 'call-1',
126 content: '{"rolls":[14],"total":14}',
127 timestamp: now(),
128 } as StreamChunk
129 yield {
130 type: 'RUN_STARTED',
131 threadId,
132 runId,
133 timestamp: now(),
134 } as StreamChunk
135 yield {
136 type: 'TEXT_MESSAGE_CONTENT',
137 messageId: 'm2',
138 model: 'fixed',
139 delta: 'done',
140 content: 'done',
141 timestamp: now(),
142 } as StreamChunk
143 yield {
144 type: 'RUN_FINISHED',
145 threadId,
146 runId,
147 model: 'fixed',
148 finishReason: 'stop',
149 timestamp: now(),
150 } as StreamChunk
151 })()
152}
153
154function scenarioOf(request: Request): string | null {
155 try {
156 return new URL(request.url).searchParams.get('scenario')
157 } catch {
158 return null
159 }
160}
161
162function durableRun(request: Request) {
163 const url = new URL(request.url)
164 const runId = url.searchParams.get('runId') ?? crypto.randomUUID()
165 url.searchParams.set('runId', runId)
166 // On a reconnect (Last-Event-ID present), memoryStream resolves the real run
167 // from the offset itself and ignores this URL runId — so a freshly minted
168 // random id here does NOT name the run being served and must not be
169 // advertised via X-Run-Id.
170 const isResume = request.headers.get('Last-Event-ID') !== null
171 return {
172 durability: memoryStream(new Request(url, request)),
173 runId,
174 advertiseRunId: isResume ? undefined : runId,
175 }
176}
177
178function withRunId(response: Response, runId: string | undefined): Response {
179 if (runId !== undefined) response.headers.set('X-Run-Id', runId)
180 return response
181}
182
183function isNdjson(request: Request): boolean {
184 try {
185 return new URL(request.url).searchParams.get('transport') === 'ndjson'
186 } catch {
187 return false
188 }
189}
190
191/** Build the durable response in the requested wire encoding (SSE or NDJSON). */
192function durableResponse(
193 request: Request,
194 runId: string,
195 durability: ReturnType<typeof memoryStream>,
196 batch?: number,
197): Response {
198 const scenario = scenarioOf(request)
199 const stream =
200 scenario === 'agent-loop'
201 ? agentLoopRun('thread-durable', runId)
202 : fixedRun('thread-durable', runId, scenario === 'slow' ? 300 : 0)
203 const durabilityOption = { adapter: durability, ...(batch ? { batch } : {}) }
204 return isNdjson(request)
205 ? toHttpResponse(stream, { durability: durabilityOption })
206 : toServerSentEventsResponse(stream, { durability: durabilityOption })
207}
208
209export const Route = createFileRoute('/api/durable-delivery')({
210 server: {
211 handlers: {
212 POST: async ({ request }) => {
213 const { durability, runId, advertiseRunId } = durableRun(request)
214 // `slow` keeps the default batch (32): its point is that live text
215 // still flows while the batch is far from full.
216 const batch = scenarioOf(request) === 'slow' ? undefined : 2
217 return withRunId(
218 durableResponse(request, runId, durability, batch),
219 advertiseRunId,
220 )
221 },
222 GET: async ({ request }) => {
223 // A join replays from the log, so no producer stream is built here.
224 const { durability, advertiseRunId } = durableRun(request)
225 const response = isNdjson(request)
226 ? resumeHttpResponse({ adapter: durability })
227 : resumeServerSentEventsResponse({ adapter: durability })
228 return withRunId(response, advertiseRunId)
229 },
230 },
231 },
232})