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