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

fork.test.ts

277 lines9.2 KB

1import { describe, expect, it } from 'vitest'
2import { z } from 'zod'
3import { toolDefinition } from '@tanstack/ai'
4import { memoryLogStore, memoryPersistence } from '@tanstack/ai-persistence'
5import {
6 configOption,
7 createHarnessHost,
8 defineHarness,
9 definePlugin,
10} from '../src'
11import { mediaIdOf, mediaPart } from '../src/media-entry'
12import {
13 messageTexts,
14 mockAdapter,
15 text,
16 toolCall,
17 turnInterrupts,
18} from './helpers'
19import type { ModelMessage } from '@tanstack/ai'
20import type { HarnessPersistence, HostLifecycleOptions } from '../src'
21​
22const SOURCE = 'source'
23const FORK = 'fork'
24​
25function durablePersistence() {
26 const { metadata } = memoryPersistence().stores
27 return { stores: { log: memoryLogStore(), metadata } }
29​
30/** A plugin with a config option and a counter in its saved state. */
31const counter = definePlugin({
32 name: 'test/counter',
33 setup: (ctx) => {
34 const state = ctx.state({ count: 0 })
35 return {
36 config: {
37 tone: configOption.select({
38 options: ['plain', 'warm'],
39 default: 'plain',
40 }),
41 },
42 tools: [
43 toolDefinition({
44 name: 'count',
45 description: 'Count one up',
46 inputSchema: z.object({}),
47 }).server(async () => {
48 await state.update((current) => ({ count: current.count + 1 }))
49 return 'counted'
50 }),
51 ],
52 }
53 },
54})
55​
56const contents = (messages: ReadonlyArray<ModelMessage>) =>
57 messages.map(
58 (message) => `${message.role}:${JSON.stringify(message.content)}`,
59 )
60​
61describe('host.fork of the transcript', () => {
62 const setup = (
63 persistence: HarnessPersistence,
64 lifecycle: HostLifecycleOptions = {},
65 ) => {
66 const { adapter, calls } = mockAdapter([
67 () => text('A1'),
68 () => text('A2'),
69 () => text('A3'),
70 ])
71 const harness = defineHarness({ name: 'test/fork', adapter })
72 const host = createHarnessHost({ persistence, lifecycle })
73 return { harness, host, calls }
74 }
75​
76 it('copies the transcript up to a message, and the fork goes on alone', async () => {
77 const persistence = durablePersistence()
78 const { harness, host, calls } = setup(persistence)
79 const source = await host.open(harness, { threadId: SOURCE })
80 await source.send('one')
81 await source.send('two')
82 const before = await source.transcript()
83 const firstAnswer = before[1]
84 if (!firstAnswer?.id) throw new Error('The answer has no id.')
85​
86 const fork = await host.fork(harness, {
87 threadId: SOURCE,
88 newThreadId: FORK,
89 at: firstAnswer.id,
90 })
91 expect(contents(await fork.transcript())).toEqual(
92 contents(before.slice(0, 2)),
93 )
94​
95 await fork.send('three')
96 expect(messageTexts(calls[2])).toEqual(['one', 'A1', 'three'])
97 // The source keeps its own transcript.
98 expect(contents(await source.transcript())).toEqual(contents(before))
99 await host.close()
100​
101 // A later host folds the fork from its log.
102 const later = createHarnessHost({ persistence })
103 const reopened = await later.open(harness, { threadId: FORK })
104 expect((await reopened.transcript()).map((m) => m.role)).toEqual([
105 'user',
106 'assistant',
107 'user',
108 'assistant',
109 ])
110 await later.close()
111 })
112​
113 it('closes a source that only the fork opened, and keeps one the app has open', async () => {
114 const persistence = durablePersistence()
115 // A session that no handle holds closes at once when it is idle.
116 const { harness, host } = setup(persistence, {
117 closeIdleSessionsAfterMs: 0,
118 })
119 const source = await host.open(harness, { threadId: SOURCE })
120 await source.send('one')
121 await host.fork(harness, { threadId: SOURCE, newThreadId: FORK })
122 // The app opened the source: the fork left it open.
123 expect(host.isOpen(harness, { threadId: SOURCE })).toBe(true)
124 await source.close()
125 expect(host.isOpen(harness, { threadId: SOURCE })).toBe(false)
126 await host.fork(harness, { threadId: SOURCE, newThreadId: 'other' })
127 // The fork opened the source itself, and released it at the end.
128 expect(host.isOpen(harness, { threadId: SOURCE })).toBe(false)
129 await host.close()
130 })
131​
132 it('copies the whole transcript by default, no messages for a null at, and refuses an unknown message or a used thread', async () => {
133 const persistence = durablePersistence()
134 const { harness, host } = setup(persistence)
135 const source = await host.open(harness, { threadId: SOURCE })
136 await source.send('one')
137​
138 const whole = await host.fork(harness, {
139 threadId: SOURCE,
140 newThreadId: FORK,
141 })
142 expect(contents(await whole.transcript())).toEqual(
143 contents(await source.transcript()),
144 )
145 const empty = await host.fork(harness, {
146 threadId: SOURCE,
147 newThreadId: 'empty',
148 at: null,
149 })
150 expect(await empty.transcript()).toEqual([])
151 await expect(
152 host.fork(harness, { threadId: SOURCE, newThreadId: 'other', at: 'm-x' }),
153 ).rejects.toThrow('m-x')
154 // The fork thread has messages now.
155 await expect(
156 host.fork(harness, { threadId: SOURCE, newThreadId: FORK }),
157 ).rejects.toThrow(FORK)
158 await host.close()
159 })
160})
161​
162describe('host.fork', () => {
163 it('copies the settings and plugin config, but not plugin state or interrupts', async () => {
164 const deploy = toolDefinition({
165 name: 'deploy',
166 description: 'Deploy',
167 inputSchema: z.object({}),
168 needsApproval: true,
169 }).server(async () => 'deployed')
170 const { adapter } = mockAdapter([
171 () => toolCall('count', {}, 'c1'),
172 () => text('counted once'),
173 () => toolCall('deploy', {}, 'c2'),
174 ])
175 const harness = defineHarness({
176 name: 'test/fork',
177 adapter,
178 tools: [deploy],
179 models: { main: adapter },
180 plugins: () => [counter],
181 })
182 const host = createHarnessHost({ persistence: memoryPersistence() })
183 const source = await host.open(harness, { threadId: SOURCE })
184 await source.updateThreadSettings({
185 settings: { model: 'main', instructions: 'Be brief.' },
186 })
187 await source.setPluginSetting({ key: 'tone', value: 'warm' })
188 await source.send('Count.')
189 await source.send('Deploy.')
190 expect(turnInterrupts(source.snapshot())).toHaveLength(1)
191 expect(source.snapshot().plugins['test/counter']).toEqual({ count: 1 })
192​
193 const fork = await host.fork(harness, {
194 threadId: SOURCE,
195 newThreadId: FORK,
196 })
197 expect(fork.threadSettings()).toEqual({
198 model: 'main',
199 instructions: 'Be brief.',
200 })
201 expect(fork.pluginSettings().tone?.value).toBe('warm')
202 expect(fork.snapshot().plugins['test/counter']).toEqual({ count: 0 })
203 expect(turnInterrupts(fork.snapshot())).toEqual([])
204 await host.close()
205 })
206​
207 it('copies the media of the copied messages, so the fork loads them', async () => {
208 const { adapter } = mockAdapter(() => text('a cat'))
209 const harness = defineHarness({ name: 'test/fork', adapter })
210 const host = createHarnessHost({ persistence: memoryPersistence() })
211 const source = await host.open(harness, { threadId: SOURCE })
212 const bytes = new Uint8Array([1, 2, 3, 4])
213 const record = await source.putMedia({
214 body: bytes,
215 mimeType: 'image/png',
216 name: 'cat.png',
217 })
218 await source.send([
219 { type: 'text', content: 'What is this?' },
220 mediaPart(record),
221 ])
222​
223 const fork = await host.fork(harness, {
224 threadId: SOURCE,
225 newThreadId: FORK,
226 })
227 const [question] = await fork.transcript()
228 const parts = Array.isArray(question?.content) ? question.content : []
229 const id = parts.map(mediaIdOf).find((value) => value !== undefined)
230 if (!id) throw new Error('The fork lost the media part.')
231​
232 expect(id).not.toBe(record.id)
233 expect(await fork.getMedia({ id })).toMatchObject({
234 threadId: FORK,
235 name: 'cat.png',
236 })
237 expect(await fork.loadMedia({ id })).toEqual(bytes)
238 // Each thread sees only its own media.
239 expect(await fork.getMedia({ id: record.id })).toBeNull()
240 expect(await source.getMedia({ id })).toBeNull()
241 await host.close()
242 })
243})
244​
245describe('a fork stays in its harness', () => {
246 it('refuses host.fork and host.sessions.fork of a thread of another harness', async () => {
247 const support = defineHarness({
248 name: 'test/support',
249 adapter: mockAdapter(() => text('ok')).adapter,
250 })
251 const billing = defineHarness({
252 name: 'test/billing',
253 adapter: mockAdapter(() => text('billing here')).adapter,
254 plugins: () => [counter],
255 })
256 const host = createHarnessHost({ persistence: memoryPersistence() })
257 const source = await host.open(support, { threadId: SOURCE })
258 await source.send('one')
259​
260 await expect(
261 host.fork(billing, { threadId: SOURCE, newThreadId: FORK }),
262 ).rejects.toThrow(
263 `Thread "${SOURCE}" belongs to harness "test/support", not "test/billing".`,
264 )
265 await expect(
266 host.sessions.fork({
267 harness: billing,
268 threadId: SOURCE,
269 at: { through: 'any' },
270 }),
271 ).rejects.toThrow('belongs to harness "test/support"')
272 // Nothing opened the source under the other harness, and no fork exists.
273 expect(host.isOpen(billing, { threadId: SOURCE })).toBe(false)
274 expect(await host.sessions.get({ threadId: FORK })).toBeUndefined()
275 await host.close()
276 })
277})