Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { memoryPersistence } from '@tanstack/ai-persistence'
3import { EventType } from '@tanstack/ai'
4import {
5 HARNESS_EVENTS,
6 createHarnessHost,
7 defineCommand,
8 defineHarness,
9 definePlugin,
10} from '../src'
11import { question } from '../src/first-party/question'
12import { mockAdapter, questionsOf, text, toolCall } from './helpers'
13import type { ChatTurnResult, HarnessSession, Operation } from '../src'
14
15const database = {
16 question: 'Which database?',
17 header: 'Database',
18 options: [
19 { label: 'Postgres', description: 'Relational, the default' },
20 { label: 'SQLite' },
21 ],
22}
23
24const features = {
25 question: 'Which features?',
26 options: [{ label: 'Auth' }, { label: 'Search' }, { label: 'Billing' }],
27 multiple: true,
28}
29
30/** The model calls `question` with `questions`, then ends the turn. */
31async function open(questions: Array<object>) {
32 const { adapter, calls } = mockAdapter([
33 () => toolCall('question', { questions }, 'c1'),
34 () => text('done'),
35 ])
36 const host = createHarnessHost({ persistence: memoryPersistence() })
37 const session = await host.open(
38 defineHarness({
39 name: 'test/question',
40 adapter,
41 plugins: () => [question()],
42 }),
43 {
44 threadId: 't',
45 },
46 )
47 const turn = session.send('ask me')
48 return { host, session, calls, turn }
49}
50
51/**
52 * Wait for the turn to stop for its question waits, then answer each one
53 * with `values`, in order, and wait for the turn that goes on. Returns the
54 * waits.
55 */
56async function reply(
57 session: HarnessSession,
58 turn: Operation<ChatTurnResult>,
59 values: Array<unknown>,
60 status: 'resolved' | 'cancelled' = 'resolved',
61) {
62 await turn
63 const pending = session.snapshot().pendingWaits
64 expect(pending.map((wait) => wait.kind)).toEqual(values.map(() => 'question'))
65 await session.resolve({
66 resume: pending.map((wait, index) => ({
67 interruptId: wait.waitId,
68 status,
69 ...(status === 'resolved' ? { payload: values[index] } : {}),
70 })),
71 inputId: 'answers',
72 })
73 expect(await session.settled({ inputId: 'answers' })).toMatchObject({
74 outcome: 'completed',
75 })
76 return pending
77}
78
79/** The tool result the model got on its second call. */
80function toolResult(
81 calls: Array<{ messages: Array<{ role: string; content: unknown }> }>,
82) {
83 return calls[1]?.messages.find((message) => message.role === 'tool')?.content
84}
85
86describe('question()', () => {
87 it('stops the turn before the tool runs, with a wait for each question, and gives the model the picked labels', async () => {
88 const { host, session, calls, turn } = await open([database, features])
89
90 expect((await turn).interrupts).toHaveLength(2)
91 // The tool did not run: the model got no result yet.
92 expect(calls).toHaveLength(1)
93 const [first, second] = await reply(session, turn, [
94 '2',
95 ['billing', 'Auth'],
96 ])
97
98 expect(first?.message).toBe(
99 'Database: Which database?\n1. Postgres - Relational, the default\n2. SQLite\nType a number or a label, or your own answer.',
100 )
101 expect(first?.schema).toEqual({
102 type: 'string',
103 enum: ['Postgres', 'SQLite'],
104 })
105 expect(second?.message).toContain('3. Billing')
106 expect(second?.schema).toEqual({
107 type: 'array',
108 items: { type: 'string', enum: ['Auth', 'Search', 'Billing'] },
109 minItems: 1,
110 uniqueItems: true,
111 })
112 expect(toolResult(calls)).toBe(
113 'Which database?\nAnswer: SQLite\n\nWhich features?\nAnswer: Billing, Auth',
114 )
115 await host.close()
116 })
117
118 it.each([
119 ['a label in another case', database, ' postgres ', 'Answer: Postgres'],
120 [
121 'numbers and labels split by commas',
122 features,
123 'auth, 3',
124 'Answer: Auth, Billing',
125 ],
126 [
127 'text that names no option',
128 database,
129 'We use Mongo',
130 'Own answer: We use Mongo',
131 ],
132 ])('reads %s', async (_name, asked, value, expected) => {
133 const { host, session, calls, turn } = await open([asked])
134
135 await reply(session, turn, [value])
136
137 expect(toolResult(calls)).toBe(`${asked.question}\n${expected}`)
138 await host.close()
139 })
140
141 it('gives the model a tool error when a reply is empty', async () => {
142 const { host, session, calls, turn } = await open([database, features])
143
144 await reply(session, turn, [' ', 'Auth'])
145
146 expect(toolResult(calls)).toContain('The user did not answer.')
147 expect(session.snapshot().pendingWaits).toEqual([])
148 await host.close()
149 })
150
151 it('gives the model a tool error when the user cancels the questions', async () => {
152 const { host, session, calls, turn } = await open([database])
153
154 await reply(session, turn, [undefined], 'cancelled')
155
156 expect(toolResult(calls)).toContain('The user did not answer.')
157 await host.close()
158 })
159
160 it('asks nothing for input that is not valid, and gives the model a tool error', async () => {
161 const { host, session, calls, turn } = await open([{ question: 'Hm?' }])
162
163 expect((await turn).interrupts ?? []).toEqual([])
164 expect(toolResult(calls)).toContain('Input validation failed')
165 expect(session.snapshot().pendingWaits).toEqual([])
166 await host.close()
167 })
168})
169
170describe('ask with a url', () => {
171 it('sends the url in the event and the snapshot', async () => {
172 const asker = definePlugin({
173 name: 'test/url-asker',
174 setup: () => ({
175 commands: {
176 verify: defineCommand({
177 description: 'Asks the user to open a page',
178 run: (_input, { step }) =>
179 step.ask({
180 name: 'verify',
181 message: 'Open the page, then type done.',
182 url: 'https://example.com/verify',
183 }),
184 }),
185 },
186 }),
187 })
188 const host = createHarnessHost({ persistence: memoryPersistence() })
189 const session = await host.open(
190 defineHarness({
191 name: 'test/url-question',
192 adapter: mockAdapter([]).adapter,
193 plugins: () => [asker],
194 }),
195 {
196 threadId: 't',
197 },
198 )
199 const running = session.runCommand({ name: 'verify' })
200
201 await vi.waitFor(() =>
202 expect(questionsOf(session.snapshot())).toHaveLength(1),
203 )
204 expect(questionsOf(session.snapshot())[0]?.url).toBe(
205 'https://example.com/verify',
206 )
207 const [pending] = questionsOf(session.snapshot())
208 if (!pending) throw new Error('No question.')
209 await session.answer({ questionId: pending.questionId, value: 'done' })
210 expect(await running).toBe('done')
211
212 const controller = new AbortController()
213 let url: unknown
214 for await (const { event } of session.events({
215 from: '0',
216 signal: controller.signal,
217 })) {
218 if (
219 event.type === EventType.CUSTOM &&
220 event.name === HARNESS_EVENTS.question &&
221 event.value !== null &&
222 typeof event.value === 'object' &&
223 'url' in event.value
224 ) {
225 url = event.value.url
226 controller.abort()
227 }
228 }
229 expect(url).toBe('https://example.com/verify')
230 await host.close()
231 })
232})