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

session.test.ts

1,217 lines36.1 KB

1import { describe, expect, it, vi } from 'vitest'
2import { z } from 'zod'
3import {
4 EventType,
5 createCapability,
6 defineAgent,
7 toolDefinition,
8} from '@tanstack/ai'
9import { memoryLogStore, memoryPersistence } from '@tanstack/ai-persistence'
10import {
11 HARNESS_EVENTS,
12 createHarnessHost,
13 defineCommand,
14 defineHarness,
15 definePlugin,
16} from '../src'
17import {
18 after,
19 appendToLog,
20 gate,
21 hideSecret,
22 messageTexts,
23 mockAdapter,
24 text,
25 toolCall,
26 storedThreadState,
27 untilAborted,
28 wakeMessages,
29 wrapLogStore,
30} from './helpers'
31import { isRecord } from '../src/utils'
32import type { AnyChatMiddleware, ContentPart, StreamChunk } from '@tanstack/ai'
33import type { LogRecord } from '@tanstack/ai-persistence'
34import type {
35 HarnessPersistence,
36 HarnessTurnOptions,
37 Receipt,
38 SessionEvent,
39} from '../src'
40import type { Reply } from './helpers'
41​
42// Coverage runs in CI are slow, so polled checks wait up to 5 s.
43const waitFor = <T>(
44 check: () => T | Promise<T>,
45 options?: { timeout?: number; interval?: number },
46) => vi.waitFor(check, { timeout: 5_000, ...options })
47​
48/** A memory host. A session closes as soon as its last handle closes and it is idle. */
49function setup() {
50 const persistence = memoryPersistence()
51 const host = createHarnessHost({
52 persistence,
53 lifecycle: { closeIdleSessionsAfterMs: 0 },
54 })
55 return { persistence, host }
57​
58function customNames(events: Array<SessionEvent>): Array<string> {
59 return events
60 .map((entry) => entry.event)
61 .filter(
62 (event): event is Extract<StreamChunk, { type: 'CUSTOM' }> =>
63 event.type === EventType.CUSTOM,
64 )
65 .map((event) => event.name)
67​
68async function collect(
69 iterable: AsyncIterable<SessionEvent>,
70): Promise<Array<SessionEvent>> {
71 const out: Array<SessionEvent> = []
72 for await (const entry of iterable) out.push(entry)
73 return out
75​
76describe('chat turns', () => {
77 it('runs a prompt, returns its text, and saves the transcript', async () => {
78 const { host } = setup()
79 const { adapter } = mockAdapter([() => text('Hello there')])
80 const harness = defineHarness({ name: 'test/chat', adapter })
81 const session = await host.open(harness, { threadId: 't1' })
82​
83 const turn = session.send('Hi')
84 await expect(turn).resolves.toEqual({ text: 'Hello there', media: [] })
85 expect(turn.status()).toBe('completed')
86​
87 const saved = await session.transcript()
88 expect(saved.map((message) => message.role)).toEqual(['user', 'assistant'])
89 const names = customNames(await collect(turn.events({ from: '0' })))
90 expect(names).toContain(HARNESS_EVENTS.inputApplied)
91 expect(names).toContain(HARNESS_EVENTS.operationStarted)
92 expect(names.at(-1)).toBe(HARNESS_EVENTS.operationFinished)
93 await host.close()
94 })
95​
96 it('queues a second prompt and gives it the first turn as history', async () => {
97 const { host } = setup()
98 const first = gate()
99 const { adapter, calls } = mockAdapter([
100 after(first.opened, 'one'),
101 () => text('two'),
102 ])
103 const session = await host.open(
104 defineHarness({ name: 'test/queue', adapter }),
105 {
106 threadId: 't1',
107 },
108 )
109​
110 const a = session.send('first')
111 const b = session.send('second')
112 await waitFor(() => expect(calls).toHaveLength(1))
113 expect(session.snapshot().queuedTurns).toBe(1)
114 first.open()
115​
116 await expect(a).resolves.toEqual({ text: 'one', media: [] })
117 await expect(b).resolves.toEqual({ text: 'two', media: [] })
118 expect(messageTexts(calls[1])).toEqual(['first', 'one', 'second'])
119 await host.close()
120 })
121​
122 it('rejects a prompt with busy: reject while a turn runs', async () => {
123 const { host } = setup()
124 const first = gate()
125 const { adapter, calls } = mockAdapter([after(first.opened, 'one')])
126 const session = await host.open(
127 defineHarness({ name: 'test/reject', adapter }),
128 {
129 threadId: 't1',
130 },
131 )
132​
133 const a = session.send('first')
134 await waitFor(() => expect(calls).toHaveLength(1))
135 await expect(session.send('second', { busy: 'reject' })).rejects.toThrow(
136 'already running',
137 )
138 first.open()
139 await a
140 await host.close()
141 })
142​
143 it('adds a steer message before the next model call of the running turn', async () => {
144 const { host } = setup()
145 const toolStarted = gate()
146 const releaseTool = gate()
147 const lookup = toolDefinition({
148 name: 'lookup',
149 description: 'Look something up',
150 inputSchema: z.object({ q: z.string() }),
151 }).server(async () => {
152 toolStarted.open()
153 await releaseTool.opened
154 return { found: true }
155 })
156 const { adapter, calls } = mockAdapter([
157 () => toolCall('lookup', { q: 'x' }),
158 () => text('done'),
159 ])
160 const session = await host.open(
161 defineHarness({ name: 'test/steer', adapter, tools: [lookup] }),
162 {
163 threadId: 't1',
164 },
165 )
166​
167 const turn = session.send('find x')
168 await toolStarted.opened
169 const receipt = await session.send('also check y', { mode: 'steer' })
170 .receipt
171 expect(receipt).toMatchObject({ status: 'accepted', operationId: turn.id })
172 releaseTool.open()
173​
174 await expect(turn).resolves.toEqual({ text: 'done', media: [] })
175 expect(calls).toHaveLength(2)
176 expect(messageTexts(calls[1]).at(-1)).toBe('also check y')
177 await host.close()
178 })
179​
180 it('answers a steer that arrived after the last model call in the same turn', async () => {
181 const { host } = setup()
182 const first = gate()
183 const { adapter, calls } = mockAdapter([
184 after(first.opened, 'one'),
185 () => text('two'),
186 ])
187 const session = await host.open(
188 defineHarness({ name: 'test/late', adapter }),
189 {
190 threadId: 't1',
191 },
192 )
193​
194 const a = session.send('first')
195 await waitFor(() => expect(calls).toHaveLength(1))
196 const joined = session.send('and this', { busy: 'steer' })
197 first.open()
198​
199 // One turn answers both messages: the joined prompt settles with it.
200 await expect(a).resolves.toEqual({ text: 'onetwo', media: [] })
201 await expect(joined).resolves.toEqual({ text: 'onetwo', media: [] })
202 expect(messageTexts(calls[1]).at(-1)).toBe('and this')
203 expect(
204 await session.settled({ inputId: (await joined.receipt).inputId }),
205 ).toEqual({
206 inputId: (await joined.receipt).inputId,
207 outcome: 'completed',
208 operationId: a.id,
209 })
210 await host.close()
211 })
212​
213 it('cancels the running turn', async () => {
214 const { host } = setup()
215 const { adapter, calls } = mockAdapter([untilAborted()])
216 const session = await host.open(
217 defineHarness({ name: 'test/cancel', adapter }),
218 {
219 threadId: 't1',
220 },
221 )
222​
223 const turn = session.send('go')
224 await waitFor(() => expect(calls).toHaveLength(1))
225 const receipt = await turn.cancel()
226 expect(receipt.status).toBe('accepted')
227 await expect(turn).rejects.toThrow('Cancelled')
228 expect(turn.status()).toBe('cancelled')
229 expect(session.snapshot().status).toBe('idle')
230 await host.close()
231 })
232​
233 it('keeps the text that a cancelled turn streamed in the transcript', async () => {
234 const { host } = setup()
235 const streamed = gate()
236 const { adapter, calls } = mockAdapter([
237 (options: any) =>
238 (async function* (): AsyncGenerator<StreamChunk> {
239 // RUN_STARTED, TEXT_MESSAGE_START, TEXT_MESSAGE_CONTENT.
240 yield* text('Here').slice(0, 3)
241 streamed.open()
242 const signal: AbortSignal = options.abortController.signal
243 await new Promise((resolve) =>
244 signal.addEventListener('abort', resolve, { once: true }),
245 )
246 })(),
247 () => text('Again.'),
248 ])
249 const session = await host.open(
250 defineHarness({ name: 'test/cancel', adapter }),
251 { threadId: 't1' },
252 )
253​
254 const turn = session.send('first')
255 await streamed.opened
256 await turn.cancel()
257 await expect(turn).rejects.toThrow('Cancelled')
258 await session.send('second')
259​
260 const pairs = (
261 messages: ReadonlyArray<{ role: string; content: unknown }>,
262 ) => messages.map((message) => [message.role, message.content])
263 // The next model call never gets two user messages in a row.
264 expect(pairs(calls[1].messages)).toEqual([
265 ['user', 'first'],
266 ['assistant', 'Here'],
267 ['user', 'second'],
268 ])
269 expect(pairs(await session.transcript())).toEqual([
270 ['user', 'first'],
271 ['assistant', 'Here'],
272 ['user', 'second'],
273 ['assistant', 'Again.'],
274 ])
275 await host.close()
276 })
277​
278 it('ends a cancelled turn with its text message and its run', async () => {
279 const { host } = setup()
280 const streamed = gate()
281 const { adapter } = mockAdapter([
282 (options: any) =>
283 (async function* (): AsyncGenerator<StreamChunk> {
284 // RUN_STARTED, TEXT_MESSAGE_START, TEXT_MESSAGE_CONTENT.
285 yield* text('Here').slice(0, 3)
286 streamed.open()
287 const signal: AbortSignal = options.abortController.signal
288 await new Promise((resolve) =>
289 signal.addEventListener('abort', resolve, { once: true }),
290 )
291 })(),
292 ])
293 const session = await host.open(
294 defineHarness({ name: 'test/cancel', adapter }),
295 { threadId: 't1' },
296 )
297​
298 const turn = session.send('first')
299 await streamed.opened
300 await turn.cancel()
301 await expect(turn).rejects.toThrow('Cancelled')
302​
303 const events = (await collect(turn.events({ from: '0' }))).map(
304 ({ event }) => event,
305 )
306 const types = events.map((event) =>
307 event.type === EventType.CUSTOM ? event.name : event.type,
308 )
309 expect(types.slice(-5)).toEqual([
310 EventType.TEXT_MESSAGE_CONTENT,
311 EventType.TEXT_MESSAGE_END,
312 EventType.RUN_FINISHED,
313 HARNESS_EVENTS.inputSettled,
314 HARNESS_EVENTS.operationFinished,
315 ])
316 expect(events.at(-3)).toMatchObject({
317 type: EventType.RUN_FINISHED,
318 runId: turn.id,
319 outcome: { type: 'cancelled' },
320 })
321 await host.close()
322 })
323​
324 it('stops for an approval and continues after resolve', async () => {
325 const { host } = setup()
326 const execute = vi.fn(async () => ({ ok: true }))
327 const remove = toolDefinition({
328 name: 'remove',
329 description: 'Remove a file',
330 needsApproval: true,
331 inputSchema: z.object({ path: z.string() }),
332 }).server(execute)
333 const { adapter } = mockAdapter([
334 () => toolCall('remove', { path: 'a.txt' }, 'call_1'),
335 () => text('removed'),
336 ])
337 const session = await host.open(
338 defineHarness({
339 name: 'test/approve',
340 adapter,
341 tools: [remove],
342 }),
343 {
344 threadId: 't1',
345 },
346 )
347​
348 const turn = await session.send('remove a.txt')
349 expect(turn.interrupts).toHaveLength(1)
350 expect(session.snapshot().status).toBe('requires_action')
351​
352 const receipt = await session.resolve({
353 resume: [
354 {
355 interruptId: turn.interrupts![0]!.id,
356 status: 'resolved',
357 payload: true,
358 },
359 ],
360 })
361 expect(receipt.status).toBe('accepted')
362 await waitFor(() => expect(session.snapshot().status).toBe('idle'))
363 expect(execute).toHaveBeenCalledWith({ path: 'a.txt' }, expect.anything())
364 await host.close()
365 })
366​
367 it('rejects resolve when nothing is waiting', async () => {
368 const { host } = setup()
369 const { adapter } = mockAdapter([() => text('hi')])
370 const session = await host.open(
371 defineHarness({ name: 'test/noresolve', adapter }),
372 {
373 threadId: 't1',
374 },
375 )
376 const receipt = await session.resolve({
377 resume: [{ interruptId: 'x', status: 'resolved', payload: true }],
378 })
379 expect(receipt).toMatchObject({
380 status: 'rejected',
381 reason: 'no_pending_interrupts',
382 })
383 await host.close()
384 })
385})
386​
387describe('settled operations', () => {
388 it('keeps the last 500 settled operations, and drops older ones', async () => {
389 const { host } = setup()
390 const session = await host.open(
391 defineHarness({
392 name: 'test/window',
393 adapter: mockAdapter([]).adapter,
394 }),
395 {
396 threadId: 't1',
397 },
398 )
399 const ids: Array<string> = []
400 for (let index = 0; index < 501; index += 1) {
401 const command = session.runCommand({ name: 'unknown' })
402 ids.push(command.id)
403 await command.then(
404 () => undefined,
405 () => undefined,
406 )
407 }
408 await waitFor(() => expect(session.operation(ids[0] ?? '')).toBe(undefined))
409 expect(session.operation(ids[1] ?? '')).toBeDefined()
410 expect(session.operation(ids[500] ?? '')).toBeDefined()
411 await host.close()
412 })
413})
414​
415describe('events', () => {
416 it('replays events after a cursor', async () => {
417 const { host } = setup()
418 const { adapter } = mockAdapter([() => text('one'), () => text('two')])
419 const session = await host.open(
420 defineHarness({ name: 'test/events', adapter }),
421 {
422 threadId: 't1',
423 },
424 )
425 await session.send('a')
426 const cursor = session.snapshot().cursor
427 const second = session.send('b')
428 await second
429​
430 const controller = new AbortController()
431 const seen: Array<SessionEvent> = []
432 for await (const entry of session.events({
433 from: cursor,
434 signal: controller.signal,
435 })) {
436 seen.push(entry)
437 // The finished event of the first turn can land after its cursor.
438 const isSecondDone =
439 entry.operationId === second.id &&
440 entry.event.type === EventType.CUSTOM &&
441 entry.event.name === HARNESS_EVENTS.operationFinished
442 if (isSecondDone) controller.abort()
443 }
444 expect(seen.every((entry) => Number(entry.cursor) > Number(cursor))).toBe(
445 true,
446 )
447 expect(seen.some((entry) => entry.operationId === second.id)).toBe(true)
448 await host.close()
449 })
450})
451​
452describe('agents', () => {
453 const pricer = defineAgent({
454 name: 'pricer',
455 description: 'Prices a vendor',
456 inputSchema: z.object({ vendor: z.string() }),
457 run: async (ctx) => ({ vendor: ctx.input.vendor, cents: 1200 }),
458 })
459​
460 it('runs a typed agent from code and notes the result in the transcript', async () => {
461 const { host, persistence } = setup()
462 const { adapter, calls } = mockAdapter([() => text('noted')])
463 const session = await host.open(
464 defineHarness({
465 name: 'test/agents',
466 adapter,
467 agents: [pricer],
468 }),
469 {
470 threadId: 't1',
471 },
472 )
473​
474 const run = session.agents.pricer.run({ vendor: 'acme' })
475 const result = await run
476 expect(result).toEqual({ vendor: 'acme', cents: 1200 })
477 expect(run.kind).toBe('agent')
478​
479 const { runs } = await storedThreadState(persistence.stores.log, {
480 threadId: 't1',
481 })
482 expect(runs.get(run.id)).toMatchObject({
483 kind: 'agent',
484 agent: 'pricer',
485 status: 'completed',
486 })
487​
488 await session.send('what did it cost?')
489 expect(
490 messageTexts(calls[0]).some((line) => line.includes('[pricer finished]')),
491 ).toBe(true)
492 await host.close()
493 })
494​
495 it('rejects input that fails the schema', async () => {
496 const { host } = setup()
497 const { adapter } = mockAdapter([])
498 const session = await host.open(
499 defineHarness({
500 name: 'test/agents-bad',
501 adapter,
502 agents: [pricer],
503 }),
504 {
505 threadId: 't1',
506 },
507 )
508 await expect(
509 session.agents.pricer.run({ vendor: 1 } as never),
510 ).rejects.toThrow('Input validation failed for agent pricer')
511 await host.close()
512 })
513​
514 it('starts a background agent that wakes the session when done', async () => {
515 const { host } = setup()
516 const { adapter, calls } = mockAdapter([() => text('thanks')])
517 const session = await host.open(
518 defineHarness({ name: 'test/wake', adapter, agents: [pricer] }),
519 {
520 threadId: 't1',
521 },
522 )
523​
524 await session.agents.pricer.start(
525 { vendor: 'acme' },
526 { startTurnWhenDone: true },
527 )
528 await waitFor(() => expect(calls).toHaveLength(1))
529 expect(messageTexts(calls[0]).at(-1)).toContain(
530 'Background agent pricer finished',
531 )
532 await waitFor(() => expect(session.snapshot().status).toBe('idle'))
533 const transcript = await session.transcript()
534 expect(wakeMessages(transcript)).toEqual([
535 expect.stringContaining('Background agent pricer finished'),
536 ])
537 await host.close()
538 })
539​
540 it('notes a failed background agent and wakes the session', async () => {
541 const failing = defineAgent({
542 name: 'failing',
543 description: 'Fails',
544 run: async () => {
545 throw new Error('no vendor')
546 },
547 })
548 const { host } = setup()
549 const { adapter, calls } = mockAdapter([() => text('sorry')])
550 const session = await host.open(
551 defineHarness({
552 name: 'test/wake-failed',
553 adapter,
554 agents: [failing],
555 }),
556 {
557 threadId: 't1',
558 },
559 )
560​
561 await expect(
562 session.agents.failing.start(undefined, { startTurnWhenDone: true }),
563 ).rejects.toThrow('no vendor')
564 await waitFor(() => expect(calls).toHaveLength(1))
565 expect(messageTexts(calls[0]).slice(-2)).toEqual([
566 '[failing failed] no vendor',
567 'Background agent failing failed: [failing failed] no vendor',
568 ])
569 await waitFor(() => expect(session.snapshot().status).toBe('idle'))
570 await host.close()
571 })
572})
573​
574describe('inputs', () => {
575 it('refuses inputs that come while the host closes, and stops the running turn', async () => {
576 const { host } = setup()
577 const { adapter } = mockAdapter([untilAborted()])
578 const session = await host.open(
579 defineHarness({ name: 'test/closing', adapter }),
580 {
581 threadId: 't1',
582 },
583 )
584 const running = session.send('First.')
585 await running.receipt
586​
587 const closed = host.close()
588 expect(() => session.send('Late.')).toThrow('The host is closed.')
589 expect(() => session.send('Later.', { mode: 'followUp' })).toThrow(
590 'The host is closed.',
591 )
592 await expect(running).rejects.toThrow()
593 await closed
594 })
595​
596 it('settles a turn as failed when it fails before it runs', async () => {
597 const { persistence, host } = setup()
598 const session = await host.open(
599 defineHarness({
600 name: 'test/early-fail',
601 adapter: mockAdapter([]).adapter,
602 }),
603 {
604 threadId: 't1',
605 },
606 )
607 // Another host wrote an interrupt whose descriptor does not match it.
608 await appendToLog(persistence.stores.log, { threadId: 't1' }, [
609 {
610 type: 'harness.interrupt',
611 interrupt: {
612 interruptId: 'i-1',
613 runId: 'r-1',
614 threadId: 't1',
615 requestedAt: 1,
616 payload: { id: 'i-2', toolCallId: 'c-1', reason: 'r', message: 'm' },
617 },
618 },
619 ])
620​
621 const turn = session.send('Go.', { inputId: 'in-early' })
622 const invalid = 'The stored interrupt descriptor is invalid.'
623 await expect(turn).rejects.toThrow(invalid)
624 expect(await session.settled({ inputId: 'in-early' })).toMatchObject({
625 outcome: 'failed',
626 error: { message: invalid },
627 })
628 const events: Array<StreamChunk> = []
629 for await (const chunk of turn.stream()) events.push(chunk)
630 expect(events.some((chunk) => chunk.type === EventType.RUN_ERROR)).toBe(
631 true,
632 )
633 await host.close()
634 })
635})
636​
637describe('plugins', () => {
638 it('fails a turn whose turn plugin adds a command', async () => {
639 const { host } = setup()
640 const session = await host.open(
641 defineHarness({
642 name: 'test/turn-commands',
643 adapter: mockAdapter([() => text('never')]).adapter,
644 plugins: () => [
645 definePlugin({
646 name: 'test/turn-command',
647 lifetime: 'turn',
648 setup: () => ({
649 commands: {
650 hello: defineCommand({ description: 'Hi', run: () => 'hi' }),
651 },
652 }),
653 }),
654 ],
655 }),
656 {
657 threadId: 't1',
658 },
659 )
660​
661 await expect(session.send('Go.')).rejects.toThrow(
662 "lifetime 'turn' cannot add commands or config",
663 )
664 await host.close()
665 })
666​
667 it('keeps session plugins across turns and sets up turn plugins per turn', async () => {
668 const { host } = setup()
669 const log: Array<string> = []
670 const sessionPlugin = definePlugin({
671 name: 'test/session',
672 setup: async ({ resources }) => {
673 await resources.acquire(
674 () => log.push('session:open'),
675 () => log.push('session:close'),
676 )
677 return { prompts: ['Session prompt.'] }
678 },
679 })
680 const runPlugin = definePlugin({
681 name: 'test/run',
682 lifetime: 'turn',
683 setup: async ({ resources }) => {
684 await resources.acquire(
685 () => log.push('run:open'),
686 () => log.push('run:close'),
687 )
688 },
689 })
690 const { adapter, calls } = mockAdapter([() => text('a'), () => text('b')])
691 const session = await host.open(
692 defineHarness({
693 name: 'test/plugins',
694 adapter,
695 plugins: () => [sessionPlugin, runPlugin],
696 }),
697 {
698 threadId: 't1',
699 },
700 )
701​
702 await session.send('one')
703 await session.send('two')
704 await session.close()
705​
706 expect(log).toEqual([
707 'session:open',
708 'run:open',
709 'run:close',
710 'run:open',
711 'run:close',
712 'session:close',
713 ])
714 expect(JSON.stringify(calls[0].systemPrompts)).toContain('Session prompt.')
715 })
716​
717 it('runs a harness without an adapter on the model a plugin picks', async () => {
718 const { host } = setup()
719 const { adapter, calls } = mockAdapter([() => text('picked')])
720 const picker = definePlugin({
721 name: 'test/picker',
722 setup: () => ({ adapter: () => adapter }),
723 })
724 const session = await host.open(
725 defineHarness({
726 name: 'test/no-adapter',
727 plugins: () => [picker],
728 }),
729 {
730 threadId: 't1',
731 },
732 )
733​
734 expect((await session.send('hi')).text).toBe('picked')
735 expect(calls).toHaveLength(1)
736 await host.close()
737 })
738​
739 it('fails the turn when nothing gives it a model', async () => {
740 const { host } = setup()
741 const session = await host.open(defineHarness({ name: 'test/no-model' }), {
742 threadId: 't1',
743 })
744​
745 const turn = session.send('hi', { inputId: 'in-1' })
746 const chunks: Array<StreamChunk> = []
747 for await (const chunk of turn.stream()) chunks.push(chunk)
748​
749 const message =
750 'This turn has no model. Set `adapter` in defineHarness, return one from a plugin `adapter()`, or pass `overrides.adapter` to the turn.'
751 await expect(turn).rejects.toThrow(message)
752 expect(chunks).toContainEqual(
753 expect.objectContaining({ type: EventType.RUN_ERROR, message }),
754 )
755 expect(await session.settled({ inputId: 'in-1' })).toMatchObject({
756 outcome: 'failed',
757 error: { message },
758 })
759 await host.close()
760 })
761​
762 it('gives plugin tools to the model and plugin capabilities to middleware', async () => {
763 const { host } = setup()
764 const clockCapability = createCapability<{ now: () => string }>()(
765 'test.clock',
766 )
767 const [getClock] = clockCapability
768 const seen: Array<string> = []
769 const clockPlugin = definePlugin({
770 name: 'test/clock',
771 provides: [clockCapability],
772 setup: ({ provide }) => {
773 provide(clockCapability, { now: () => 'noon' })
774 return {
775 tools: [
776 toolDefinition({
777 name: 'clock',
778 description: 'Tell the time',
779 }).server(async () => 'noon'),
780 ],
781 middleware: [
782 {
783 name: 'test/read-clock',
784 requires: [clockCapability],
785 onStart: (ctx) => {
786 seen.push(getClock(ctx).now())
787 },
788 },
789 ],
790 }
791 },
792 })
793 const { adapter, calls } = mockAdapter([() => text('ok')])
794 const session = await host.open(
795 defineHarness({
796 name: 'test/tools',
797 adapter,
798 plugins: () => [clockPlugin],
799 }),
800 {
801 threadId: 't1',
802 },
803 )
804​
805 await session.send('time?')
806 expect(calls[0].tools.map((tool: { name: string }) => tool.name)).toContain(
807 'clock',
808 )
809 expect(seen).toEqual(['noon'])
810 await host.close()
811 })
812​
813 it('fails open when two plugins add the same tool', async () => {
814 const { host } = setup()
815 const tool = toolDefinition({ name: 'dup', description: 'x' }).server(
816 async () => 1,
817 )
818 const a = definePlugin({ name: 'test/a', setup: () => ({ tools: [tool] }) })
819 const b = definePlugin({ name: 'test/b', setup: () => ({ tools: [tool] }) })
820 const { adapter } = mockAdapter([])
821 await expect(
822 host.open(
823 defineHarness({
824 name: 'test/dup',
825 adapter,
826 plugins: () => [a, b],
827 }),
828 {
829 threadId: 't1',
830 },
831 ),
832 ).rejects.toThrow(
833 'Duplicate tool "dup": first owner test/a, second owner test/b',
834 )
835 })
836})
837​
838describe('a waiting steer with an abort request', () => {
839 it('does not join, and settles aborted', async () => {
840 const started = gate()
841 const done = gate()
842 const wait = toolDefinition({ name: 'wait', description: 'Wait' }).server(
843 async () => {
844 started.open()
845 await done.opened
846 return 'waited'
847 },
848 )
849 const { adapter, calls } = mockAdapter([
850 () => toolCall('wait', {}),
851 () => text('host answer'),
852 ])
853 const host = createHarnessHost({ persistence: memoryPersistence() })
854 const session = await host.open(
855 defineHarness({
856 name: 'test/steer-abort',
857 adapter,
858 tools: [wait],
859 }),
860 {
861 threadId: 't-abort',
862 },
863 )
864​
865 const turn = session.send('start')
866 await started.opened
867 const steer = session.send('stop me', {
868 busy: 'steer',
869 inputId: 'steer-1',
870 })
871 await steer.receipt
872 await session.cancel({ operationId: steer.id })
873 done.open()
874​
875 expect(await turn).toEqual({ text: 'host answer', media: [] })
876 expect(messageTexts(calls[1])).not.toContain('stop me')
877 expect(await session.settled({ inputId: 'steer-1' })).toMatchObject({
878 outcome: 'aborted',
879 })
880 expect(calls).toHaveLength(2)
881 await host.close()
882 })
883})
884​
885describe('joins', () => {
886 /** A session whose `wait` tool runs until `wait.done` opens. */
887 async function openJoins(
888 replies: Array<Reply>,
889 turn: HarnessTurnOptions,
890 persistence: HarnessPersistence = memoryPersistence(),
891 ) {
892 const started = gate()
893 const done = gate()
894 const tool = toolDefinition({ name: 'wait', description: 'Wait' }).server(
895 async () => {
896 started.open()
897 await done.opened
898 return 'waited'
899 },
900 )
901 const { adapter, calls } = mockAdapter(replies)
902 const host = createHarnessHost({ persistence })
903 const session = await host.open(
904 defineHarness({
905 name: 'test/joins',
906 adapter,
907 tools: [tool],
908 turn,
909 }),
910 {
911 threadId: 't-joins',
912 },
913 )
914 return { host, session, calls, wait: { started, done } }
915 }
916​
917 it('keeps a joined prompt findable, and cancels it with its turn', async () => {
918 const { host, session, calls, wait } = await openJoins(
919 [() => toolCall('wait', {}), untilAborted()],
920 {},
921 )
922​
923 const turn = session.send('start')
924 await wait.started.opened
925 const steer = session.send('join me', { busy: 'steer' })
926 await steer.receipt
927 wait.done.open()
928 await waitFor(() => expect(calls).toHaveLength(2))
929​
930 expect(session.operation(steer.id)).toBe(steer)
931 expect(await session.cancel({ operationId: steer.id })).toMatchObject({
932 status: 'rejected',
933 reason: 'not_running',
934 })
935 await session.cancel({ operationId: turn.id })
936 await expect(steer).rejects.toThrow()
937 expect(steer.status()).toBe('cancelled')
938 await host.close()
939 })
940​
941 it('refuses a cancel that lands while onJoin runs, and the steer joins', async () => {
942 const inJoin = gate()
943 const releaseJoin = gate()
944 const { host, session, calls, wait } = await openJoins(
945 [() => toolCall('wait', {}), () => text('host answer')],
946 {
947 onJoin: async () => {
948 inJoin.open()
949 await releaseJoin.opened
950 return undefined
951 },
952 },
953 )
954​
955 const turn = session.send('start')
956 await wait.started.opened
957 const steer = session.send('stop me', { busy: 'steer', inputId: 's1' })
958 await steer.receipt
959 wait.done.open()
960 await inJoin.opened
961 const receipt = await session.cancel({ operationId: steer.id })
962 releaseJoin.open()
963​
964 expect(receipt).toMatchObject({ status: 'rejected', reason: 'not_running' })
965 expect(await steer).toEqual(await turn)
966 expect(messageTexts(calls[1]).at(-1)).toBe('stop me')
967 expect(await session.settled({ inputId: 's1' })).toMatchObject({
968 outcome: 'completed',
969 operationId: turn.id,
970 })
971 await host.close()
972 })
973​
974 it('refuses a cancel that lands after the late-join check', async () => {
975 const inner = memoryLogStore()
976 const inUpdate = gate()
977 const releaseUpdate = gate()
978 let isArmed = false
979 /** The run of the turn starts again, for the late steer. */
980 const isRunAgain = (record: LogRecord) =>
981 record.type === 'harness.run.update' &&
982 isRecord(record.patch) &&
983 record.patch.status === 'running'
984 const log = wrapLogStore(inner, {
985 append: async (batch) => {
986 if (isArmed && batch.records.some(isRunAgain)) {
987 isArmed = false
988 inUpdate.open()
989 await releaseUpdate.opened
990 }
991 return inner.append(batch)
992 },
993 })
994 const release = gate()
995 const { host, session, calls } = await openJoins(
996 [after(release.opened, 'first answer'), () => text('late answer')],
997 {},
998 { stores: { log } },
999 )
1000​
1001 const turn = session.send('first')
1002 await waitFor(() => expect(calls).toHaveLength(1))
1003 const late = session.send('late', { busy: 'steer', inputId: 'late' })
1004 await late.receipt
1005 isArmed = true
1006 release.open()
1007 // The turn decided to run the model again for the late steer.
1008 await inUpdate.opened
1009 // Its input record waits for the log write of the run.
1010 const receipt = session.cancel({ operationId: late.id })
1011 releaseUpdate.open()
1012​
1013 expect(await receipt).toMatchObject({
1014 status: 'rejected',
1015 reason: 'not_running',
1016 })
1017 expect(await turn).toEqual({ text: 'first answerlate answer', media: [] })
1018 expect(calls).toHaveLength(2)
1019 expect(messageTexts(calls[1]).at(-1)).toBe('late')
1020 await host.close()
1021 })
1022​
1023 it('keeps the model context that an earlier middleware set, with the steer', async () => {
1024 const release = gate()
1025 const { adapter, calls } = mockAdapter([
1026 after(release.opened, 'first'),
1027 () => text('second'),
1028 ])
1029 const host = createHarnessHost({ persistence: memoryPersistence() })
1030 const session = await host.open(
1031 defineHarness({
1032 name: 'test/steer-context',
1033 adapter,
1034 middleware: [hideSecret],
1035 }),
1037 threadId: 't-context',
1038 },
1040​
1041 const turn = session.send('secret')
1042 await waitFor(() => expect(calls).toHaveLength(1))
1043 await session.send('more', { busy: 'steer' }).receipt
1044 release.open()
1045 await turn
1046​
1047 expect(messageTexts(calls[1])).toEqual(['[hidden]', 'first', 'more'])
1048 await host.close()
1049 })
1050​
1051 it('sends a steer that joins a call through the per-call change of a middleware', async () => {
1052 const image: ContentPart = {
1053 type: 'image',
1054 source: { type: 'url', value: 'https://example.com/cat.png' },
1056 // Like a model that cannot read images: each image becomes a text.
1057 const noImages: AnyChatMiddleware = {
1058 name: 'test/no-images',
1059 onConfig: (ctx, config) => {
1060 if (ctx.phase !== 'beforeModel') return undefined
1061 return {
1062 providerMessages: (config.providerMessages ?? config.messages).map(
1063 (message) =>
1064 Array.isArray(message.content)
1065 ? {
1066 ...message,
1067 content: message.content.map((part) =>
1068 part.type === 'image'
1069 ? { type: 'text' as const, content: '[image]' }
1070 : part,
1071 ),
1073 : message,
1074 ),
1076 },
1078 const release = gate()
1079 const { adapter, calls } = mockAdapter([
1080 after(release.opened, 'first'),
1081 () => text('second'),
1082 ])
1083 const host = createHarnessHost({ persistence: memoryPersistence() })
1084 const session = await host.open(
1085 defineHarness({
1086 name: 'test/steer-convert',
1087 adapter,
1088 middleware: [noImages],
1089 }),
1091 threadId: 't-convert',
1092 },
1094 const steer: Array<ContentPart> = [{ type: 'text', content: 'this' }, image]
1095​
1096 const turn = session.send('look')
1097 await waitFor(() => expect(calls).toHaveLength(1))
1098 await session.send(steer, { busy: 'steer' }).receipt
1099 release.open()
1100 await turn
1101​
1102 expect(calls[1].messages.at(-1).content).toEqual([
1103 { type: 'text', content: 'this' },
1104 { type: 'text', content: '[image]' },
1105 ])
1106 const transcript = await session.transcript()
1107 expect(
1108 transcript.find(
1109 (message) => message.role === 'user' && Array.isArray(message.content),
1110 )?.content,
1111 ).toEqual(steer)
1112 await host.close()
1113 })
1114​
1115 it('fails the turn when onJoin throws, and runs the steer as its own turn', async () => {
1116 const { host, session, calls, wait } = await openJoins(
1117 [() => toolCall('wait', {}), () => text('steer answer')],
1119 onJoin: () => {
1120 throw new Error('hook broke')
1121 },
1122 },
1124​
1125 const turn = session.send('start')
1126 await wait.started.opened
1127 const steer = session.send('more', { busy: 'steer', inputId: 's1' })
1128 await steer.receipt
1129 wait.done.open()
1130​
1131 await expect(turn).rejects.toThrow('hook broke')
1132 expect(await steer).toEqual({ text: 'steer answer', media: [] })
1133 expect(messageTexts(calls[1])).toContain('more')
1134 expect((await session.settled({ inputId: 's1' })).operationId).not.toBe(
1135 turn.id,
1137 await host.close()
1138 })
1139​
1140 it('adds nothing from onJoin to a turn cancelled while the hook runs', async () => {
1141 const inJoin = gate()
1142 const releaseJoin = gate()
1143 const { host, session, calls, wait } = await openJoins(
1145 () => toolCall('wait', {}),
1146 () => text('cancelled answer'),
1147 () => text('steer answer'),
1148 ],
1150 onJoin: async () => {
1151 inJoin.open()
1152 await releaseJoin.opened
1153 return { messages: [{ role: 'user', content: 'hook' }] }
1154 },
1155 },
1157​
1158 const turn = session.send('start')
1159 await wait.started.opened
1160 const steer = session.send('more', { busy: 'steer', inputId: 's1' })
1161 await steer.receipt
1162 wait.done.open()
1163 await inJoin.opened
1164 await turn.cancel()
1165 releaseJoin.open()
1166​
1167 await expect(turn).rejects.toThrow('Cancelled')
1168 expect(await steer).toEqual({ text: 'steer answer', media: [] })
1169 for (const call of calls) expect(messageTexts(call)).not.toContain('hook')
1170 expect(messageTexts(calls.at(-1))).toContain('more')
1171 expect((await session.settled({ inputId: 's1' })).operationId).not.toBe(
1172 turn.id,
1174 await host.close()
1175 })
1176​
1177 it('stops at a steer that a cancel reaches while canJoin runs', async () => {
1178 let cancelled: Receipt | undefined
1179 let aId = ''
1180 let session: Awaited<ReturnType<typeof openJoins>>['session'] | undefined
1181 const joins = await openJoins(
1183 () => toolCall('wait', {}),
1184 () => text('host answer'),
1185 () => text('b answer'),
1186 ],
1188 canJoin: async ({ inputId }) => {
1189 // The cancel of the earlier steer lands while canJoin runs for `b`.
1190 if (inputId === 'b' && !cancelled) {
1191 cancelled = await session?.cancel({ operationId: aId })
1193 return true
1194 },
1195 },
1197 session = joins.session
1198 const { host, calls, wait } = joins
1199​
1200 const turn = session.send('start')
1201 await wait.started.opened
1202 const a = session.send('a', { busy: 'steer', inputId: 'a' })
1203 aId = a.id
1204 const b = session.send('b', { busy: 'steer', inputId: 'b' })
1205 await Promise.all([a.receipt, b.receipt])
1206 wait.done.open()
1207 await turn
1208​
1209 expect(cancelled?.status).toBe('accepted')
1210 expect(messageTexts(calls[1])).not.toContain('a')
1211 expect(await session.settled({ inputId: 'a' })).toMatchObject({
1212 outcome: 'aborted',
1213 })
1214 expect(await b).toEqual({ text: 'b answer', media: [] })
1215 await host.close()
1216 })