Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { EventType } from '@tanstack/ai'
3import { memoryLogStore, memoryPersistence } from '@tanstack/ai-persistence'
4import {
5 createHarnessHost,
6 defineCommand,
7 defineHarness,
8 definePlugin,
9 logIdOf,
10} from '../src'
11import { gate, mockAdapter, text, untilAborted } from './helpers'
12import type { ChatMiddleware, StreamChunk } from '@tanstack/ai'
13import type { HarnessPlugin, HarnessRunContext, SessionEvent } from '../src'
14import type { Reply } from './helpers'
15
16const THREAD = 't1'
17const alice = { id: 'alice' }
18
19// Coverage runs in CI are slow, so polled checks wait up to 5 s.
20const waitFor = <T>(check: () => T | Promise<T>) =>
21 vi.waitFor(check, { timeout: 5_000 })
22
23/** `content` as one model call that reports 7 prompt and 3 completion tokens. */
24const answerWithUsage =
25 (content: string): Reply =>
26 () =>
27 text(content).map(
28 (chunk): StreamChunk =>
29 chunk.type === EventType.RUN_FINISHED
30 ? {
31 ...chunk,
32 usage: { promptTokens: 7, completionTokens: 3, totalTokens: 10 },
33 }
34 : chunk,
35 )
36
37/** Open `THREAD` with `plugins`. The main model answers with `main`. */
38async function open(
39 plugins: Array<HarnessPlugin>,
40 main: Array<Reply>,
41 middleware?: Array<ChatMiddleware<HarnessRunContext>>,
42) {
43 const log = memoryLogStore()
44 const { metadata } = memoryPersistence().stores
45 const host = createHarnessHost({ persistence: { stores: { log, metadata } } })
46 const session = await host.open(
47 defineHarness({
48 name: 'test/plugin-model',
49 adapter: mockAdapter(main).adapter,
50 plugins: () => plugins,
51 ...(middleware ? { middleware } : {}),
52 }),
53 { threadId: THREAD, user: alice },
54 )
55 return { host, session, log }
56}
57
58describe('ctx.model.chat', () => {
59 it('counts the usage under plugin:<name> with the label, in the session and in the run', async () => {
60 const checker = mockAdapter(answerWithUsage('looks fine'))
61 let runId = ''
62 const plugin = definePlugin({
63 name: 'test/checker',
64 setup: (ctx) => ({
65 commands: {
66 check: defineCommand({
67 description: 'Check',
68 run: async (_input, { run }) => {
69 runId = run.runId
70 const { text: answer } = await ctx.model.chat({
71 adapter: checker.adapter,
72 run,
73 label: 'check',
74 options: { messages: [{ role: 'user', content: 'Check it' }] },
75 })
76 return answer
77 },
78 }),
79 },
80 }),
81 })
82 const { host, session, log } = await open([plugin], [])
83 const seen: Array<SessionEvent> = []
84 const reader = new AbortController()
85 const reading = (async () => {
86 for await (const entry of session.events({ signal: reader.signal }))
87 seen.push(entry)
88 })()
89
90 expect(await session.runCommand({ name: 'check' })).toBe('looks fine')
91
92 const usage = session.usage()
93 expect(usage.total).toMatchObject({ calls: 1, totalTokens: 10 })
94 expect(usage.bySource).toEqual({ 'plugin:test/checker': usage.total })
95 expect(usage.bySender).toEqual({ alice: usage.total })
96 const records = (await log.read({ logId: logIdOf({ logId: THREAD }) }))
97 .map((entry) => entry.record)
98 .filter((record) => record.type === 'harness.usage')
99 expect(records).toEqual([
100 expect.objectContaining({
101 source: 'plugin:test/checker',
102 label: 'check',
103 runId,
104 user: alice,
105 }),
106 ])
107 await waitFor(() =>
108 expect(
109 seen.find(
110 (entry) =>
111 entry.event.type === EventType.CUSTOM &&
112 entry.event.name === 'harness.usage',
113 )?.event,
114 ).toMatchObject({
115 value: { source: 'plugin:test/checker', label: 'check' },
116 }),
117 )
118 reader.abort()
119 await reading.catch(() => {})
120 await host.close()
121 })
122
123 it('uses the model and the run of the turn by default, and stops when the turn is cancelled', async () => {
124 let call: Promise<unknown> | undefined
125 const plugin = definePlugin({
126 name: 'test/side-call',
127 lifetime: 'turn',
128 setup: (ctx) => ({
129 middleware: [
130 {
131 name: 'test/side-call',
132 onConfig: (run) => {
133 if (run.phase !== 'init' || call) return
134 call = ctx.model.chat({
135 options: { messages: [{ role: 'user', content: 'Side' }] },
136 })
137 // The test reads the rejection below.
138 call.catch(() => {})
139 },
140 },
141 ],
142 }),
143 })
144 // The plugin call and the turn both wait until they are aborted.
145 const { host, session } = await open(
146 [plugin],
147 [untilAborted(), untilAborted()],
148 )
149
150 const turn = session.send('go')
151 await waitFor(() => expect(call).toBeDefined())
152 await turn.cancel()
153
154 await expect(call).rejects.toThrow()
155 await expect(turn).rejects.toThrow('Cancelled.')
156 await host.close()
157 })
158
159 it('tells the harness middleware which call it sees: the turn, or a plugin call and its label', async () => {
160 const seen: Array<{ source?: string; label?: string }> = []
161 const recorder: ChatMiddleware<HarnessRunContext> = {
162 name: 'test/recorder',
163 onStart: (ctx) => {
164 const { source, label } = ctx.context.run
165 seen.push({ source, label })
166 },
167 }
168 const checker = mockAdapter(answerWithUsage('looks fine'))
169 const plugin = definePlugin({
170 name: 'test/checker',
171 setup: (ctx) => ({
172 commands: {
173 check: defineCommand({
174 description: 'Check',
175 run: async (_input, { run }) =>
176 (
177 await ctx.model.chat({
178 adapter: checker.adapter,
179 run,
180 label: 'check',
181 options: { messages: [{ role: 'user', content: 'Check' }] },
182 })
183 ).text,
184 }),
185 },
186 }),
187 })
188 const { host, session } = await open(
189 [plugin],
190 [() => text('hi')],
191 [recorder],
192 )
193
194 await session.send('hello')
195 await session.runCommand({ name: 'check' })
196
197 expect(seen).toEqual([
198 { source: 'turn', label: undefined },
199 { source: 'plugin:test/checker', label: 'check' },
200 ])
201 await host.close()
202 })
203
204 it('stops after timeoutMs', async () => {
205 const slow = mockAdapter(untilAborted())
206 const plugin = definePlugin({
207 name: 'test/slow',
208 setup: (ctx) => ({
209 commands: {
210 slow: defineCommand({
211 description: 'Slow',
212 run: async (_input, { run }) => {
213 const failure = await ctx.model
214 .chat({
215 adapter: slow.adapter,
216 run,
217 timeoutMs: 20,
218 options: { messages: [{ role: 'user', content: 'Wait' }] },
219 })
220 .then(
221 () => undefined,
222 (error: unknown) => error,
223 )
224 return failure instanceof Error ? failure.name : 'no error'
225 },
226 }),
227 },
228 }),
229 })
230 const { host, session } = await open([plugin], [])
231
232 expect(await session.runCommand({ name: 'slow' })).toBe('TimeoutError')
233 expect(slow.calls).toHaveLength(1)
234 await host.close()
235 })
236
237 it('needs a run in a session plugin', async () => {
238 let failure: unknown
239 const plugin = definePlugin({
240 name: 'test/no-run',
241 setup: (ctx) => ({
242 commands: {
243 go: defineCommand({
244 description: 'Go',
245 run: async () => {
246 failure = await ctx.model
247 .chat({ options: { messages: [] } })
248 .catch((error: unknown) => error)
249 },
250 }),
251 },
252 }),
253 })
254 const { host, session } = await open([plugin], [])
255
256 await session.runCommand({ name: 'go' })
257
258 expect(String(failure)).toContain(
259 'ctx.model.chat of test/no-run needs a run',
260 )
261 await host.close()
262 })
263
264 it('records the usage of a call that ends after its run, with no event after the run finished', async () => {
265 const late = gate()
266 const checker = mockAdapter(() =>
267 (async function* () {
268 await late.opened
269 yield* answerWithUsage('late')({})
270 })(),
271 )
272 let call: Promise<unknown> | undefined
273 let runId = ''
274 const plugin = definePlugin({
275 name: 'test/late',
276 setup: (ctx) => ({
277 commands: {
278 go: defineCommand({
279 description: 'Go',
280 // Next to the run, as the title plugin does: not awaited.
281 run: async (_input, { run }) => {
282 runId = run.runId
283 call = ctx.model.chat({
284 adapter: checker.adapter,
285 run,
286 options: { messages: [{ role: 'user', content: 'Later' }] },
287 })
288 },
289 }),
290 },
291 }),
292 })
293 const { host, session } = await open([plugin], [])
294 const seen: Array<SessionEvent> = []
295 const reader = new AbortController()
296 const reading = (async () => {
297 for await (const entry of session.events({ signal: reader.signal }))
298 seen.push(entry)
299 })()
300
301 await session.runCommand({ name: 'go' })
302 late.open()
303 await call
304
305 await waitFor(() => expect(session.usage().total.calls).toBe(1))
306 const ofRun = seen.filter((entry) => entry.operationId === runId)
307 const finished = ofRun.findIndex(
308 (entry) =>
309 entry.event.type === EventType.CUSTOM &&
310 entry.event.name === 'harness.operation.finished',
311 )
312 expect(finished).toBeGreaterThan(-1)
313 expect(ofRun.slice(finished + 1)).toEqual([])
314 reader.abort()
315 await reading.catch(() => {})
316 await host.close()
317 })
318})