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

api.activity-test.ts

300 lines8.3 KB

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 * `?mode=persist-error` fails the run after the activity (issue #1804).
35 *
36 * Exempt from the aimock policy: a fixed AG-UI sequence, never an LLM provider.
37 */
38​
39const ACTIVITY_ID = 'act-e2e-1'
40const MIDDLEWARE_ACTIVITY_ID = 'act-e2e-middleware'
41const ACTIVITY_NEEDLE = 'e2e-activity-needle'
42const ACTIVITY_FOUND = 'ACTIVITY_FOUND cats'
43const ACTIVITY_CLEAN = 'ACTIVITY_CLEAN'
44const ACTIVITY_LEAK = 'ACTIVITY_LEAK'
45​
46const activityPersistence = memoryPersistence()
47​
48const adapter: AnyTextAdapter = {
49 kind: 'text',
50 name: 'activity-test',
51 model: 'activity-test',
52 '~types': {
53 providerOptions: {},
54 inputModalities: ['text'],
55 messageMetadataByModality: {},
56 toolCapabilities: [],
57 toolCallMetadata: undefined,
58 systemPromptMetadata: undefined,
59 },
60 async *chatStream(options): AsyncGenerator<AdapterYieldChunk> {
61 const runId = options.runId ?? 'activity-test-run'
62 const threadId = options.threadId ?? 'activity-test-thread'
63 const userTurns = options.messages.filter(
64 (message) => message.role === 'user',
65 ).length
66 if (userTurns > 1) {
67 yield* textRun(threadId, runId, 'asst-clean', ACTIVITY_CLEAN)
68 return
69 }
70 yield {
71 type: EventType.RUN_STARTED,
72 threadId,
73 runId,
74 timestamp: Date.now(),
75 }
76 yield {
77 type: 'ACTIVITY_SNAPSHOT',
78 messageId: ACTIVITY_ID,
79 activityType: 'SEARCH',
80 content: { query: ACTIVITY_NEEDLE, status: 'running' },
81 timestamp: Date.now(),
82 }
83 yield {
84 type: 'ACTIVITY_DELTA',
85 messageId: ACTIVITY_ID,
86 activityType: 'SEARCH',
87 patch: [
88 { op: 'replace', path: '/status', value: 'done' },
89 { op: 'add', path: '/hits', value: 3 },
90 ],
91 timestamp: Date.now(),
92 }
93 yield* textRun(threadId, runId, 'asst-found', ACTIVITY_FOUND, false)
94 },
95 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
97​
98function inboundLeakedActivity(
99 messages: Awaited<ReturnType<typeof chatParamsFromRequestBody>>['messages'],
100): boolean {
101 return messages.some((message) => {
102 if (message.role === 'activity') return true
103 if ('id' in message && message.id === ACTIVITY_ID) return true
104 return JSON.stringify(message).includes(ACTIVITY_NEEDLE)
105 })
107​
108async function* textRun(
109 threadId: string,
110 runId: string,
111 messageId: string,
112 text: string,
113 includeStart = true,
114): AsyncGenerator<AdapterYieldChunk> {
115 if (includeStart) {
116 yield {
117 type: EventType.RUN_STARTED,
118 threadId,
119 runId,
120 timestamp: Date.now(),
121 }
122 }
123 yield {
124 type: EventType.TEXT_MESSAGE_START,
125 messageId,
126 role: 'assistant',
127 timestamp: Date.now(),
128 }
129 yield {
130 type: EventType.TEXT_MESSAGE_CONTENT,
131 messageId,
132 delta: text,
133 timestamp: Date.now(),
134 }
135 yield {
136 type: EventType.TEXT_MESSAGE_END,
137 messageId,
138 timestamp: Date.now(),
139 }
140 yield {
141 type: EventType.RUN_FINISHED,
142 threadId,
143 runId,
144 timestamp: Date.now(),
145 }
147​
148function snapshotRun(
149 threadId: string,
150 runId: string,
151): AsyncIterable<StreamChunk> {
152 return (async function* () {
153 yield {
154 type: EventType.RUN_STARTED,
155 threadId,
156 runId,
157 timestamp: Date.now(),
158 } satisfies StreamChunk
159 yield {
160 type: EventType.MESSAGES_SNAPSHOT,
161 timestamp: Date.now(),
162 messages: [
163 { id: 'u1', role: 'user', content: 'search' },
164 {
165 id: ACTIVITY_ID,
166 role: 'activity',
167 activityType: 'SEARCH',
168 content: { query: ACTIVITY_NEEDLE, status: 'done', hits: 3 },
169 },
170 { id: 'a1', role: 'assistant', content: ACTIVITY_FOUND },
171 ],
172 } satisfies StreamChunk
173 yield {
174 type: EventType.RUN_FINISHED,
175 threadId,
176 runId,
177 timestamp: Date.now(),
178 } satisfies StreamChunk
179 })()
181​
182function leakRun(threadId: string, runId: string): AsyncIterable<StreamChunk> {
183 return textRun(threadId, runId, 'asst-leak', ACTIVITY_LEAK)
185​
186function stringField(body: unknown, key: string): string | undefined {
187 if (typeof body !== 'object' || body === null || !(key in body)) {
188 return undefined
189 }
190 const value: unknown = (body as Record<string, unknown>)[key]
191 return typeof value === 'string' ? value : undefined
193​
194/** Adds its own activity card before the assistant text (issue #1803). */
195const middlewareActivity: ChatMiddleware = {
196 name: 'middleware-activity',
197 onChunk(_ctx, chunk) {
198 if (chunk.type !== EventType.TEXT_MESSAGE_START) return [chunk]
199 return [
200 {
201 type: EventType.ACTIVITY_SNAPSHOT,
202 messageId: MIDDLEWARE_ACTIVITY_ID,
203 activityType: 'NOTICE',
204 content: { text: 'from middleware' },
205 timestamp: Date.now(),
206 },
207 chunk,
208 ]
209 },
211​
212/** Fails the run after the activity, before the assistant text (issue #1804). */
213const failAfterActivity: ChatMiddleware = {
214 name: 'fail-after-activity',
215 onChunk(_ctx, chunk) {
216 if (chunk.type === EventType.TEXT_MESSAGE_START) {
217 throw new Error('provider failed')
218 }
219 },
221​
222const persistMiddleware: Record<string, Array<ChatMiddleware> | undefined> = {
223 persist: [],
224 'persist-middleware': [middlewareActivity],
225 'persist-error': [failAfterActivity],
227​
228async function persistActivity(
229 threadId: string,
230 runId: string,
231 extra: Array<ChatMiddleware>,
232) {
233 const stream = chat({
234 adapter,
235 messages: [{ role: 'user', content: 'search' }],
236 stream: true,
237 threadId,
238 runId,
239 middleware: [withPersistence(activityPersistence), ...extra],
240 })
241 try {
242 for await (const _ of stream) void _
243 } catch {
244 // persist-error fails the run on purpose.
245 }
246 return { threadId, runId }
248​
249export const Route = createFileRoute('/api/activity-test')({
250 server: {
251 handlers: {
252 POST: async ({ request }) => {
253 const mode = new URL(request.url).searchParams.get('mode')
254 const extra = mode ? persistMiddleware[mode] : undefined
255 if (extra) {
256 const body: unknown = await request.json()
257 const threadId = stringField(body, 'threadId') ?? crypto.randomUUID()
258 const runId = stringField(body, 'runId') ?? crypto.randomUUID()
259 return Response.json(await persistActivity(threadId, runId, extra))
260 }
261​
262 let params
263 try {
264 params = await chatParamsFromRequestBody(await request.json())
265 } catch (error) {
266 return new Response(
267 error instanceof Error ? error.message : 'Bad request',
268 { status: 400 },
269 )
270 }
271​
272 if (mode === 'snapshot') {
273 return toServerSentEventsResponse(
274 snapshotRun(params.threadId, params.runId),
275 )
276 }
277​
278 if (inboundLeakedActivity(params.messages)) {
279 return toServerSentEventsResponse(
280 leakRun(params.threadId, params.runId),
281 )
282 }
283​
284 const stream = chat({
285 adapter,
286 messages: params.messages,
287 stream: true,
288 threadId: params.threadId,
289 runId: params.runId,
290 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
291 })
292 return toServerSentEventsResponse(stream)
293 },
294 GET: ({ request }) =>
295 reconstructChat(activityPersistence, request, {
296 authorize: (threadId) => threadId.length > 0,
297 }),
298 },
299 },
300})