Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 EventType,
4 chat,
5 chatParamsFromRequestBody,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import {
9 memoryPersistence,
10 reconstructChat,
11 withPersistence,
12} from '@tanstack/ai-persistence'
13import type {
14 AnyTextAdapter,
15 AdapterYieldChunk,
16 ChatMiddleware,
17 StreamChunk,
18} from '@tanstack/ai'
19
20/**
21 * Provider-free harness for AG-UI activity (issue #1286).
22 *
23 * Live mode (`POST /api/activity-test`) runs `chat()` with a fixed adapter that
24 * yields ACTIVITY_SNAPSHOT then ACTIVITY_DELTA, then assistant text. The second
25 * turn inspects the inbound body: activity must not be sent as model input.
26 *
27 * Snapshot mode (`?mode=snapshot`) yields a MESSAGES_SNAPSHOT that already
28 * contains an ActivityMessage, so the client must hydrate `role: 'activity'`
29 * instead of rewriting it to an empty assistant.
30 *
31 * Persist mode (`?mode=persist`) drains `chat()` through `withPersistence`
32 * and GET `/api/activity-test?threadId=` returns `reconstructChat`.
33 * `?mode=persist-middleware` also adds an activity from middleware `onChunk`.
34 *
35 * Exempt from the aimock policy: a fixed AG-UI sequence, never an LLM provider.
36 */
37
38const ACTIVITY_ID = 'act-e2e-1'
39const MIDDLEWARE_ACTIVITY_ID = 'act-e2e-middleware'
40const ACTIVITY_NEEDLE = 'e2e-activity-needle'
41const ACTIVITY_FOUND = 'ACTIVITY_FOUND cats'
42const ACTIVITY_CLEAN = 'ACTIVITY_CLEAN'
43const ACTIVITY_LEAK = 'ACTIVITY_LEAK'
44
45const activityPersistence = memoryPersistence()
46
47const adapter: AnyTextAdapter = {
48 kind: 'text',
49 name: 'activity-test',
50 model: 'activity-test',
51 '~types': {
52 providerOptions: {},
53 inputModalities: ['text'],
54 messageMetadataByModality: {},
55 toolCapabilities: [],
56 toolCallMetadata: undefined,
57 systemPromptMetadata: undefined,
58 },
59 async *chatStream(options): AsyncGenerator<AdapterYieldChunk> {
60 const runId = options.runId ?? 'activity-test-run'
61 const threadId = options.threadId ?? 'activity-test-thread'
62 const userTurns = options.messages.filter(
63 (message) => message.role === 'user',
64 ).length
65 if (userTurns > 1) {
66 yield* textRun(threadId, runId, 'asst-clean', ACTIVITY_CLEAN)
67 return
68 }
69 yield {
70 type: EventType.RUN_STARTED,
71 threadId,
72 runId,
73 timestamp: Date.now(),
74 }
75 yield {
76 type: 'ACTIVITY_SNAPSHOT',
77 messageId: ACTIVITY_ID,
78 activityType: 'SEARCH',
79 content: { query: ACTIVITY_NEEDLE, status: 'running' },
80 timestamp: Date.now(),
81 }
82 yield {
83 type: 'ACTIVITY_DELTA',
84 messageId: ACTIVITY_ID,
85 activityType: 'SEARCH',
86 patch: [
87 { op: 'replace', path: '/status', value: 'done' },
88 { op: 'add', path: '/hits', value: 3 },
89 ],
90 timestamp: Date.now(),
91 }
92 yield* textRun(threadId, runId, 'asst-found', ACTIVITY_FOUND, false)
93 },
94 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
95}
96
97function inboundLeakedActivity(
98 messages: Awaited<ReturnType<typeof chatParamsFromRequestBody>>['messages'],
99): boolean {
100 return messages.some((message) => {
101 if (message.role === 'activity') return true
102 if ('id' in message && message.id === ACTIVITY_ID) return true
103 return JSON.stringify(message).includes(ACTIVITY_NEEDLE)
104 })
105}
106
107async function* textRun(
108 threadId: string,
109 runId: string,
110 messageId: string,
111 text: string,
112 includeStart = true,
113): AsyncGenerator<AdapterYieldChunk> {
114 if (includeStart) {
115 yield {
116 type: EventType.RUN_STARTED,
117 threadId,
118 runId,
119 timestamp: Date.now(),
120 }
121 }
122 yield {
123 type: EventType.TEXT_MESSAGE_START,
124 messageId,
125 role: 'assistant',
126 timestamp: Date.now(),
127 }
128 yield {
129 type: EventType.TEXT_MESSAGE_CONTENT,
130 messageId,
131 delta: text,
132 timestamp: Date.now(),
133 }
134 yield {
135 type: EventType.TEXT_MESSAGE_END,
136 messageId,
137 timestamp: Date.now(),
138 }
139 yield {
140 type: EventType.RUN_FINISHED,
141 threadId,
142 runId,
143 timestamp: Date.now(),
144 }
145}
146
147function snapshotRun(
148 threadId: string,
149 runId: string,
150): AsyncIterable<StreamChunk> {
151 return (async function* () {
152 yield {
153 type: EventType.RUN_STARTED,
154 threadId,
155 runId,
156 timestamp: Date.now(),
157 } satisfies StreamChunk
158 yield {
159 type: EventType.MESSAGES_SNAPSHOT,
160 timestamp: Date.now(),
161 messages: [
162 { id: 'u1', role: 'user', content: 'search' },
163 {
164 id: ACTIVITY_ID,
165 role: 'activity',
166 activityType: 'SEARCH',
167 content: { query: ACTIVITY_NEEDLE, status: 'done', hits: 3 },
168 },
169 { id: 'a1', role: 'assistant', content: ACTIVITY_FOUND },
170 ],
171 } satisfies StreamChunk
172 yield {
173 type: EventType.RUN_FINISHED,
174 threadId,
175 runId,
176 timestamp: Date.now(),
177 } satisfies StreamChunk
178 })()
179}
180
181function leakRun(threadId: string, runId: string): AsyncIterable<StreamChunk> {
182 return textRun(threadId, runId, 'asst-leak', ACTIVITY_LEAK)
183}
184
185function stringField(body: unknown, key: string): string | undefined {
186 if (typeof body !== 'object' || body === null || !(key in body)) {
187 return undefined
188 }
189 const value: unknown = (body as Record<string, unknown>)[key]
190 return typeof value === 'string' ? value : undefined
191}
192
193/** Adds its own activity card before the assistant text (issue #1803). */
194const middlewareActivity: ChatMiddleware = {
195 name: 'middleware-activity',
196 onChunk(_ctx, chunk) {
197 if (chunk.type !== EventType.TEXT_MESSAGE_START) return [chunk]
198 return [
199 {
200 type: EventType.ACTIVITY_SNAPSHOT,
201 messageId: MIDDLEWARE_ACTIVITY_ID,
202 activityType: 'NOTICE',
203 content: { text: 'from middleware' },
204 timestamp: Date.now(),
205 },
206 chunk,
207 ]
208 },
209}
210
211async function persistActivity(
212 threadId: string,
213 runId: string,
214 withMiddlewareActivity: boolean,
215) {
216 const stream = chat({
217 adapter,
218 messages: [{ role: 'user', content: 'search' }],
219 stream: true,
220 threadId,
221 runId,
222 middleware: [
223 withPersistence(activityPersistence),
224 ...(withMiddlewareActivity ? [middlewareActivity] : []),
225 ],
226 })
227 for await (const _ of stream) void _
228 return { threadId, runId }
229}
230
231export const Route = createFileRoute('/api/activity-test')({
232 server: {
233 handlers: {
234 POST: async ({ request }) => {
235 const mode = new URL(request.url).searchParams.get('mode')
236 if (mode === 'persist' || mode === 'persist-middleware') {
237 const body: unknown = await request.json()
238 const threadId = stringField(body, 'threadId') ?? crypto.randomUUID()
239 const runId = stringField(body, 'runId') ?? crypto.randomUUID()
240 return Response.json(
241 await persistActivity(
242 threadId,
243 runId,
244 mode === 'persist-middleware',
245 ),
246 )
247 }
248
249 let params
250 try {
251 params = await chatParamsFromRequestBody(await request.json())
252 } catch (error) {
253 return new Response(
254 error instanceof Error ? error.message : 'Bad request',
255 { status: 400 },
256 )
257 }
258
259 if (mode === 'snapshot') {
260 return toServerSentEventsResponse(
261 snapshotRun(params.threadId, params.runId),
262 )
263 }
264
265 if (inboundLeakedActivity(params.messages)) {
266 return toServerSentEventsResponse(
267 leakRun(params.threadId, params.runId),
268 )
269 }
270
271 const stream = chat({
272 adapter,
273 messages: params.messages,
274 stream: true,
275 threadId: params.threadId,
276 runId: params.runId,
277 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
278 })
279 return toServerSentEventsResponse(stream)
280 },
281 GET: ({ request }) =>
282 reconstructChat(activityPersistence, request, {
283 authorize: (threadId) => threadId.length > 0,
284 }),
285 },
286 },
287})