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

api.durable-delivery.ts

215 lines6.6 KB

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// Emits bare TEXT_MESSAGE_CONTENT chunks without TEXT_MESSAGE_START/END
28// bracketing: this harness deliberately exercises raw chunk delivery + resume,
29// not UIMessage reassembly. The durability layer terminalizes on RUN_FINISHED
30// (emitted below), which is all resume/join needs.
31export function fixedRun(
32 threadId: string,
33 runId: string,
34): AsyncIterable<StreamChunk> {
35 return (async function* () {
36 yield {
37 type: 'RUN_STARTED',
38 threadId,
39 runId,
40 timestamp: Date.now(),
41 } as StreamChunk
42 for (let i = 1; i <= 5; i++) {
43 yield {
44 type: 'TEXT_MESSAGE_CONTENT',
45 messageId: 'm',
46 model: 'fixed',
47 delta: String(i),
48 content: String(i),
49 timestamp: Date.now(),
50 } as StreamChunk
51 }
52 yield {
53 type: 'RUN_FINISHED',
54 threadId,
55 runId,
56 model: 'fixed',
57 finishReason: 'stop',
58 timestamp: Date.now(),
59 } as StreamChunk
60 })()
62​
63/**
64 * An agent-loop run: one RUN_STARTED/RUN_FINISHED pair PER iteration. The first
65 * terminal carries `finishReason: 'tool_calls'` (the model paused to call a
66 * tool); the tool result and a second iteration (the real answer) follow, ending
67 * on a `'stop'` terminal. This is the shape a tool-calling run takes on the
68 * wire, and the case that regressed: a durability sink that ended the log on the
69 * FIRST terminal truncated the run at the tool call.
70 */
71function agentLoopRun(
72 threadId: string,
73 runId: string,
74): AsyncIterable<StreamChunk> {
75 return (async function* () {
76 const now = () => Date.now()
77 yield {
78 type: 'RUN_STARTED',
79 threadId,
80 runId,
81 timestamp: now(),
82 } as StreamChunk
83 yield {
84 type: 'TOOL_CALL_START',
85 toolCallId: 'call-1',
86 toolCallName: 'rollDice',
87 toolName: 'rollDice',
88 timestamp: now(),
89 } as StreamChunk
90 yield {
91 type: 'TOOL_CALL_ARGS',
92 toolCallId: 'call-1',
93 delta: '{"sides":20}',
94 timestamp: now(),
95 } as StreamChunk
96 yield {
97 type: 'TOOL_CALL_END',
98 toolCallId: 'call-1',
99 timestamp: now(),
100 } as StreamChunk
101 // First per-iteration terminal. A sink that stops here drops everything below.
102 yield {
103 type: 'RUN_FINISHED',
104 threadId,
105 runId,
106 model: 'fixed',
107 finishReason: 'tool_calls',
108 timestamp: now(),
109 } as StreamChunk
110 // The tool result and the second iteration must survive the first terminal.
111 yield {
112 type: 'TOOL_CALL_RESULT',
113 toolCallId: 'call-1',
114 content: '{"rolls":[14],"total":14}',
115 timestamp: now(),
116 } as StreamChunk
117 yield {
118 type: 'RUN_STARTED',
119 threadId,
120 runId,
121 timestamp: now(),
122 } as StreamChunk
123 yield {
124 type: 'TEXT_MESSAGE_CONTENT',
125 messageId: 'm2',
126 model: 'fixed',
127 delta: 'done',
128 content: 'done',
129 timestamp: now(),
130 } as StreamChunk
131 yield {
132 type: 'RUN_FINISHED',
133 threadId,
134 runId,
135 model: 'fixed',
136 finishReason: 'stop',
137 timestamp: now(),
138 } as StreamChunk
139 })()
141​
142function isAgentLoop(request: Request): boolean {
143 try {
144 return new URL(request.url).searchParams.get('scenario') === 'agent-loop'
145 } catch {
146 return false
147 }
149​
150function durableRun(request: Request) {
151 const url = new URL(request.url)
152 const runId = url.searchParams.get('runId') ?? crypto.randomUUID()
153 url.searchParams.set('runId', runId)
154 // On a reconnect (Last-Event-ID present), memoryStream resolves the real run
155 // from the offset itself and ignores this URL runId — so a freshly minted
156 // random id here does NOT name the run being served and must not be
157 // advertised via X-Run-Id.
158 const isResume = request.headers.get('Last-Event-ID') !== null
159 return {
160 durability: memoryStream(new Request(url, request)),
161 runId,
162 advertiseRunId: isResume ? undefined : runId,
163 }
165​
166function withRunId(response: Response, runId: string | undefined): Response {
167 if (runId !== undefined) response.headers.set('X-Run-Id', runId)
168 return response
170​
171function isNdjson(request: Request): boolean {
172 try {
173 return new URL(request.url).searchParams.get('transport') === 'ndjson'
174 } catch {
175 return false
176 }
178​
179/** Build the durable response in the requested wire encoding (SSE or NDJSON). */
180function durableResponse(
181 request: Request,
182 runId: string,
183 durability: ReturnType<typeof memoryStream>,
184 batch?: number,
185): Response {
186 const stream = isAgentLoop(request)
187 ? agentLoopRun('thread-durable', runId)
188 : fixedRun('thread-durable', runId)
189 const durabilityOption = { adapter: durability, ...(batch ? { batch } : {}) }
190 return isNdjson(request)
191 ? toHttpResponse(stream, { durability: durabilityOption })
192 : toServerSentEventsResponse(stream, { durability: durabilityOption })
194​
195export const Route = createFileRoute('/api/durable-delivery')({
196 server: {
197 handlers: {
198 POST: async ({ request }) => {
199 const { durability, runId, advertiseRunId } = durableRun(request)
200 return withRunId(
201 durableResponse(request, runId, durability, 2),
202 advertiseRunId,
203 )
204 },
205 GET: async ({ request }) => {
206 // A join replays from the log, so no producer stream is built here.
207 const { durability, advertiseRunId } = durableRun(request)
208 const response = isNdjson(request)
209 ? resumeHttpResponse({ adapter: durability })
210 : resumeServerSentEventsResponse({ adapter: durability })
211 return withRunId(response, advertiseRunId)
212 },
213 },
214 },
215})