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

client.test.ts

447 lines14.5 KB

1import { describe, expect, it, vi } from 'vitest'
2import { z } from 'zod'
3import { defineAgent, toolDefinition } from '@tanstack/ai'
4import { memoryPersistence } from '@tanstack/ai-persistence'
5import {
6 createHarnessHost,
7 defineHarness,
8 logMessageStore,
9 membersOnly,
10} from '../src'
11import { createHarnessHandler } from '../src/server'
12import { createHarnessClient } from '../src/client'
13import { gate, messageTexts, mockAdapter, text } from './helpers'
14import type { SessionEvent } from '../src'
15​
16// Coverage runs in CI are slow, so polled checks wait up to 5 s.
17const waitFor = <T>(
18 check: () => T | Promise<T>,
19 options?: { timeout?: number; interval?: number },
20) => vi.waitFor(check, { timeout: 5_000, ...options })
21​
22describe('createHarnessClient', () => {
23 it('sends inputs, reads events, and gets a snapshot through the handler', async () => {
24 const pricer = defineAgent({
25 name: 'pricer',
26 description: 'Prices a vendor',
27 inputSchema: z.object({ vendor: z.string() }),
28 run: async (ctx) => ({ cents: ctx.input.vendor.length }),
29 })
30 const { adapter } = mockAdapter([() => text('hello from the host')])
31 const studio = defineHarness({
32 name: 'test/client',
33 adapter,
34 agents: [pricer],
35 expose: { agents: ['pricer'] },
36 })
37 const host = createHarnessHost({
38 persistence: memoryPersistence(),
39 access: {
40 getUser: ({ request }) =>
41 request.headers.get('authorization') === 'Bearer t'
42 ? { id: 'u' }
43 : null,
44 rules: { isAllowed: () => true },
45 },
46 })
47 const handler = createHarnessHandler({ host, harness: studio })
48 const client = createHarnessClient<typeof studio>({
49 url: 'http://local/api/harness/',
50 threadId: 'thread-c',
51 headers: { authorization: 'Bearer t' },
52 fetch: (input, init) => handler(new Request(input, init)),
53 })
54​
55 const receipt = await client.send('hi')
56 expect(receipt.status).toBe('accepted')
57​
58 const controller = new AbortController()
59 const seen: Array<SessionEvent> = []
60 // From the start: the turn can send its events before this read.
61 for await (const entry of client.events({
62 from: '0',
63 signal: controller.signal,
64 })) {
65 seen.push(entry)
66 if (
67 entry.event.type === 'CUSTOM' &&
68 entry.event.name === 'harness.operation.finished'
69 ) {
70 controller.abort()
71 }
72 }
73 expect(JSON.stringify(seen)).toContain('hello from the host')
74​
75 const agent = await client.agents.pricer.start({ vendor: 'acme' })
76 expect(agent.status).toBe('accepted')
77 // @ts-expect-error the input is typed from the harness
78 void client.agents.pricer.start({ vendor: 1 })
79​
80 const snapshot = await client.snapshot()
81 expect(snapshot.threadId).toBe('thread-c')
82 await host.close()
83 })
84​
85 it('sends an inputId, so a retry gets the first receipt', async () => {
86 const { adapter, calls } = mockAdapter([() => text('once')])
87 const studio = defineHarness({ name: 'test/client-ids', adapter })
88 const host = createHarnessHost({ persistence: memoryPersistence() })
89 const handler = createHarnessHandler({
90 host,
91 harness: studio,
92 openAccess: { user: { id: 'u' } },
93 })
94 const client = createHarnessClient<typeof studio>({
95 url: 'http://local/api/harness',
96 threadId: 'thread-ids',
97 fetch: (input, init) => handler(new Request(input, init)),
98 })
99​
100 const first = await client.send('hi', { inputId: 'req-1' })
101 const retry = await client.send('hi', { inputId: 'req-1' })
102 const steer = await client.send('also', { mode: 'steer', inputId: 'req-2' })
103 const steerRetry = await client.send('also', {
104 mode: 'steer',
105 inputId: 'req-2',
106 })
107​
108 expect(first).toMatchObject({ inputId: 'req-1', status: 'accepted' })
109 expect(retry).toEqual(first)
110 expect(steerRetry).toEqual(steer)
111 expect(calls.length).toBeLessThanOrEqual(2)
112 await host.close()
113 })
114​
115 it('sends continue, and the model answers the stored transcript', async () => {
116 const { adapter, calls } = mockAdapter([() => text('went')])
117 const studio = defineHarness({ name: 'test/client-continue', adapter })
118 const persistence = memoryPersistence()
119 await logMessageStore({ store: persistence.stores.log }).saveThread(
120 'thread-go',
121 [{ id: 'u1', role: 'user', content: 'go' }],
122 )
123 const host = createHarnessHost({ persistence })
124 const handler = createHarnessHandler({
125 host,
126 harness: studio,
127 openAccess: { user: { id: 'u' } },
128 })
129 const client = createHarnessClient<typeof studio>({
130 url: 'http://local/api/harness',
131 threadId: 'thread-go',
132 fetch: (input, init) => handler(new Request(input, init)),
133 })
134​
135 const receipt = await client.continueWithoutMessage({ inputId: 'c-1' })
136​
137 expect(receipt).toMatchObject({ inputId: 'c-1', status: 'accepted' })
138 await waitFor(() => expect(calls).toHaveLength(1))
139 expect(messageTexts(calls[0])).toEqual(['go'])
140 await host.close()
141 })
142​
143 it('runs an exposed tool with typed args, and refuses an append it does not expose', async () => {
144 const stats = toolDefinition({
145 name: 'fetch_stats',
146 description: 'Stats of a queue',
147 inputSchema: z.object({ queue: z.string() }),
148 }).server(async ({ queue }) => ({ queue, open: 7 }))
149 const { adapter, calls } = mockAdapter([])
150 const studio = defineHarness({
151 name: 'test/client-tool',
152 adapter,
153 tools: [stats],
154 expose: { tools: ['fetch_stats'] },
155 })
156 const persistence = memoryPersistence()
157 const host = createHarnessHost({ persistence })
158 const handler = createHarnessHandler({
159 host,
160 harness: studio,
161 openAccess: { user: { id: 'u' } },
162 })
163 const client = createHarnessClient<typeof studio>({
164 url: 'http://local/api/harness',
165 threadId: 'thread-tool',
166 fetch: (input, init) => handler(new Request(input, init)),
167 })
168​
169 expect(
170 await client.runTool({
171 name: 'fetch_stats',
172 args: { queue: 'billing' },
173 inputId: 't-1',
174 }),
175 ).toMatchObject({ inputId: 't-1', status: 'accepted' })
176 void client
177 .runTool({
178 name: 'fetch_stats',
179 // @ts-expect-error `queue` must be a string.
180 args: { queue: 1 },
181 })
182 .catch(() => {})
183 await waitFor(async () =>
184 expect(
185 JSON.stringify(
186 await logMessageStore({ store: persistence.stores.log }).loadThread(
187 'thread-tool',
188 ),
189 ),
190 ).toContain('billing'),
191 )
192 expect(calls).toHaveLength(0)
193 expect(
194 await client.appendRecords({ records: [{ type: 'app.signal' }] }),
195 ).toMatchObject({
196 status: 'rejected',
197 reason: 'not_exposed',
198 })
199 await host.close()
200 })
201​
202 it('sends ephemeral messages with prompt and continue, and no store keeps them', async () => {
203 const { adapter, calls } = mockAdapter([
204 () => text('one'),
205 () => text('two'),
206 ])
207 const studio = defineHarness({ name: 'test/client-ephemeral', adapter })
208 const persistence = memoryPersistence()
209 // The thread is in the default tenant.
210 const messages = logMessageStore({ store: persistence.stores.log })
211 const key = 'thread-eph'
212 await messages.saveThread(key, [{ id: 'u1', role: 'user', content: 'go' }])
213 const host = createHarnessHost({ persistence })
214 const handler = createHarnessHandler({
215 host,
216 harness: studio,
217 openAccess: { user: { id: 'u' } },
218 })
219 const client = createHarnessClient<typeof studio>({
220 url: 'http://local/api/harness',
221 threadId: 'thread-eph',
222 fetch: (input, init) => handler(new Request(input, init)),
223 })
224​
225 await client.continueWithoutMessage({
226 ephemeral: [{ role: 'user', content: 'note 1' }],
227 })
228 await client.send('again', {
229 ephemeral: [{ role: 'user', content: 'note 2' }],
230 })
231 await waitFor(async () =>
232 expect(await messages.loadThread(key)).toHaveLength(4),
233 )
234​
235 expect(messageTexts(calls[0])).toEqual(['go', 'note 1'])
236 expect(messageTexts(calls[1])).toEqual(['go', 'one', 'again', 'note 2'])
237 expect(JSON.stringify(await messages.loadThread(key))).not.toContain('note')
238 await host.close()
239 })
240​
241 it('throws on a refused request instead of retrying', async () => {
242 const { adapter } = mockAdapter([])
243 const studio = defineHarness({ name: 'test/client-denied', adapter })
244 const host = createHarnessHost({
245 persistence: memoryPersistence(),
246 access: { getUser: () => null, rules: { isAllowed: () => true } },
247 })
248 const handler = createHarnessHandler({ host, harness: studio })
249 const client = createHarnessClient<typeof studio>({
250 url: 'http://local/api/harness',
251 threadId: 't',
252 fetch: (input, init) => handler(new Request(input, init)),
253 })
254 await expect(client.send('hi')).rejects.toThrow('401')
255 await expect(async () => {
256 for await (const _ of client.events()) break
257 }).rejects.toThrow('401')
258 await host.close()
259 })
260})
261​
262describe('client.events with no from', () => {
263 it('starts at the head, so it does not send the old events again', async () => {
264 const { adapter } = mockAdapter([
265 () => text('the old answer'),
266 () => text('the new answer'),
267 ])
268 const harness = defineHarness({ name: 'test/client-head', adapter })
269 const host = createHarnessHost({ persistence: memoryPersistence() })
270 const handler = createHarnessHandler({
271 host,
272 harness,
273 openAccess: { user: { id: 'u' } },
274 })
275 const client = createHarnessClient<typeof harness>({
276 url: 'http://local/api/harness',
277 threadId: 't-head',
278 fetch: (input, init) => handler(new Request(input, init)),
279 })
280 const session = await host.open(harness, { threadId: 't-head' })
281 await session.send('one')
282 const { cursor } = await client.snapshot()
283​
284 const controller = new AbortController()
285 const seen: Array<SessionEvent> = []
286 const opened = gate()
287 const reading = (async () => {
288 const events = client.events({
289 signal: controller.signal,
290 onConnection: (state) => {
291 if (state === 'open') opened.open()
292 },
293 })
294 for await (const entry of events) {
295 seen.push(entry)
296 if (
297 entry.event.type === 'CUSTOM' &&
298 entry.event.name === 'harness.operation.finished'
299 ) {
300 controller.abort()
301 }
302 }
303 })()
304 // The read asks for the head first, then streams from it.
305 await opened.opened
306 await session.send('two')
307 await reading
308​
309 const body = JSON.stringify(seen)
310 expect(body).toContain('the new answer')
311 expect(body).not.toContain('the old answer')
312 expect(seen.every((entry) => Number(entry.cursor) > Number(cursor))).toBe(
313 true,
314 )
315 await session.close()
316 await host.close()
317 })
318​
319 it('throws, with no retry, when the snapshot has no cursor', async () => {
320 let reads = 0
321 const client = createHarnessClient({
322 url: 'http://local/api/harness',
323 threadId: 't',
324 fetch: async () => {
325 reads += 1
326 return Response.json({ status: 'idle' })
327 },
328 })
329​
330 await expect(async () => {
331 for await (const _ of client.events()) break
332 }).rejects.toThrow('no string "cursor"')
333 expect(reads).toBe(1)
334 })
335})
336​
337describe('client.send to an agent run', () => {
338 it('sends a message to an agent run, as the request user', async () => {
339 const hold = gate()
340 const drafter = defineAgent({
341 name: 'drafter',
342 description: 'Drafts when the test lets it',
343 inputSchema: z.object({ topic: z.string() }),
344 run: async (ctx) => {
345 await hold.opened
346 return `a draft about ${ctx.input.topic}`
347 },
348 })
349 const studio = defineHarness({
350 name: 'test/client-agent-messages',
351 adapter: mockAdapter([]).adapter,
352 agents: [drafter],
353 expose: { agents: ['drafter'] },
354 })
355 const host = createHarnessHost({ persistence: memoryPersistence() })
356 const handler = createHarnessHandler({
357 host,
358 harness: studio,
359 openAccess: { user: { id: 'u' } },
360 })
361 const client = createHarnessClient<typeof studio>({
362 url: 'http://local/api/harness',
363 threadId: 'thread-m',
364 fetch: (input, init) => handler(new Request(input, init)),
365 })
366​
367 const started = await client.agents.drafter.start({ topic: 'tea' })
368 const receipt = await client.send('Add a title.', {
369 to: started.operationId ?? '',
370 mode: 'followUp',
371 inputId: 'm-1',
372 })
373​
374 expect(receipt).toMatchObject({ inputId: 'm-1', status: 'queued' })
375 const session = await host.open(studio, { threadId: 'thread-m' })
376 expect(session.agentRuns()).toMatchObject([
377 { operationId: started.operationId, agent: 'drafter' },
378 {
379 operationId: receipt.operationId,
380 status: 'queued',
381 user: { id: 'u' },
382 },
383 ])
384 hold.open()
385 await host.close()
386 })
387})
388​
389describe('client.sessions share and unshare', () => {
390 it('shares a session with a user, unshares them, and throws for a missing thread', async () => {
391 const studio = defineHarness({
392 name: 'test/client-share',
393 adapter: mockAdapter(() => text('ok')).adapter,
394 })
395 const users = new Map([
396 ['olga', { id: 'olga' }],
397 ['bea', { id: 'bea' }],
398 ])
399 const host = createHarnessHost({
400 persistence: memoryPersistence(),
401 access: {
402 getUser: ({ request }) =>
403 users.get(request.headers.get('x-user') ?? '') ?? null,
404 rules: membersOnly(),
405 },
406 })
407 const handler = createHarnessHandler({ host, harness: studio })
408 const clientOf = (userId: string) =>
409 createHarnessClient<typeof studio>({
410 url: 'http://local/api/harness',
411 threadId: 't1',
412 headers: { 'x-user': userId },
413 fetch: (input, init) => handler(new Request(input, init)),
414 })
415 const olga = clientOf('olga')
416 const bea = clientOf('bea')
417 await olga.send('hi')
418​
419 const shared = await olga.sessions.share({
420 threadId: 't1',
421 userId: 'bea',
422 role: 'viewer',
423 })
424​
425 expect(shared.members).toEqual([
426 { userId: 'olga', role: 'owner' },
427 { userId: 'bea', role: 'viewer' },
428 ])
429 await expect(bea.transcript()).resolves.toBeDefined()
430​
431 const unshared = await olga.sessions.unshare({
432 threadId: 't1',
433 userId: 'bea',
434 })
435​
436 expect(unshared.members).toEqual([{ userId: 'olga', role: 'owner' }])
437 await expect(bea.transcript()).rejects.toThrow('403')
438 await expect(
439 olga.sessions.share({
440 threadId: 't-none',
441 userId: 'bea',
442 role: 'member',
443 }),
444 ).rejects.toThrow('404')
445 await host.close()
446 })
447})