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

transfer.test.ts

669 lines21.0 KB

1import { describe, expect, it, vi } from 'vitest'
2import { z } from 'zod'
3import { EventType, toolDefinition } from '@tanstack/ai'
4import {
5 memoryLogState,
6 memoryLogStore,
7 memoryPersistence,
8} from '@tanstack/ai-persistence'
9import {
10 AccessDeniedError,
11 configOption,
12 createHarnessHost,
13 defineHarness,
14 definePlugin,
15 logIdOf,
16 membersOnly,
17} from '../src'
18import { mediaIdOf, mediaPart } from '../src/media-entry'
19import {
20 after,
21 gate,
22 messageTexts,
23 mockAdapter,
24 storedThreadState,
25 text,
26 toolCall,
27 turnInterrupts,
28 wrapLogStore,
29} from './helpers'
30import type { ModelMessage, StreamChunk } from '@tanstack/ai'
31import type { LogStore } from '@tanstack/ai-persistence'
32import type { HarnessHost, HostEvent } from '../src'
33import type { Reply } from './helpers'
34​
35// Coverage runs in CI are slow, so polled checks wait up to 5 s.
36const waitFor = <T>(check: () => T | Promise<T>) =>
37 vi.waitFor(check, { timeout: 5_000 })
38​
39interface User {
40 id: string
41 tenantId: string
43​
44const olga: User = { id: 'olga', tenantId: 'acme' }
45const bea: User = { id: 'bea', tenantId: 'acme' }
46const cid: User = { id: 'cid', tenantId: 'acme' }
47const gus: User = { id: 'gus', tenantId: 'globex' }
48​
49const SOURCE = 'src'
50const NOTE = 'Refund for order 42.'
51​
52/** A plugin with a config option and a counter in its saved state. */
53const counter = definePlugin({
54 name: 'test/counter',
55 setup: (ctx) => {
56 const state = ctx.state({ count: 0 })
57 return {
58 config: {
59 tone: configOption.select({
60 options: ['plain', 'warm'],
61 default: 'plain',
62 }),
63 },
64 tools: [
65 toolDefinition({
66 name: 'count',
67 description: 'Count one up',
68 inputSchema: z.object({}),
69 }).server(async () => {
70 await state.update((current) => ({ count: current.count + 1 }))
71 return 'counted'
72 }),
73 ],
74 }
75 },
76})
77​
78const contents = (messages: ReadonlyArray<ModelMessage>) =>
79 messages.map(
80 (message) => `${message.role}:${JSON.stringify(message.content)}`,
81 )
82​
83/** `chunks` with this usage on RUN_FINISHED, as a provider reports it. */
84function withUsage(
85 chunks: Array<StreamChunk>,
86 prompt: number,
87 completion: number,
88) {
89 return chunks.map((chunk) =>
90 chunk.type === EventType.RUN_FINISHED
91 ? {
92 ...chunk,
93 usage: {
94 promptTokens: prompt,
95 completionTokens: completion,
96 totalTokens: prompt + completion,
97 },
98 }
99 : chunk,
100 )
102​
103/** The records of the log of a thread of tenant `acme`, in order. */
104async function recordsOf(log: LogStore, threadId: string) {
105 const entries = await log.read({
106 logId: logIdOf({ tenantId: 'acme', logId: threadId }),
107 })
108 return entries.map((entry) => entry.record)
110​
111const transfersIn = async (log: LogStore, threadId: string) =>
112 (await recordsOf(log, threadId)).filter(
113 (record) => record.type === 'harness.transferred',
114 )
115​
116/**
117 * A host with `membersOnly()` access, a `support` harness (the source) and
118 * a `billing` harness (the target), each with scripted turns.
119 */
120function accessHost({
121 support = () => text('ok'),
122 billing = () => text('billing here'),
123}: { support?: Array<Reply> | Reply; billing?: Array<Reply> | Reply } = {}) {
124 const persistence = memoryPersistence()
125 const host: HarnessHost<User> = createHarnessHost({
126 persistence,
127 access: { getUser: (): User | null => null, rules: membersOnly() },
128 })
129 const supportModel = mockAdapter(support)
130 const billingModel = mockAdapter(billing)
131 return {
132 host,
133 log: persistence.stores.log,
134 support: defineHarness({
135 name: 'test/support',
136 adapter: supportModel.adapter,
137 }),
138 billing: defineHarness({
139 name: 'test/billing',
140 adapter: billingModel.adapter,
141 }),
142 supportCalls: supportModel.calls,
143 billingCalls: billingModel.calls,
144 }
146​
147/** Read `host.events()` into a list until `stop` runs. */
148function readEvents(host: HarnessHost<User>) {
149 const events: Array<HostEvent> = []
150 const reader = new AbortController()
151 const reading = (async () => {
152 for await (const event of host.events({ signal: reader.signal })) {
153 events.push(event)
154 }
155 })()
156 const stop = async () => {
157 reader.abort()
158 await reading
159 }
160 return { events, stop }
162​
163describe('host.transfer to a new thread', () => {
164 it('makes a thread of the target harness in the source tenant, with the user as its only member', async () => {
165 const { host, support, billing, billingCalls } = accessHost()
166 const reader = readEvents(host)
167 const source = await host.open(support, {
168 threadId: SOURCE,
169 user: olga,
170 })
171 await source.send('one')
172 await host.sessions.share({
173 threadId: SOURCE,
174 userId: bea.id,
175 role: 'member',
176 user: olga,
177 })
178​
179 const { transferId, threadId } = await host.transfer({
180 from: { harness: support, threadId: SOURCE },
181 to: { harness: billing },
182 envelope: { note: NOTE },
183 user: olga,
184 })
185​
186 const entry = await host.sessions.get({ threadId, user: olga })
187 expect(entry).toMatchObject({
188 tenantId: 'acme',
189 harness: 'test/billing',
190 members: [{ userId: 'olga', role: 'owner' }],
191 metadata: {
192 'harness:transferredFrom': [
193 { transferId, harness: 'test/support', threadId: SOURCE },
194 ],
195 },
196 })
197 expect(entry?.parentThreadId).toBeUndefined()
198 const sourceEntry = await host.sessions.get({
199 threadId: SOURCE,
200 user: olga,
201 })
202 expect(sourceEntry?.metadata).toMatchObject({
203 'harness:transferredTo': [
204 { transferId, harness: 'test/billing', threadId },
205 ],
206 })
207 // The target is a root thread: the list has it, and it opens alone.
208 const listed = await host.sessions.list({ user: olga })
209 expect(listed.entries.map((listedEntry) => listedEntry.threadId)).toContain(
210 threadId,
211 )
212 const target = await host.open(billing, { threadId, user: olga })
213 // `messages` defaults to 'none': the note alone.
214 expect(contents(await target.transcript())).toEqual([
215 `user:${JSON.stringify(NOTE)}`,
216 ])
217 await target.send('Hi.')
218 expect(messageTexts(billingCalls[0])).toEqual([NOTE, 'Hi.'])
219 // The members of the source do not come along.
220 await expect(
221 host.open(billing, { threadId, user: bea }),
222 ).rejects.toBeInstanceOf(AccessDeniedError)
223 // The source goes on.
224 await source.send('two')
225 expect(source.snapshot().status).toBe('idle')
226​
227 await waitFor(() =>
228 expect(reader.events).toContainEqual({
229 type: 'transferred',
230 transferId,
231 tenantId: 'acme',
232 from: { harness: 'test/support', threadId: SOURCE },
233 to: { harness: 'test/billing', threadId },
234 userId: 'olga',
235 at: expect.any(Number),
236 }),
237 )
238 await reader.stop()
239 await host.close()
240 })
241​
242 it("copies the settled messages and their media for messages: 'all', and no settings, config, state, or waits", async () => {
243 const deploy = toolDefinition({
244 name: 'deploy',
245 description: 'Deploy',
246 inputSchema: z.object({}),
247 needsApproval: true,
248 }).server(async () => 'deployed')
249 const { adapter } = mockAdapter([
250 () => text('a cat'),
251 () => toolCall('count', {}, 'c1'),
252 () => text('counted once'),
253 () => toolCall('deploy', {}, 'c2'),
254 ])
255 const persistence = memoryPersistence()
256 const { log } = persistence.stores
257 const host = createHarnessHost({ persistence })
258 const support = defineHarness({
259 name: 'test/support',
260 adapter,
261 tools: [deploy],
262 models: { main: adapter },
263 plugins: () => [counter],
264 })
265 const billing = defineHarness({
266 name: 'test/billing',
267 adapter: mockAdapter(() => text('billing here')).adapter,
268 plugins: () => [counter],
269 })
270 const source = await host.open(support, {
271 threadId: SOURCE,
272 user: olga,
273 })
274 await source.updateThreadSettings({
275 settings: { model: 'main', instructions: 'Be brief.' },
276 })
277 await source.setPluginSetting({ key: 'tone', value: 'warm' })
278 const bytes = new Uint8Array([1, 2, 3, 4])
279 const record = await source.putMedia({
280 body: bytes,
281 mimeType: 'image/png',
282 name: 'cat.png',
283 })
284 await source.send([
285 { type: 'text', content: 'What is this?' },
286 mediaPart(record),
287 ])
288 await source.send('Count.')
289 await source.send('Deploy.')
290 expect(turnInterrupts(source.snapshot())).toHaveLength(1)
291​
292 const { threadId } = await host.transfer({
293 from: { harness: support, threadId: SOURCE },
294 to: { harness: billing },
295 envelope: { note: NOTE, messages: 'all' },
296 user: olga,
297 })
298​
299 const target = await host.open(billing, { threadId, user: olga })
300 const transcript = await target.transcript()
301 const sourceTranscript = await source.transcript()
302 // The note, then the transcript up to the deploy call, which has no
303 // result yet.
304 const settled = sourceTranscript.slice(0, -1)
305 expect(sourceTranscript.at(-1)?.toolCalls?.[0]?.id).toBe('c2')
306 expect(transcript.map((message) => message.role)).toEqual([
307 'user',
308 ...settled.map((message) => message.role),
309 ])
310 expect(transcript.slice(2).map((message) => message.content)).toEqual(
311 settled.slice(1).map((message) => message.content),
312 )
313 // The media file has a copy in the target thread.
314 const parts = Array.isArray(transcript[1]?.content)
315 ? transcript[1].content
316 : []
317 const id = parts.map(mediaIdOf).find((value) => value !== undefined)
318 if (!id) throw new Error('The transfer lost the media part.')
319 expect(id).not.toBe(record.id)
320 expect(await target.getMedia({ id })).toMatchObject({
321 threadId,
322 name: 'cat.png',
323 })
324 expect(await target.loadMedia({ id })).toEqual(bytes)
325 expect(await target.getMedia({ id: record.id })).toBeNull()
326 // Nothing else moved.
327 expect(target.threadSettings()).toEqual({})
328 expect(target.pluginSettings().tone?.value).toBe('plain')
329 expect(target.snapshot().plugins['test/counter']).toEqual({ count: 0 })
330 expect(turnInterrupts(target.snapshot())).toEqual([])
331 const types = new Set(
332 (
333 await log.read({
334 logId: logIdOf({ tenantId: 'acme', logId: threadId }),
335 })
336 ).map((entry) => entry.record.type),
337 )
338 for (const type of [
339 'harness.settings',
340 'harness.config',
341 'harness.plugin.state',
342 'harness.state',
343 'harness.wait',
344 'harness.interrupt',
345 ]) {
346 expect(types.has(type)).toBe(false)
347 }
348 await host.close()
349 })
350​
351 it("adds one summary message by the source model for messages: 'summary', and counts its usage in the source", async () => {
352 const { host, log, support, billing, supportCalls } = accessHost({
353 support: [
354 () => text('A1'),
355 () => withUsage(text('The user wants a refund.'), 7, 3),
356 ],
357 })
358 const source = await host.open(support, {
359 threadId: SOURCE,
360 user: olga,
361 })
362 await source.send('I want my money back.')
363​
364 const { threadId } = await host.transfer({
365 from: { harness: support, threadId: SOURCE },
366 to: { harness: billing },
367 envelope: { note: NOTE, messages: 'summary' },
368 user: olga,
369 })
370​
371 const target = await host.open(billing, { threadId, user: olga })
372 expect(contents(await target.transcript())).toEqual([
373 `user:${JSON.stringify(NOTE)}`,
374 `assistant:${JSON.stringify('Summary of the conversation so far:\nThe user wants a refund.')}`,
375 ])
376 // The model of the source read the transcript.
377 const [prompt] = messageTexts(supportCalls[1])
378 expect(prompt).toContain('I want my money back.')
379 expect(prompt).toContain('A1')
380 await waitFor(() =>
381 expect(source.usage().bySender.olga).toMatchObject({
382 calls: 1,
383 totalTokens: 10,
384 }),
385 )
386 // The summary call counts under the source `transfer`.
387 expect(source.usage().bySource).toEqual({
388 transfer: source.usage().bySender.olga,
389 })
390 expect(
391 (await recordsOf(log, SOURCE)).filter(
392 (record) => record.type === 'harness.usage',
393 ),
394 ).toEqual([
395 expect.objectContaining({ source: 'transfer', label: 'summary' }),
396 ])
397 expect(target.usage().total.calls).toBe(0)
398 await host.close()
399 })
400})
401​
402describe('host.transfer retries', () => {
403 it('writes one record with the same transferId in both logs, and a retry makes no second thread', async () => {
404 const { host, log, support, billing } = accessHost()
405 const source = await host.open(support, {
406 threadId: SOURCE,
407 user: olga,
408 })
409 await source.send('one')
410 const options = {
411 from: { harness: support, threadId: SOURCE },
412 to: { harness: billing },
413 envelope: { note: NOTE, messages: 'all' as const },
414 user: olga,
415 transferId: 'tr-1',
416 }
417​
418 const first = await host.transfer(options)
419 const second = await host.transfer(options)
420​
421 expect(second).toEqual(first)
422 expect(first.transferId).toBe('tr-1')
423 const listed = await host.sessions.list({ user: olga })
424 expect(listed.entries).toHaveLength(2)
425 const target = await host.open(billing, {
426 threadId: first.threadId,
427 user: olga,
428 })
429 expect(contents(await target.transcript())).toEqual([
430 `user:${JSON.stringify(NOTE)}`,
431 ...contents(await source.transcript()),
432 ])
433 expect(await transfersIn(log, first.threadId)).toEqual([
434 expect.objectContaining({
435 transferId: 'tr-1',
436 from: { harness: 'test/support', threadId: SOURCE },
437 user: { id: 'olga', tenantId: 'acme' },
438 }),
439 ])
440 expect(await transfersIn(log, SOURCE)).toEqual([
441 expect.objectContaining({
442 transferId: 'tr-1',
443 to: { harness: 'test/billing', threadId: first.threadId },
444 }),
445 ])
446 const entry = await host.sessions.get({
447 threadId: first.threadId,
448 user: olga,
449 })
450 expect(entry?.metadata?.['harness:transferredFrom']).toHaveLength(1)
451 await host.close()
452 })
453​
454 it('writes only the source record on a retry after the source write failed', async () => {
455 const logState = memoryLogState()
456 const log = memoryLogStore({ state: logState })
457 const { sessions } = memoryPersistence().stores
458 // The first host cannot write the source end of a transfer.
459 const failing = wrapLogStore(log, {
460 append: (options) =>
461 options.records.some(
462 (record) => record.type === 'harness.transferred',
463 ) && options.logId === logIdOf({ logId: SOURCE })
464 ? Promise.reject(new Error('The store is down.'))
465 : log.append(options),
466 })
467 const support = defineHarness({
468 name: 'test/support',
469 adapter: mockAdapter(() => text('ok')).adapter,
470 })
471 const billing = defineHarness({
472 name: 'test/billing',
473 adapter: mockAdapter(() => text('billing here')).adapter,
474 })
475 const options = {
476 from: { harness: support, threadId: SOURCE },
477 to: { harness: billing },
478 envelope: { note: NOTE },
479 transferId: 'tr-2',
480 }
481 const first = createHarnessHost({
482 persistence: { stores: { log: failing, sessions } },
483 })
484 const source = await first.open(support, { threadId: SOURCE })
485 await source.send('one')
486 await expect(first.transfer(options)).rejects.toThrow('The store is down.')
487 await first.close()
488​
489 const second = createHarnessHost({
490 persistence: { stores: { log, sessions } },
491 })
492 const { threadId } = await second.transfer(options)
493​
494 const target = await second.open(billing, { threadId })
495 expect(contents(await target.transcript())).toEqual([
496 `user:${JSON.stringify(NOTE)}`,
497 ])
498 const sourceState = await storedThreadState(log, { threadId: SOURCE })
499 expect(sourceState.transfers.get('tr-2')?.to).toEqual({
500 harness: 'test/billing',
501 threadId,
502 })
503 await second.close()
504 })
505})
506​
507describe('host.transfer access', () => {
508 it('refuses a user of another tenant, a non-member, and a member who is not the owner', async () => {
509 const { host, support, billing } = accessHost()
510 const source = await host.open(support, {
511 threadId: SOURCE,
512 user: olga,
513 })
514 await source.send('one')
515 await host.sessions.share({
516 threadId: SOURCE,
517 userId: cid.id,
518 role: 'member',
519 user: olga,
520 })
521 const transfer = (user: User) =>
522 host.transfer({
523 from: { harness: support, threadId: SOURCE },
524 to: { harness: billing },
525 envelope: { note: NOTE },
526 user,
527 })
528​
529 for (const user of [gus, bea, cid]) {
530 await expect(transfer(user)).rejects.toBeInstanceOf(AccessDeniedError)
531 }
532 // No target thread was made, in any tenant.
533 expect((await host.sessions.list({ user: olga })).entries).toHaveLength(1)
534 expect((await host.sessions.list({ user: gus })).entries).toEqual([])
535 await host.close()
536 })
537​
538 it('throws for a source thread that does not exist, also with no access', async () => {
539 const host = createHarnessHost({ persistence: memoryPersistence() })
540 const support = defineHarness({
541 name: 'test/support',
542 adapter: mockAdapter(() => text('ok')).adapter,
543 })
544 const billing = defineHarness({
545 name: 'test/billing',
546 adapter: mockAdapter(() => text('billing here')).adapter,
547 })
548​
549 await expect(
550 host.transfer({
551 from: { harness: support, threadId: 'case-42 ' },
552 to: { harness: billing, threadId: 'target' },
553 envelope: { note: NOTE, messages: 'all' },
554 }),
555 ).rejects.toThrow('Thread "case-42 " does not exist.')
556 expect(await host.sessions.get({ threadId: 'case-42 ' })).toBeUndefined()
557 expect(await host.sessions.get({ threadId: 'target' })).toBeUndefined()
558 await host.close()
559 })
560​
561 it('refuses an existing target of another harness, or one the user cannot send to, and keeps the members of a target it can', async () => {
562 const { host, support, billing } = accessHost()
563 const source = await host.open(support, {
564 threadId: SOURCE,
565 user: olga,
566 })
567 await source.send('one')
568 await host.open(support, { threadId: 'other', user: olga })
569 await host.open(billing, { threadId: 'bea-billing', user: bea })
570 await host.sessions.share({
571 threadId: 'bea-billing',
572 userId: olga.id,
573 role: 'viewer',
574 user: bea,
575 })
576 const transfer = (threadId: string) =>
577 host.transfer({
578 from: { harness: support, threadId: SOURCE },
579 to: { harness: billing, threadId },
580 envelope: { note: NOTE },
581 user: olga,
582 })
583​
584 await expect(transfer('other')).rejects.toThrow(
585 'belongs to harness "test/support"',
586 )
587 await expect(transfer('bea-billing')).rejects.toBeInstanceOf(
588 AccessDeniedError,
589 )
590 await host.sessions.share({
591 threadId: 'bea-billing',
592 userId: olga.id,
593 role: 'member',
594 user: bea,
595 })
596 await transfer('bea-billing')
597 const entry = await host.sessions.get({
598 threadId: 'bea-billing',
599 user: bea,
600 })
601 expect(entry?.members).toEqual([
602 { userId: 'bea', role: 'owner' },
603 { userId: 'olga', role: 'member' },
604 ])
605 await host.close()
606 })
607})
608​
609describe('host.transfer across hosts', () => {
610 it('writes the source record through the input lane when another host owns the source', async () => {
611 const logState = memoryLogState()
612 const { sessions } = memoryPersistence().stores
613 const release = gate()
614 const support = defineHarness({
615 name: 'test/support',
616 adapter: mockAdapter([() => text('A1'), after(release.opened, 'A2')])
617 .adapter,
618 })
619 const billing = defineHarness({
620 name: 'test/billing',
621 adapter: mockAdapter(() => text('billing here')).adapter,
622 })
623 const one = createHarnessHost({
624 persistence: {
625 stores: { log: memoryLogStore({ state: logState }), sessions },
626 },
627 })
628 const twoLog = memoryLogStore({ state: logState })
629 const two = createHarnessHost({
630 persistence: { stores: { log: twoLog, sessions } },
631 })
632 const source = await one.open(support, { threadId: SOURCE })
633 await source.send('one')
634 // Host one owns the log while this turn runs.
635 const turn = source.send('two')
636 await waitFor(() => expect(source.snapshot().status).toBe('running'))
637​
638 const { threadId } = await two.transfer({
639 from: { harness: support, threadId: SOURCE },
640 to: { harness: billing },
641 envelope: { note: NOTE, messages: 'all' },
642 transferId: 'tr-3',
643 })
644​
645 // Host one appended the offered record.
646 await waitFor(async () =>
647 expect(
648 (await storedThreadState(twoLog, { threadId: SOURCE })).transfers.get(
649 'tr-3',
650 )?.to,
651 ).toEqual({ harness: 'test/billing', threadId }),
652 )
653 expect(
654 await twoLog.listOfferedInputs({ logId: logIdOf({ logId: SOURCE }) }),
655 ).toEqual([])
656 // The saved messages moved: not the answer of the turn that runs.
657 const target = await two.open(billing, { threadId })
658 expect(contents(await target.transcript())).toEqual([
659 `user:${JSON.stringify(NOTE)}`,
660 'user:"one"',
661 'assistant:"A1"',
662 'user:"two"',
663 ])
664 release.open()
665 await turn
666 await one.close()
667 await two.close()
668 })
669})