Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { z } from 'zod'
3import { EventType, createCapability, toolDefinition } from '@tanstack/ai'
4import {
5 memoryLogState,
6 memoryLogStore,
7 memoryPersistence,
8} from '@tanstack/ai-persistence'
9import {
10 HARNESS_EVENTS,
11 configOption,
12 createHarnessHost,
13 defineHarness,
14 definePlugin,
15 logIdOf,
16} from '../src'
17import { canOtherHostTake, mockAdapter, text } from './helpers'
18import type { AnyTool, ModelMessage } from '@tanstack/ai'
19import type { HarnessConfig, HarnessPersistence } from '../src'
20import type { Reply } from './helpers'
21
22const THREAD = 't1'
23
24function durablePersistence() {
25 const { metadata } = memoryPersistence().stores
26 return { stores: { log: memoryLogStore(), metadata } }
27}
28
29const toolNames = (call: { tools?: ReadonlyArray<AnyTool> }) =>
30 (call.tools ?? []).map((tool) => tool.name)
31
32const echo = (name: string) =>
33 toolDefinition({
34 name,
35 description: `The ${name} tool`,
36 inputSchema: z.object({}),
37 }).server(async () => name)
38
39/** A base adapter and two named models, each with its own calls. */
40function models(replies: Array<Reply> = [() => text('ok')]) {
41 const base = mockAdapter(() => text('base'))
42 const fast = mockAdapter(() => text('fast'))
43 const strong = mockAdapter(replies)
44 return { base, fast, strong }
45}
46
47async function open(
48 extras: Omit<HarnessConfig, 'name'> = {},
49 persistence: HarnessPersistence = memoryPersistence(),
50) {
51 const host = createHarnessHost({ persistence })
52 const harness = defineHarness({ name: 'test/settings', ...extras })
53 const session = await host.open(harness, { threadId: THREAD })
54 return { host, harness, session }
55}
56
57describe('thread settings', () => {
58 it('runs the next turn on the model the settings name', async () => {
59 const { base, fast, strong } = models()
60 const { host, session } = await open({
61 adapter: base.adapter,
62 models: { fast: fast.adapter, strong: strong.adapter },
63 })
64
65 expect(
66 await session.updateThreadSettings({ settings: { model: 'strong' } }),
67 ).toMatchObject({
68 status: 'accepted',
69 })
70 expect(session.threadSettings()).toEqual({ model: 'strong' })
71 expect((await session.send('Hi.')).text).toBe('ok')
72 expect(strong.calls).toHaveLength(1)
73 expect(base.calls).toHaveLength(0)
74
75 // `null` clears the field: the harness adapter answers again.
76 await session.updateThreadSettings({ settings: { model: null } })
77 expect(session.threadSettings()).toEqual({})
78 expect((await session.send('Again.')).text).toBe('base')
79 await host.close()
80 })
81
82 it('puts the settings model after the turn override and before a plugin pick', async () => {
83 const { base, fast, strong } = models()
84 const override = mockAdapter(() => text('override'))
85 const picked = mockAdapter(() => text('picked'))
86 const { host, session } = await open({
87 adapter: base.adapter,
88 models: { fast: fast.adapter, strong: strong.adapter },
89 plugins: () => [
90 definePlugin({
91 name: 'test/picker',
92 setup: () => ({ adapter: () => picked.adapter }),
93 }),
94 ],
95 })
96 await session.updateThreadSettings({ settings: { model: 'fast' } })
97
98 const overridden = await session.send('One.', {
99 overrides: { adapter: override.adapter },
100 })
101 expect(overridden.text).toBe('override')
102 expect((await session.send('Two.')).text).toBe('fast')
103 await session.updateThreadSettings({ settings: { model: null } })
104 expect((await session.send('Three.')).text).toBe('picked')
105 // A removed plugin's pick is left out too.
106 await session.updateThreadSettings({
107 settings: { plugins: { remove: ['test/picker'] } },
108 })
109 expect((await session.send('Four.')).text).toBe('base')
110 await host.close()
111 })
112
113 it('lets a plugin pick with override: true win over the settings model', async () => {
114 const { base, fast, strong } = models()
115 const override = mockAdapter(() => text('override'))
116 const forced = mockAdapter(() => text('forced'))
117 const picked = mockAdapter(() => text('picked'))
118 let force = true
119 const { host, session } = await open({
120 adapter: base.adapter,
121 models: { fast: fast.adapter, strong: strong.adapter },
122 plugins: () => [
123 definePlugin({
124 name: 'test/forcer',
125 setup: () => ({
126 adapter: () =>
127 force ? { adapter: forced.adapter, override: true } : undefined,
128 }),
129 }),
130 // A later plain pick does not hide the override pick.
131 definePlugin({
132 name: 'test/picker',
133 setup: () => ({ adapter: () => picked.adapter }),
134 }),
135 ],
136 })
137 await session.updateThreadSettings({ settings: { model: 'fast' } })
138
139 expect((await session.send('One.')).text).toBe('forced')
140 // The prompt override still wins over everything.
141 const overridden = await session.send('Two.', {
142 overrides: { adapter: override.adapter },
143 })
144 expect(overridden.text).toBe('override')
145 // Without the override pick, the settings model wins again.
146 force = false
147 expect((await session.send('Three.')).text).toBe('fast')
148 await host.close()
149 })
150
151 it('publishes the change, and treats a repeated inputId as the same input', async () => {
152 const { adapter } = mockAdapter(() => text('ok'))
153 const { host, session } = await open({ adapter })
154 const from = session.snapshot().cursor
155 const reader = new AbortController()
156
157 const first = await session.updateThreadSettings({
158 settings: { instructions: 'Be short.' },
159 inputId: 'set-1',
160 })
161 expect(
162 await session.updateThreadSettings({
163 settings: { instructions: 'Be short.' },
164 inputId: 'set-1',
165 }),
166 ).toEqual(first)
167 expect(
168 await session.updateThreadSettings({
169 settings: { instructions: 'Be long.' },
170 inputId: 'set-1',
171 }),
172 ).toMatchObject({ status: 'rejected', reason: 'conflict' })
173 expect(session.threadSettings()).toEqual({ instructions: 'Be short.' })
174
175 for await (const entry of session.events({ from, signal: reader.signal })) {
176 const { event } = entry
177 if (
178 event.type === EventType.CUSTOM &&
179 event.name === HARNESS_EVENTS.settingsChanged
180 ) {
181 expect(event.value).toEqual({ settings: { instructions: 'Be short.' } })
182 reader.abort()
183 }
184 }
185 await host.close()
186 })
187
188 it('sends the settings reasoning unless the turn overrides it', async () => {
189 const { adapter, calls } = mockAdapter(() => text('ok'))
190 const { host, session } = await open({ adapter })
191 await session.updateThreadSettings({ settings: { reasoning: 'high' } })
192
193 await session.send('One.')
194 await session.send('Two.', { overrides: { reasoning: 'low' } })
195 expect(calls.map((call) => call.reasoning?.level)).toEqual(['high', 'low'])
196 await host.close()
197 })
198
199 it('adds the instructions as the last system prompt', async () => {
200 const { adapter, calls } = mockAdapter(() => text('ok'))
201 const { host, session } = await open({
202 adapter,
203 systemPrompts: ['You help with code.'],
204 plugins: () => [
205 definePlugin({
206 name: 'test/prompt',
207 setup: () => ({ prompts: ['Use tabs.'] }),
208 }),
209 ],
210 })
211 await session.updateThreadSettings({
212 settings: { instructions: 'Answer in French.' },
213 })
214
215 await session.send('Hi.')
216 const prompts: Array<unknown> = calls[0].systemPrompts
217 expect(JSON.stringify(prompts.at(-1))).toContain('Answer in French.')
218 expect(JSON.stringify(prompts)).toContain('Use tabs.')
219 await host.close()
220 })
221
222 it('keeps an exact tool list, or leaves out named tools', async () => {
223 const { adapter, calls } = mockAdapter(() => text('ok'))
224 const { host, session } = await open({
225 adapter,
226 tools: [echo('alpha'), echo('beta'), echo('gamma')],
227 })
228
229 await session.updateThreadSettings({ settings: { tools: ['alpha'] } })
230 await session.send('One.')
231 await session.updateThreadSettings({
232 settings: { tools: { remove: ['alpha'] } },
233 })
234 await session.send('Two.')
235 // A tool of the turn override is kept.
236 await session.send('Three.', { overrides: { tools: [echo('delta')] } })
237
238 expect(calls.map(toolNames)).toEqual([
239 ['alpha'],
240 ['beta', 'gamma'],
241 ['beta', 'gamma', 'delta'],
242 ])
243 await host.close()
244 })
245
246 it('leaves out the tools, prompts, and middleware of a removed plugin', async () => {
247 const { adapter, calls } = mockAdapter(() => text('ok'))
248 const seen: Array<string> = []
249 const { host, session } = await open({
250 adapter,
251 plugins: () => [
252 definePlugin({
253 name: 'acme/notes',
254 setup: () => ({
255 tools: [echo('note')],
256 prompts: ['Keep notes.'],
257 middleware: [
258 { name: 'notes', onStart: () => void seen.push('notes') },
259 ],
260 }),
261 }),
262 definePlugin({
263 name: 'acme/search',
264 lifetime: 'turn',
265 setup: () => ({ tools: [echo('search')], prompts: ['Search.'] }),
266 }),
267 ],
268 })
269
270 await session.send('One.')
271 await session.updateThreadSettings({
272 settings: { plugins: { remove: ['acme/notes'] } },
273 })
274 await session.send('Two.')
275
276 expect(calls.map(toolNames)).toEqual([['note', 'search'], ['search']])
277 expect(JSON.stringify(calls[1].systemPrompts)).not.toContain('Keep notes.')
278 expect(JSON.stringify(calls[1].systemPrompts)).toContain('Search.')
279 expect(seen).toEqual(['notes'])
280 await host.close()
281 })
282
283 it('refuses an unknown model or plugin', async () => {
284 const { adapter } = mockAdapter(() => text('ok'))
285 const { host, session } = await open({
286 adapter,
287 models: { fast: adapter },
288 })
289
290 expect(
291 await session.updateThreadSettings({ settings: { model: 'huge' } }),
292 ).toMatchObject({
293 status: 'rejected',
294 reason: expect.stringContaining('huge'),
295 })
296 expect(
297 await session.updateThreadSettings({
298 settings: { plugins: { remove: ['acme/none'] } },
299 }),
300 ).toMatchObject({
301 status: 'rejected',
302 reason: expect.stringContaining('acme/none'),
303 })
304 expect(session.threadSettings()).toEqual({})
305 await host.close()
306 })
307
308 it('refuses to remove a plugin whose capability a turn plugin or a harness middleware requires', async () => {
309 const Notes = createCapability<string>()('acme/notes-capability')
310 const { adapter } = mockAdapter(() => text('ok'))
311 const { host, session } = await open({
312 adapter,
313 middleware: [{ name: 'audit', requires: [Notes] }],
314 plugins: () => [
315 definePlugin({
316 name: 'acme/notes',
317 provides: [Notes],
318 setup: (ctx) => void ctx.provide(Notes, 'notes'),
319 }),
320 definePlugin({
321 name: 'acme/search',
322 lifetime: 'turn',
323 requires: [Notes],
324 }),
325 ],
326 })
327 const remove = (names: Array<string>) =>
328 session.updateThreadSettings({ settings: { plugins: { remove: names } } })
329
330 expect(await remove(['acme/notes'])).toMatchObject({
331 status: 'rejected',
332 reason: expect.stringContaining('plugin acme/search requires'),
333 })
334 expect(await remove(['acme/notes', 'acme/search'])).toMatchObject({
335 status: 'rejected',
336 reason: expect.stringContaining('harness middleware audit requires'),
337 })
338 expect(session.threadSettings()).toEqual({})
339 await host.close()
340 })
341
342 it('keeps the settings after a restart', async () => {
343 const persistence = durablePersistence()
344 const { base, strong } = models([() => text('strong')])
345 const harness = defineHarness({
346 name: 'test/settings',
347 adapter: base.adapter,
348 models: { strong: strong.adapter },
349 })
350 const first = createHarnessHost({ persistence })
351 await (
352 await first.open(harness, { threadId: THREAD })
353 ).updateThreadSettings({
354 settings: { model: 'strong', instructions: 'Be short.' },
355 })
356 await first.close()
357
358 const second = createHarnessHost({ persistence })
359 const session = await second.open(harness, { threadId: THREAD })
360 expect(session.threadSettings()).toEqual({
361 model: 'strong',
362 instructions: 'Be short.',
363 })
364 expect((await session.send('Hi.')).text).toBe('strong')
365 await second.close()
366 })
367})
368
369describe('the working folder note', () => {
370 const sent = (call: { messages: ReadonlyArray<ModelMessage> }) =>
371 JSON.stringify(call.messages)
372
373 it('adds no note to a new thread, so the user message comes first', async () => {
374 const { adapter, calls } = mockAdapter(() => text('ok'))
375 const { host, session } = await open({ adapter })
376
377 await session.updateThreadSettings({ settings: { cwd: '/repo/app' } })
378 await session.send('Hi.')
379 const roles = calls[0]?.messages.map(
380 (message: ModelMessage) => message.role,
381 )
382 expect(roles).toEqual(['user'])
383 expect(sent(calls[0])).not.toContain('working folder')
384 await host.close()
385 })
386
387 it('tells the next model call when the working folder changes', async () => {
388 const { adapter, calls } = mockAdapter(() => text('ok'))
389 const { host, session } = await open({ adapter })
390
391 await session.send('First.')
392 await session.updateThreadSettings({ settings: { cwd: '/repo/app' } })
393 await session.send('Hi.')
394 expect(sent(calls[1])).toContain(
395 'The working folder is now /repo/app. Paths are relative to it.',
396 )
397 // The note is in the saved transcript, so it survives a restart.
398 expect(JSON.stringify(await session.transcript())).toContain(
399 'The working folder is now /repo/app.',
400 )
401 await host.close()
402 })
403
404 it('adds no note when the working folder stays the same', async () => {
405 const { adapter, calls } = mockAdapter(() => text('ok'))
406 const { host, session } = await open({ adapter })
407
408 await session.send('First.')
409 await session.updateThreadSettings({ settings: { cwd: '/repo/app' } })
410 await session.updateThreadSettings({ settings: { cwd: '/repo/app' } })
411 await session.updateThreadSettings({
412 settings: { instructions: 'Be short.' },
413 })
414 await session.send('Hi.')
415 expect(sent(calls[1]).split('The working folder is now')).toHaveLength(2)
416 await host.close()
417 })
418
419 it('tells the model when the working folder is cleared', async () => {
420 const { adapter, calls } = mockAdapter(() => text('ok'))
421 const { host, session } = await open({ adapter })
422
423 await session.updateThreadSettings({ settings: { cwd: null } })
424 await session.send('Hi.')
425 expect(sent(calls[0])).not.toContain('working folder')
426
427 await session.updateThreadSettings({ settings: { cwd: '/repo/app' } })
428 await session.updateThreadSettings({ settings: { cwd: null } })
429 await session.send('Again.')
430 expect(sent(calls[1])).toContain(
431 'The working folder is the default folder again.',
432 )
433 await host.close()
434 })
435})
436
437describe('plugin config next to the settings', () => {
438 it('keeps plugin config and the settings apart', async () => {
439 const { adapter } = mockAdapter(() => text('ok'))
440 const { host, session } = await open({
441 adapter,
442 plugins: () => [
443 definePlugin({
444 name: 'test/tone',
445 setup: () => ({
446 config: {
447 tone: configOption.select({
448 options: ['plain', 'warm'],
449 default: 'plain',
450 }),
451 },
452 }),
453 }),
454 ],
455 })
456 await session.setPluginSetting({ key: 'tone', value: 'warm' })
457 await session.updateThreadSettings({
458 settings: { instructions: 'Be brief.' },
459 })
460 expect(session.pluginSettings().tone?.value).toBe('warm')
461 expect(session.threadSettings()).toEqual({ instructions: 'Be brief.' })
462 await host.close()
463 })
464})
465
466describe('thread settings on two hosts', () => {
467 it('keeps the change of the other host, and a turn uses it', async () => {
468 const logState = memoryLogState()
469 const model = mockAdapter(() => text('ok'))
470 const harness = defineHarness({
471 name: 'test/settings',
472 adapter: model.adapter,
473 })
474 const hostOn = () =>
475 createHarnessHost({
476 persistence: { stores: { log: memoryLogStore({ state: logState }) } },
477 })
478 const hostA = hostOn()
479 const hostB = hostOn()
480 const a = await hostA.open(harness, { threadId: THREAD })
481 const b = await hostB.open(harness, { threadId: THREAD })
482
483 await a.updateThreadSettings({ settings: { reasoning: 'high' } })
484 // A gives the log back, so B owns it for its change.
485 const store = memoryLogStore({ state: logState })
486 await vi.waitFor(
487 async () =>
488 expect(await canOtherHostTake(store, logIdOf({ logId: THREAD }))).toBe(
489 true,
490 ),
491 { timeout: 5_000 },
492 )
493 expect(
494 await b.updateThreadSettings({
495 settings: { instructions: 'Answer in French.' },
496 }),
497 ).toMatchObject({ status: 'accepted' })
498
499 // Each host reads the change of the other one from the log.
500 const both = { reasoning: 'high', instructions: 'Answer in French.' }
501 for (const session of [a, b]) {
502 await vi.waitFor(() => expect(session.threadSettings()).toEqual(both), {
503 timeout: 5_000,
504 })
505 }
506 await b.send('Hello.')
507 expect(model.calls.map((call) => call.reasoning?.level)).toEqual(['high'])
508 await hostA.close()
509 await hostB.close()
510 })
511})