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

session-plugins.test.ts

944 lines29.8 KB

1import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
5import { z } from 'zod'
6import { EventType, toolDefinition } from '@tanstack/ai'
7import { memoryPersistence } from '@tanstack/ai-persistence'
8import {
9 checkConfigValue,
10 configOption,
11 createHarnessHost,
12 createPluginEvent,
13 defineCommand,
14 durableTool,
15 defineHarness,
16 definePlugin,
17} from '../src'
18import { compact, modelPicker, todos, usage } from '../src/first-party'
19import { fileCommands, projectInstructions } from '../src/first-party/node'
20import { loadLogState, logIdOf, sessionOf } from '../src/log'
21import {
22 after,
23 appendToLog,
24 gate,
25 mockAdapter,
26 questionsOf,
27 text,
28 toolCall,
29} from './helpers'
30import type { PluginSessionApi, PluginState, SessionEvent } from '../src'
31​
32// Coverage runs in CI are slow, so polled checks wait up to 5 s.
33const waitFor = <T>(
34 check: () => T | Promise<T>,
35 options?: { timeout?: number; interval?: number },
36) => vi.waitFor(check, { timeout: 5_000, ...options })
37​
38const settings = definePlugin({
39 name: 'test/settings',
40 setup: () => ({
41 config: {
42 level: configOption.select({ options: ['low', 'high'], default: 'low' }),
43 verbose: configOption.boolean({ default: false }),
44 label: configOption.text({ default: 'none' }),
45 retries: configOption.number({ default: 1, min: 0, max: 5 }),
46 },
47 }),
48})
49​
50describe('config values', () => {
51 it('checks every option type and its limits', () => {
52 const number = configOption.number({ default: 1, min: 0, max: 5 })
53 expect(() => checkConfigValue('n', number, 'x')).toThrow('a number')
54 expect(() => checkConfigValue('n', number, Number.NaN)).toThrow('a number')
55 expect(() => checkConfigValue('n', number, -1)).toThrow('>= 0')
56 expect(() => checkConfigValue('n', number, 6)).toThrow('<= 5')
57 expect(checkConfigValue('n', configOption.number({ default: 1 }), 99)).toBe(
58 99,
59 )
60 expect(() =>
61 checkConfigValue('b', configOption.boolean({ default: false }), 'yes'),
62 ).toThrow('true or false')
63 expect(() =>
64 checkConfigValue('t', configOption.text({ default: '' }), 1),
65 ).toThrow('expects text')
66 expect(() => configOption.select({ options: ['a'], default: 'b' })).toThrow(
67 'is not an option',
68 )
69 })
70​
71 it('rejects unknown keys and bad values, and loads saved values in a new session', async () => {
72 const persistence = memoryPersistence()
73 await appendToLog(persistence.stores.log, { threadId: 't' }, [
74 { type: 'harness.config', key: 'verbose', value: 'not a boolean' },
75 { type: 'harness.config', key: 'gone', value: 'old key' },
76 { type: 'harness.config', key: 'retries', value: 3 },
77 ])
78 const { adapter } = mockAdapter([])
79 const host = createHarnessHost({ persistence })
80 const harness = defineHarness({
81 name: 'test/config',
82 adapter,
83 plugins: () => [settings],
84 })
85 const session = await host.open(harness, { threadId: 't' })
86 // An invalid or unknown saved value falls back to the default.
87 expect(session.pluginSettings().verbose?.value).toBe(false)
88 expect(session.pluginSettings().retries?.value).toBe(3)
89 expect(session.pluginSettings()).not.toHaveProperty('gone')
90 expect(
91 await session.setPluginSetting({ key: 'missing', value: 1 }),
92 ).toMatchObject({
93 status: 'rejected',
94 reason: 'unknown_config',
95 })
96 expect(
97 await session.setPluginSetting({ key: 'retries', value: 9 }),
98 ).toMatchObject({
99 status: 'rejected',
100 reason: expect.stringContaining('<= 5'),
101 })
102 expect(
103 (await session.setPluginSetting({ key: 'level', value: 'high' })).status,
104 ).toBe('accepted')
105 expect(
106 (await session.setPluginSetting({ key: 'label', value: 'mine' })).status,
107 ).toBe('accepted')
108 await host.close()
109​
110 const again = createHarnessHost({ persistence })
111 const reopened = await again.open(harness, { threadId: 't' })
112 expect(reopened.pluginSettings()).toMatchObject({
113 level: { value: 'high', owner: 'test/settings' },
114 label: { value: 'mine' },
115 retries: { value: 3 },
116 })
117 await again.close()
118 })
119})
120​
121describe('commands', () => {
122 it('lists commands with input schemas and reports failures', async () => {
123 const release = gate()
124 const tools = definePlugin({
125 name: 'test/commands',
126 setup: () => ({
127 commands: {
128 greet: defineCommand({
129 description: 'Greet someone',
130 input: z.object({ name: z.string() }),
131 run: (input) => `hello ${input.name}`,
132 }),
133 boom: defineCommand({
134 description: 'Throws',
135 run: () => {
136 throw new Error('command broke')
137 },
138 }),
139 wait: defineCommand({
140 description: 'Waits until stopped',
141 run: (_input, ctx) =>
142 new Promise((_resolve, reject) => {
143 ctx.signal.addEventListener('abort', () =>
144 reject(new Error('stopped')),
145 )
146 release.open()
147 }),
148 }),
149 },
150 }),
151 })
152 const host = createHarnessHost({ persistence: memoryPersistence() })
153 const session = await host.open(
154 defineHarness({
155 name: 'test/cmds',
156 adapter: mockAdapter([]).adapter,
157 plugins: () => [tools],
158 }),
159 {
160 threadId: 't',
161 },
162 )
163 const listed = session.commands()
164 expect(listed.find((command) => command.name === 'greet')).toMatchObject({
165 owner: 'test/commands',
166 input: { type: 'object' },
167 })
168 expect(
169 listed.find((command) => command.name === 'boom')?.input,
170 ).toBeUndefined()
171​
172 expect(
173 await session.runCommand({ name: 'greet', input: { name: 'Ada' } }),
174 ).toBe('hello Ada')
175 await expect(
176 session.runCommand({ name: 'greet', input: { name: 1 } }),
177 ).rejects.toThrow('Input validation failed for command greet')
178 await expect(session.runCommand({ name: 'nope' })).rejects.toThrow(
179 'Unknown command: nope',
180 )
181 await expect(session.runCommand({ name: 'boom' })).rejects.toThrow(
182 'command broke',
183 )
184​
185 const waiting = session.runCommand({ name: 'wait' })
186 await release.opened
187 await waiting.cancel()
188 await waiting.then(
189 () => undefined,
190 () => undefined,
191 )
192 expect(waiting.status()).toBe('cancelled')
193 await host.close()
194 })
195​
196 it('gives a command without a schema the input as sent, typed unknown', async () => {
197 // Defined on their own, with no contextual type from a plugin's `setup`.
198 const peek = defineCommand({
199 description: 'Reads a field without a check',
200 // @ts-expect-error Without a schema, narrow the input before use.
201 run: (input) => input.foo,
202 })
203 const shout = defineCommand({
204 description: 'Shouts the text it gets',
205 run: (input) =>
206 typeof input === 'string' ? input.toUpperCase() : 'no text',
207 })
208 const raw = definePlugin({
209 name: 'test/raw-commands',
210 setup: () => ({ commands: { peek, shout } }),
211 })
212 const host = createHarnessHost({ persistence: memoryPersistence() })
213 const session = await host.open(
214 defineHarness({
215 name: 'test/raw-cmds',
216 adapter: mockAdapter([]).adapter,
217 plugins: () => [raw],
218 }),
219 {
220 threadId: 't',
221 },
222 )
223​
224 expect(
225 await session.runCommand({ name: 'peek', input: { foo: 'bar' } }),
226 ).toBe('bar')
227 expect(await session.runCommand({ name: 'shout', input: 'hi' })).toBe('HI')
228 expect(
229 await session.runCommand({ name: 'shout', input: { text: 'hi' } }),
230 ).toBe('no text')
231 await host.close()
232 })
233})
234​
235describe('questions', () => {
236 it('asks with a schema, checks answers, and rejects open questions on close', async () => {
237 const asker = definePlugin({
238 name: 'test/asker',
239 setup: () => ({
240 commands: {
241 pick: defineCommand({
242 description: 'Pick a number',
243 run: async (_input, { step }) => {
244 const answer = await step.ask({
245 name: 'count',
246 message: 'How many?',
247 schema: z.object({ count: z.number() }),
248 })
249 return answer.count * 2
250 },
251 }),
252 open: defineCommand({
253 description: 'Asks and never gets an answer',
254 run: (_input, { step }) =>
255 step.ask({ name: 'there', message: 'Still there?' }),
256 }),
257 },
258 }),
259 })
260 const host = createHarnessHost({ persistence: memoryPersistence() })
261 const session = await host.open(
262 defineHarness({
263 name: 'test/questions',
264 adapter: mockAdapter([]).adapter,
265 plugins: () => [asker],
266 }),
267 {
268 threadId: 't',
269 },
270 )
271 const picking = session.runCommand({ name: 'pick' })
272 await waitFor(() => expect(questionsOf(session.snapshot())).toHaveLength(1))
273 const [question] = questionsOf(session.snapshot())
274 expect(question).toMatchObject({
275 message: 'How many?',
276 schema: { type: 'object' },
277 })
278 expect(
279 await session.answer({ questionId: 'q-unknown', value: 1 }),
280 ).toMatchObject({
281 status: 'rejected',
282 reason: 'unknown_question',
283 })
284 expect(
285 await session.answer({
286 questionId: question?.questionId ?? '',
287 value: { count: 'two' },
288 }),
289 ).toMatchObject({
290 status: 'rejected',
291 reason: expect.stringContaining('Invalid answer'),
292 })
293 expect(
294 (
295 await session.answer({
296 questionId: question?.questionId ?? '',
297 value: { count: 2 },
298 })
299 ).status,
300 ).toBe('accepted')
301 expect(await picking).toBe(4)
302​
303 const open = session.runCommand({ name: 'open' })
304 await waitFor(() => expect(questionsOf(session.snapshot())).toHaveLength(1))
305 await host.close()
306 // The close cancels the command that waits for its answer.
307 await expect(open).rejects.toBeDefined()
308 expect(open.status()).toBe('cancelled')
309 expect(questionsOf(session.snapshot())).toEqual([])
310 })
311​
312 it('rejects the questions of a turn when the turn is cancelled', async () => {
313 let asked: Promise<unknown> | undefined
314 const asker = definePlugin({
315 name: 'test/turn-asker',
316 setup: () => ({
317 tools: [
318 durableTool(
319 toolDefinition({ name: 'confirm', description: 'Ask' }),
320 async (_args, { step }) => {
321 asked = step.ask({ name: 'sure', message: 'Sure?' })
322 return asked
323 },
324 ),
325 ],
326 }),
327 })
328 const host = createHarnessHost({ persistence: memoryPersistence() })
329 const session = await host.open(
330 defineHarness({
331 name: 'test/turn-questions',
332 adapter: mockAdapter([() => toolCall('confirm', {})]).adapter,
333 plugins: () => [asker],
334 }),
335 {
336 threadId: 't',
337 },
338 )
339 const turn = session.send('Go.')
340 await waitFor(() => expect(questionsOf(session.snapshot())).toHaveLength(1))
341​
342 await session.cancel({ operationId: turn.id })
343​
344 await expect(asked).rejects.toThrow('Cancelled.')
345 expect(questionsOf(session.snapshot())).toEqual([])
346 await host.close()
347 })
348​
349 it('rejects the question of a command when the command is cancelled', async () => {
350 let asked: Promise<unknown> | undefined
351 const asker = definePlugin({
352 name: 'test/command-asker',
353 setup: () => ({
354 commands: {
355 confirm: defineCommand({
356 description: 'Ask',
357 run: (_input, { step }) => {
358 asked = step.ask({ name: 'sure', message: 'Sure?' })
359 return asked
360 },
361 }),
362 },
363 }),
364 })
365 const host = createHarnessHost({ persistence: memoryPersistence() })
366 const session = await host.open(
367 defineHarness({
368 name: 'test/command-questions',
369 adapter: mockAdapter([]).adapter,
370 plugins: () => [asker],
371 }),
372 {
373 threadId: 't',
374 },
375 )
376 const command = session.runCommand({ name: 'confirm' })
377 await waitFor(() => expect(questionsOf(session.snapshot())).toHaveLength(1))
378​
379 await session.cancel({ operationId: command.id })
380​
381 await expect(asked).rejects.toThrow('Cancelled.')
382 expect(questionsOf(session.snapshot())).toEqual([])
383 await host.close()
384 })
385})
386​
387describe('plugin state and events', () => {
388 const counter = createPluginEvent<number>('test/count')
389​
390 function statePlugin(onValue: (value: number) => void) {
391 return definePlugin({
392 name: 'test/state',
393 setup: (ctx) => {
394 const state = ctx.state({ count: 0 })
395 const stop = ctx.on(counter, () => {
396 throw new Error('a listener that throws is ignored')
397 })
398 ctx.on(counter, onValue)
399 return {
400 commands: {
401 bump: defineCommand({
402 description: 'Add one',
403 run: async () => {
404 const next = await state.update((value) => ({
405 count: value.count + 1,
406 }))
407 ctx.emit(counter, next.count)
408 stop()
409 return (await state.get()).count
410 },
411 }),
412 },
413 }
414 },
415 })
416 }
417​
418 it('keeps state in the log, with no metadata store', async () => {
419 const base = memoryPersistence()
420 const { metadata: _metadata, ...stores } = base.stores
421 const harness = defineHarness({
422 name: 'test/state-store',
423 adapter: mockAdapter([]).adapter,
424 plugins: () => [statePlugin(() => {})],
425 })
426 const host = createHarnessHost({ persistence: { stores } })
427 const session = await host.open(harness, { threadId: 't' })
428 expect(await session.runCommand({ name: 'bump' })).toBe(1)
429 expect(await session.runCommand({ name: 'bump' })).toBe(2)
430 await host.close()
431​
432 const again = createHarnessHost({ persistence: { stores } })
433 const reopened = await again.open(harness, { threadId: 't' })
434 expect(reopened.snapshot().plugins).toEqual({ 'test/state': { count: 2 } })
435 expect(await reopened.runCommand({ name: 'bump' })).toBe(3)
436 await again.close()
437 })
438​
439 it('refuses a metadata store with no compare-and-set at the start', () => {
440 const base = memoryPersistence()
441 const plain = {
442 get: (namespace: string, key: string) =>
443 base.stores.metadata.get(namespace, key),
444 set: (namespace: string, key: string, value: unknown) =>
445 base.stores.metadata.set(namespace, key, value),
446 delete: (namespace: string, key: string) =>
447 base.stores.metadata.delete(namespace, key),
448 }
449 expect(() =>
450 createHarnessHost({
451 persistence: { stores: { ...base.stores, metadata: plain } },
452 }),
453 ).toThrow('stores.metadata needs getVersioned and setIf')
454 })
455​
456 it('keeps both of two concurrent updates', async () => {
457 let state: PluginState<{ count: number }> | undefined
458 const host = createHarnessHost({ persistence: memoryPersistence() })
459 await host.open(
460 defineHarness({
461 name: 'test/state-race',
462 adapter: mockAdapter([]).adapter,
463 plugins: () => [
464 definePlugin({
465 name: 'test/race',
466 setup: (ctx) => {
467 state = ctx.state({ count: 0 })
468 },
469 }),
470 ],
471 }),
472 {
473 threadId: 't',
474 },
475 )
476 if (!state) throw new Error('The plugin did not set up.')
477 const bump = (value: { count: number }) => ({ count: value.count + 1 })
478​
479 await Promise.all([state.update(bump), state.update(bump)])
480​
481 expect(await state.get()).toEqual({ count: 2 })
482 await host.close()
483 })
484​
485 it('warns when an async listener rejects', async () => {
486 const host = createHarnessHost({ persistence: memoryPersistence() })
487 const session = await host.open(
488 defineHarness({
489 name: 'test/async-listener',
490 adapter: mockAdapter([]).adapter,
491 plugins: () => [
492 definePlugin({
493 name: 'test/async-listener',
494 setup: (ctx) => {
495 ctx.on(counter, async () => {
496 throw new Error('listener broke')
497 })
498 return {
499 commands: {
500 ping: defineCommand({
501 description: 'Emit',
502 run: () => ctx.emit(counter, 1),
503 }),
504 },
505 }
506 },
507 }),
508 ],
509 }),
510 {
511 threadId: 't',
512 },
513 )
514 const warnings: Array<unknown> = []
515 session.onEvent(EventType.CUSTOM, ({ event }) => {
516 if (event.name === 'harness.plugin.warning') warnings.push(event.value)
517 })
518​
519 await session.runCommand({ name: 'ping' })
520​
521 await waitFor(() =>
522 expect(warnings).toEqual([
523 { plugin: 'harness:events', message: 'listener broke' },
524 ]),
525 )
526 await host.close()
527 })
528​
529 it('loads the saved state of a plugin whose name is an Object key', async () => {
530 const persistence = memoryPersistence()
531 await appendToLog(persistence.stores.log, { threadId: 't' }, [
532 {
533 type: 'harness.plugin.state',
534 plugin: 'constructor',
535 delta: { path: [], value: { saved: true } },
536 },
537 ])
538 const host = createHarnessHost({ persistence })
539 const session = await host.open(
540 defineHarness({
541 name: 'test/state-names',
542 adapter: mockAdapter([]).adapter,
543 plugins: () => [
544 definePlugin({
545 name: 'constructor',
546 setup: (ctx) => {
547 ctx.state({ saved: false })
548 },
549 }),
550 ],
551 }),
552 {
553 threadId: 't',
554 },
555 )
556​
557 expect(session.snapshot().plugins).toEqual({
558 constructor: { saved: true },
559 })
560 await host.close()
561 })
562})
563​
564describe('the plugin session API and inspect', () => {
565 it('reads and replaces the transcript, prompts, and describes the session', async () => {
566 let api: any
567 const probe = definePlugin({
568 name: 'test/probe',
569 setup: (ctx) => {
570 api = ctx.session
571 return {
572 tools: [
573 toolDefinition({ name: 'ping', description: 'Ping' }).server(
574 async () => 'pong',
575 ),
576 ],
577 prompts: ['Be brief.'],
578 }
579 },
580 })
581 const { adapter, calls } = mockAdapter([
582 () => text('first'),
583 () => text('from the plugin prompt'),
584 ])
585 const host = createHarnessHost({ persistence: memoryPersistence() })
586 const session = await host.open(
587 defineHarness({
588 name: 'test/api',
589 adapter,
590 plugins: () => [probe, settings],
591 }),
592 {
593 threadId: 't',
594 user: { id: 'u1' },
595 },
596 )
597 expect(api.threadId).toBe('t')
598 expect(api.user).toEqual({ id: 'u1' })
599 await session.send('hello')
600 expect(
601 (await api.transcript()).map((m: { content: string }) => m.content),
602 ).toEqual(['hello', 'first'])
603 await api.replaceTranscript([{ role: 'user', content: 'replaced' }])
604 expect(await api.transcript()).toEqual([
605 { role: 'user', content: 'replaced' },
606 ])
607 api.send('queued by a plugin')
608 await waitFor(() => expect(calls).toHaveLength(2))
609 await waitFor(() => expect(api.snapshot().status).toBe('idle'))
610 expect(JSON.stringify(calls[1].messages)).toContain('replaced')
611​
612 const inspected = session.inspect()
613 expect(inspected.plugins.map((plugin) => plugin.name)).toEqual([
614 'test/probe',
615 'test/settings',
616 ])
617 expect(inspected.tools).toEqual(
618 expect.arrayContaining([expect.objectContaining({ name: 'ping' })]),
619 )
620 expect(inspected.config.map((entry) => entry.key)).toContain('retries')
621 await host.close()
622 })
623})
624​
625describe('first-party plugin edges', () => {
626 let dir: string
627 beforeAll(async () => {
628 dir = await mkdtemp(join(tmpdir(), 'harness-files-'))
629 await mkdir(join(dir, 'commands'))
630 await writeFile(
631 join(dir, 'commands', 'review.md'),
632 '---\ndescription: Review a file\n---\nReview $ARGUMENTS carefully.',
633 )
634 await writeFile(join(dir, 'commands', 'plain.md'), 'Say hi to $ARGUMENTS.')
635 await writeFile(join(dir, 'commands', 'skip.txt'), 'not a command')
636 await writeFile(join(dir, 'RULES.md'), 'Use tabs.')
637 await writeFile(join(dir, 'EMPTY.md'), ' ')
638 })
639 afterAll(async () => {
640 await rm(dir, { recursive: true, force: true })
641 })
642​
643 it('turns markdown files into commands and reads chosen instruction files', async () => {
644 const { adapter, calls } = mockAdapter([
645 () => text('a'),
646 () => text('b'),
647 () => text('c'),
648 ])
649 const host = createHarnessHost({ persistence: memoryPersistence() })
650 const session = await host.open(
651 defineHarness({
652 name: 'test/files',
653 adapter,
654 plugins: () => [
655 fileCommands({ dir: join(dir, 'commands') }),
656 projectInstructions({
657 root: dir,
658 files: ['RULES.md', 'EMPTY.md', 'NONE.md'],
659 }),
660 ],
661 }),
662 {
663 threadId: 't',
664 },
665 )
666 const described = session.commands()
667 expect(
668 described.map((command) => [command.name, command.description]).sort(),
669 ).toEqual([
670 ['plain', 'Run plain.md'],
671 ['review', 'Review a file'],
672 ])
673 expect(
674 await session.runCommand({ name: 'review', input: 'src/a.ts' }),
675 ).toBe('Sent /review.')
676 await waitFor(() => expect(calls).toHaveLength(1))
677 await waitFor(() => expect(session.snapshot().status).toBe('idle'))
678 await session.runCommand({ name: 'plain', input: { who: 'Ada' } })
679 await waitFor(() => expect(calls).toHaveLength(2))
680 await waitFor(() => expect(session.snapshot().status).toBe('idle'))
681 await session.runCommand({ name: 'plain' })
682 await waitFor(() => expect(calls).toHaveLength(3))
683​
684 // A missing folder gives no commands.
685 const empty = await host.open(
686 defineHarness({
687 name: 'test/files-missing',
688 adapter,
689 plugins: () => [fileCommands({ dir: join(dir, 'missing') })],
690 }),
691 {
692 threadId: 'empty',
693 },
694 )
695 expect(empty.commands()).toEqual([])
696​
697 const said = calls.map((call) => JSON.stringify(call.messages.at(-1)))
698 expect(said[0]).toContain('Review src/a.ts carefully.')
699 expect(said[1]).toContain('Say hi to {\\"who\\":\\"Ada\\"}.')
700 expect(said[2]).toContain('Say hi to .')
701 const prompts = JSON.stringify(calls[0].systemPrompts)
702 expect(prompts).toContain('Project instructions from RULES.md')
703 expect(prompts).not.toContain('EMPTY.md')
704 await host.close()
705 })
706​
707 it('checks todo input and shows an empty list', async () => {
708 const { adapter, calls } = mockAdapter([
709 () => toolCall('todo_write', { todos: [{ text: 'x', status: 'later' }] }),
710 () => text('bad input'),
711 () => toolCall('todo_write', { todos: [] }, 'call-2'),
712 () => text('cleared'),
713 ])
714 const host = createHarnessHost({ persistence: memoryPersistence() })
715 const session = await host.open(
716 defineHarness({
717 name: 'test/todos',
718 adapter,
719 plugins: () => [todos()],
720 }),
721 {
722 threadId: 't',
723 },
724 )
725 const before = session.snapshot().plugins
726 await session.send('plan')
727 // chat() checks the tool's JSON Schema before it runs, so an invalid
728 // status is a tool error the model sees, and the tool never runs.
729 expect(JSON.stringify(calls[1].messages)).toContain(
730 'Input validation failed for tool todo_write',
731 )
732 expect(session.snapshot().plugins).toEqual(before)
733 expect(await session.runCommand({ name: 'todos' })).toBe(
734 'The todo list is empty.',
735 )
736 await session.send('clear')
737 expect(JSON.stringify(calls[3].messages)).toContain(
738 'The todo list is empty.',
739 )
740 expect(await session.runCommand({ name: 'todos' })).toBe(
741 'The todo list is empty.',
742 )
743 await host.close()
744 })
745​
746 it('needs a model choice and answers every /model form', async () => {
747 expect(() => modelPicker({ choices: {} })).toThrow('at least one choice')
748 const fast = mockAdapter([]).adapter
749 const smart = mockAdapter([]).adapter
750 const host = createHarnessHost({ persistence: memoryPersistence() })
751 const session = await host.open(
752 defineHarness({
753 name: 'test/models',
754 adapter: smart,
755 plugins: () => [modelPicker({ choices: { smart, fast } })],
756 }),
757 {
758 threadId: 't',
759 },
760 )
761 expect(await session.runCommand({ name: 'model' })).toBe(
762 'Model: smart. Choices: smart, fast.',
763 )
764 expect(await session.runCommand({ name: 'model', input: 'slow' })).toBe(
765 'Unknown model "slow". Choices: smart, fast.',
766 )
767 expect(
768 await session.runCommand({ name: 'model', input: { name: 'fast' } }),
769 ).toBe('Model: fast. It applies at the next turn.')
770 await host.close()
771 })
772​
773 it('keeps the conversation when the summary is empty', async () => {
774 const summarizer = mockAdapter([() => text(' ')])
775 const host = createHarnessHost({ persistence: memoryPersistence() })
776 const session = await host.open(
777 defineHarness({
778 name: 'test/compact-empty',
779 adapter: mockAdapter([() => text('one'), () => text('two')]).adapter,
780 plugins: () => [compact({ adapter: summarizer.adapter })],
781 }),
782 {
783 threadId: 't',
784 },
785 )
786 await session.send('first')
787 await session.send('second')
788 await expect(session.runCommand({ name: 'compact' })).rejects.toThrow(
789 'The summary model returned no text.',
790 )
791 expect(await session.transcript()).toHaveLength(4)
792 await host.close()
793 })
794​
795 it('keeps short conversations, keeps the last messages, and counts usage', async () => {
796 const summarizer = mockAdapter([() => text('the summary')])
797 const withUsage = (content: string) =>
798 text(content).map((chunk) =>
799 chunk.type === EventType.RUN_FINISHED
800 ? {
801 ...chunk,
802 usage: { promptTokens: 3, completionTokens: 2, totalTokens: 5 },
803 }
804 : chunk,
805 )
806 const { adapter } = mockAdapter([
807 () => withUsage('one'),
808 () => withUsage('two'),
809 ])
810 const host = createHarnessHost({ persistence: memoryPersistence() })
811 const session = await host.open(
812 defineHarness({
813 name: 'test/compact',
814 adapter,
815 plugins: () => [
816 compact({ adapter: summarizer.adapter, keepLast: 1 }),
817 usage(),
818 ],
819 }),
820 {
821 threadId: 't',
822 },
823 )
824 expect(await session.runCommand({ name: 'compact' })).toBe(
825 'The conversation is already short.',
826 )
827 await session.send([{ type: 'text', content: 'first question' }] as never)
828 await session.send('second question')
829 expect(await session.runCommand({ name: 'compact' })).toBe(
830 'Compacted 3 messages into a summary.',
831 )
832 expect(JSON.stringify(summarizer.calls[0].messages)).toContain(
833 'first question',
834 )
835 expect(await session.runCommand({ name: 'usage' })).toBe(
836 '2 model calls, 6 input tokens, 4 output tokens, 10 total.',
837 )
838 await host.close()
839 })
840})
841​
842describe('session events', () => {
843 it('publishes config changes', async () => {
844 const host = createHarnessHost({ persistence: memoryPersistence() })
845 const session = await host.open(
846 defineHarness({
847 name: 'test/events',
848 adapter: mockAdapter([]).adapter,
849 plugins: () => [settings],
850 }),
851 {
852 threadId: 't',
853 },
854 )
855 const seen: Array<SessionEvent> = []
856 const controller = new AbortController()
857 const reading = (async () => {
858 for await (const entry of session.events({
859 from: '0',
860 signal: controller.signal,
861 }))
862 seen.push(entry)
863 })()
864 await session.setPluginSetting({ key: 'verbose', value: true })
865 await waitFor(() =>
866 expect(
867 seen.some(
868 (entry) =>
869 entry.event.type === EventType.CUSTOM &&
870 entry.event.value !== null &&
871 typeof entry.event.value === 'object' &&
872 'key' in entry.event.value &&
873 entry.event.value.key === 'verbose',
874 ),
875 ).toBe(true),
876 )
877 controller.abort()
878 await reading
879 await host.close()
880 })
881})
882​
883describe('the turns that a session plugin starts', () => {
884 it('run as the owner, or as the user that the plugin passes, not as the sender of the running turn', async () => {
885 let api: PluginSessionApi | undefined
886 const notes = definePlugin({
887 name: 'test/notes',
888 setup: (ctx) => {
889 api = ctx.session
890 },
891 })
892 const release = gate()
893 const { adapter, calls } = mockAdapter([
894 after(release.opened, 'Bea is done.'),
895 () => text('One.'),
896 () => text('Two.'),
897 () => text('Three.'),
898 ])
899 const persistence = memoryPersistence()
900 const host = createHarnessHost({ persistence })
901 const harness = defineHarness({
902 name: 'test/notes',
903 adapter,
904 plugins: () => [notes],
905 })
906 // Olga opens the thread first, so she owns it.
907 await host.open(harness, { threadId: 't', user: { id: 'olga' } })
908 const bea = await host.open(harness, {
909 threadId: 't',
910 user: { id: 'bea' },
911 })
912 const turn = bea.send('Start a job.')
913 await waitFor(() => expect(turn.status()).toBe('running'))
914 if (!api) throw new Error('No plugin context.')
915​
916 // A job of olga ends while the turn of bea runs.
917 await api.note('The job of olga ended.', { wake: true })
918 await api.note('The job of carl ended.', {
919 wake: true,
920 user: { id: 'carl' },
921 })
922 api.send('Go on, carl.', { user: { id: 'carl' } })
923 release.open()
924 await turn
925 await waitFor(() => expect(calls).toHaveLength(4))
926​
927 const state = await loadLogState({
928 store: persistence.stores.log,
929 logId: logIdOf({ logId: 't' }),
930 rootThread: 't',
931 })
932 const senders = [...sessionOf(state, 't').inputs.values()].map((logged) => [
933 logged.input.op,
934 logged.user?.id,
935 ])
936 expect(senders).toEqual([
937 ['prompt', 'bea'],
938 ['followUp', 'olga'],
939 ['followUp', 'carl'],
940 ['prompt', 'carl'],
941 ])
942 await host.close()
943 })
944})