Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { toolDefinition } from '@tanstack/ai'
3import { memoryPersistence } from '@tanstack/ai-persistence'
4import {
5 createHarnessHost,
6 defineCommand,
7 defineHarness,
8 definePlugin,
9} from '../src'
10import { mockAdapter, text, toolCall } from './helpers'
11import type { HarnessPlugin, HarnessRunContext } from '../src'
12import type { Reply } from './helpers'
13
14/** Calls `who` once, then answers after the tool result. */
15const callWho: Reply = (options) =>
16 options.messages.at(-1)?.role === 'tool' ? text('done') : toolCall('who', {})
17
18/** A host plugin that counts its setups and its cleanups. */
19function countedPlugin() {
20 const counts = { setups: 0, disposed: 0 }
21 const seen: Array<string | undefined> = []
22 const plugin = definePlugin({
23 name: 'test/shared',
24 lifetime: 'host',
25 setup: async (ctx) => {
26 counts.setups += 1
27 await ctx.resources.acquire(
28 () => 'pool',
29 () => {
30 counts.disposed += 1
31 },
32 )
33 return {
34 tools: [
35 toolDefinition({
36 name: 'who',
37 description: 'Name the caller',
38 }).server<HarnessRunContext>((_input, { context }) => {
39 seen.push(context.run.user?.id)
40 return 'ok'
41 }),
42 ],
43 }
44 },
45 })
46 return { plugin, counts, seen }
47}
48
49function setup(
50 plugins: () => ReadonlyArray<HarnessPlugin>,
51 closeIdleSessionsAfterMs = 0,
52 name = 'test/host-plugins',
53) {
54 const host = createHarnessHost({
55 persistence: memoryPersistence(),
56 lifecycle: { closeIdleSessionsAfterMs },
57 })
58 const harness = defineHarness({
59 name,
60 adapter: mockAdapter(callWho).adapter,
61 plugins,
62 })
63 return { host, harness }
64}
65
66describe('lifetime host', () => {
67 it('gives a new harness definition with the same name its own setup', async () => {
68 const first = countedPlugin()
69 const second = countedPlugin()
70 const host = createHarnessHost({
71 persistence: memoryPersistence(),
72 lifecycle: { closeIdleSessionsAfterMs: 0 },
73 })
74 // Two definitions under one name, with other plugin options, as an app
75 // that builds its harness for each request does.
76 const define = (plugin: HarnessPlugin) =>
77 defineHarness({
78 name: 'test/same-name',
79 adapter: mockAdapter(callWho).adapter,
80 plugins: () => [plugin],
81 })
82
83 const a = await host.open(define(first.plugin), { threadId: 'a' })
84 const b = await host.open(define(second.plugin), { threadId: 'b' })
85
86 expect(first.counts.setups).toBe(1)
87 expect(second.counts.setups).toBe(1)
88 await a.close()
89 await b.close()
90 await host.close()
91 })
92
93 it('sets up once for two sessions, and disposes after the last session closes', async () => {
94 const { plugin, counts } = countedPlugin()
95 const { host, harness } = setup(() => [plugin])
96
97 const first = await host.open(harness, { threadId: 'a' })
98 const second = await host.open(harness, { threadId: 'b' })
99 expect(counts).toEqual({ setups: 1, disposed: 0 })
100
101 await first.close()
102 expect(counts).toEqual({ setups: 1, disposed: 0 })
103 await second.close()
104 expect(counts).toEqual({ setups: 1, disposed: 1 })
105
106 // The next session sets it up again.
107 const third = await host.open(harness, { threadId: 'c' })
108 expect(counts).toEqual({ setups: 2, disposed: 1 })
109 await third.close()
110 await host.close()
111 })
112
113 it('gives each plugin object that the factory builds its own setup', async () => {
114 const setups: Array<string> = []
115 let built = 0
116 // A new plugin for each session, as `() => [mcp({...})]` builds one.
117 const { host, harness } = setup(() => {
118 built += 1
119 const own = `plugin-${built}`
120 return [
121 definePlugin({
122 name: 'test/per-session',
123 lifetime: 'host',
124 setup: () => {
125 setups.push(own)
126 },
127 }),
128 ]
129 })
130
131 const first = await host.open(harness, { threadId: 'a' })
132 const second = await host.open(harness, { threadId: 'b' })
133
134 expect(setups).toHaveLength(2)
135 expect(new Set(setups).size).toBe(2)
136 await first.close()
137 await second.close()
138 await host.close()
139 })
140
141 it('disposes at host.close() while sessions are open', async () => {
142 const { plugin, counts } = countedPlugin()
143 const { host, harness } = setup(() => [plugin], 60_000)
144 await host.open(harness, { threadId: 'a' })
145
146 await host.close()
147
148 expect(counts).toEqual({ setups: 1, disposed: 1 })
149 })
150
151 it('sets up once for each harness name', async () => {
152 const { plugin, counts } = countedPlugin()
153 const one = setup(() => [plugin], 60_000, 'test/one')
154 const other = defineHarness({
155 name: 'test/other',
156 adapter: mockAdapter(callWho).adapter,
157 plugins: () => [plugin],
158 })
159
160 await one.host.open(one.harness, { threadId: 'a' })
161 // One thread has one harness: the log of a thread is its own.
162 await one.host.open(other, { threadId: 'b' })
163
164 expect(counts.setups).toBe(2)
165 await one.host.close()
166 expect(counts.disposed).toBe(2)
167 })
168
169 it('gives its tool the user of the calling run', async () => {
170 const { plugin, seen } = countedPlugin()
171 const { host, harness } = setup(() => [plugin], 60_000)
172 const alice = await host.open(harness, {
173 threadId: 'a',
174 user: { id: 'alice' },
175 })
176 const bob = await host.open(harness, {
177 threadId: 'b',
178 user: { id: 'bob' },
179 })
180
181 await alice.send('who am I?')
182 await bob.send('who am I?')
183
184 expect(seen).toEqual(['alice', 'bob'])
185 await host.close()
186 })
187
188 it('still sets up a turn plugin for each turn, and a session plugin for each session', async () => {
189 const counts = { host: 0, session: 0, turn: 0 }
190 const shared = definePlugin({
191 name: 'test/host',
192 lifetime: 'host',
193 setup: () => {
194 counts.host += 1
195 },
196 })
197 const perSession = definePlugin({
198 name: 'test/session',
199 setup: () => {
200 counts.session += 1
201 },
202 })
203 const perTurn = definePlugin({
204 name: 'test/turn',
205 lifetime: 'turn',
206 setup: () => {
207 counts.turn += 1
208 },
209 })
210 const host = createHarnessHost({ persistence: memoryPersistence() })
211 const harness = defineHarness({
212 name: 'test/lifetimes',
213 adapter: mockAdapter(() => text('hi')).adapter,
214 plugins: () => [shared, perSession, perTurn],
215 })
216
217 for (const threadId of ['a', 'b']) {
218 const session = await host.open(harness, { threadId })
219 await session.send('one')
220 await session.send('two')
221 }
222
223 expect(counts).toEqual({ host: 1, session: 2, turn: 4 })
224 await host.close()
225 })
226
227 it('runs its session part for each session, with that session', async () => {
228 const closed: Array<string> = []
229 const plugin = definePlugin({
230 name: 'test/layered',
231 lifetime: 'host',
232 setup: () => ({
233 session: async (ctx) => {
234 await ctx.resources.acquire(
235 () => ctx.session.threadId,
236 (threadId) => closed.push(threadId),
237 )
238 return {
239 commands: {
240 thread: defineCommand({
241 description: 'Name the thread',
242 run: () => ctx.session.threadId,
243 }),
244 },
245 }
246 },
247 }),
248 })
249 const { host, harness } = setup(() => [plugin])
250 const first = await host.open(harness, { threadId: 'a' })
251 const second = await host.open(harness, { threadId: 'b' })
252
253 await expect(first.runCommand({ name: 'thread' })).resolves.toBe('a')
254 await expect(second.runCommand({ name: 'thread' })).resolves.toBe('b')
255 await first.close()
256
257 expect(closed).toEqual(['a'])
258 await host.close()
259 })
260
261 it('sets up again after a setup that failed', async () => {
262 let attempts = 0
263 const plugin = definePlugin({
264 name: 'test/flaky',
265 lifetime: 'host',
266 setup: () => {
267 attempts += 1
268 if (attempts === 1) throw new Error('no pool')
269 },
270 })
271 const { host, harness } = setup(() => [plugin])
272
273 await expect(host.open(harness, { threadId: 'a' })).rejects.toThrow(
274 'no pool',
275 )
276 const session = await host.open(harness, { threadId: 'a' })
277
278 expect(attempts).toBe(2)
279 await session.close()
280 await host.close()
281 })
282})