Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { z } from 'zod'
3import { defineAgent, toolDefinition } from '@tanstack/ai'
4import { memoryPersistence } from '@tanstack/ai-persistence'
5import {
6 configOption,
7 createHarnessHost,
8 defineCommand,
9 defineHarness,
10 definePlugin,
11} from '../src'
12import {
13 CRASHING_OWNERSHIP,
14 messageTexts,
15 mockAdapter,
16 ownershipExpired,
17 storedThreadState,
18 text,
19 toolCall,
20 turnInterrupts,
21 untilAborted,
22} from './helpers'
23import type { ModelMessage, ReasoningRequest } from '@tanstack/ai'
24import type { HarnessConfig, OwnershipOptions } from '../src'
25import type { Reply } from './helpers'
26
27// Coverage runs in CI are slow, so polled checks wait up to 5 s.
28const waitFor = <T>(
29 check: () => T | Promise<T>,
30 options?: { timeout?: number; interval?: number },
31) => vi.waitFor(check, { timeout: 5_000, ...options })
32
33const THREAD = 't1'
34const alice = { id: 'alice' }
35const HIGH: ReasoningRequest = { level: 'high', summary: true }
36
37/**
38 * Memory stores, as two servers share them, and the metadata namespaces
39 * that the harness writes. Thread state goes to the log, so the list stays
40 * empty. A server that stopped owns its logs until the ownership expires.
41 */
42function sharedStores() {
43 const { log, metadata } = memoryPersistence().stores
44 const persistence = { stores: { log, metadata } }
45 const written: Array<string> = []
46 const record = (namespace: string) => {
47 written.push(namespace)
48 }
49 const { setIf } = metadata
50 if (!setIf) throw new Error('The memory store has compare-and-set.')
51 const set = metadata.set.bind(metadata)
52 const remove = metadata.delete.bind(metadata)
53 vi.spyOn(metadata, 'set').mockImplementation((namespace, key, value) => {
54 record(namespace)
55 return set(namespace, key, value)
56 })
57 vi.spyOn(metadata, 'setIf').mockImplementation(
58 (namespace, key, value, revision) => {
59 record(namespace)
60 return setIf.call(metadata, namespace, key, value, revision)
61 },
62 )
63 vi.spyOn(metadata, 'delete').mockImplementation((namespace, key) => {
64 record(namespace)
65 return remove(namespace, key)
66 })
67 return { persistence, written }
68}
69
70type Shared = ReturnType<typeof sharedStores>
71
72/** Open thread `THREAD` for alice on a new host: a server that starts. */
73async function openOn(
74 { persistence }: Shared,
75 config: Omit<HarnessConfig, 'name' | 'adapter'>,
76 replies: Array<Reply> = [],
77 ownership?: OwnershipOptions,
78) {
79 const model = mockAdapter(replies)
80 const host = createHarnessHost({
81 persistence,
82 ...(ownership ? { ownership } : {}),
83 })
84 const session = await host.open(
85 defineHarness({
86 name: 'test/thread-state',
87 adapter: model.adapter,
88 ...config,
89 }),
90 { threadId: THREAD, user: alice },
91 )
92 return { host, session, calls: model.calls }
93}
94
95const level = definePlugin({
96 name: 'test/level',
97 setup: () => ({
98 config: {
99 level: configOption.select({ options: ['low', 'high'], default: 'low' }),
100 },
101 }),
102})
103
104/** A plugin whose `/bump` command counts in its thread state. */
105const counter = definePlugin({
106 name: 'test/counter',
107 setup: (ctx) => {
108 const state = ctx.state({ count: 0, label: 'none' })
109 return {
110 commands: {
111 bump: defineCommand({
112 description: 'Add one',
113 run: async () =>
114 (
115 await state.update((value) => ({
116 ...value,
117 count: value.count + 1,
118 }))
119 ).count,
120 }),
121 },
122 }
123 },
124})
125
126describe('thread state in the log', () => {
127 it('keeps the checked settings, and drops a rejected change', async () => {
128 const shared = sharedStores()
129 const config = { models: { strong: mockAdapter([]).adapter } }
130 const first = await openOn(shared, config)
131 await first.session.updateThreadSettings({
132 settings: { model: 'strong', instructions: 'Answer in French.' },
133 })
134 const refused = await first.session.updateThreadSettings({
135 settings: { model: 'missing' },
136 })
137 expect(refused).toMatchObject({ status: 'rejected' })
138 await first.host.close()
139
140 const second = await openOn(shared, config)
141
142 expect(second.session.threadSettings()).toEqual({
143 model: 'strong',
144 instructions: 'Answer in French.',
145 })
146 expect(shared.written).toEqual([])
147 await second.host.close()
148 })
149
150 it('keeps the config values', async () => {
151 const shared = sharedStores()
152 const config = { plugins: () => [level] }
153 const first = await openOn(shared, config)
154 await first.session.setPluginSetting({ key: 'level', value: 'high' })
155 await first.host.close()
156
157 const second = await openOn(shared, config)
158
159 expect(second.session.pluginSettings().level?.value).toBe('high')
160 expect(shared.written).toEqual([])
161 await second.host.close()
162 })
163
164 it('keeps the plugin state, and goes on from it', async () => {
165 const shared = sharedStores()
166 const config = { plugins: () => [counter] }
167 const first = await openOn(shared, config)
168 expect(await first.session.runCommand({ name: 'bump' })).toBe(1)
169 expect(await first.session.runCommand({ name: 'bump' })).toBe(2)
170 await first.host.close()
171
172 const second = await openOn(shared, config)
173
174 expect(second.session.snapshot().plugins).toEqual({
175 'test/counter': { count: 2, label: 'none' },
176 })
177 expect(await second.session.runCommand({ name: 'bump' })).toBe(3)
178 expect(shared.written).toEqual([])
179 await second.host.close()
180 })
181
182 it('keeps the interrupted turn, so a new host resolves it', async () => {
183 const shared = sharedStores()
184 const execute = vi.fn(async () => ({ removed: true }))
185 const remove = toolDefinition({
186 name: 'remove',
187 description: 'Remove a file',
188 needsApproval: true,
189 inputSchema: z.object({ path: z.string() }),
190 }).server(execute)
191 const first = await openOn(shared, { tools: [remove] }, [
192 () => toolCall('remove', { path: 'a.txt' }, 'call-1'),
193 ])
194 const stopped = await first.session.send('Remove a.txt.')
195 const [approval] = stopped.interrupts ?? []
196 if (!approval) throw new Error('The turn did not stop for approval.')
197 await first.host.close()
198 const stored = await storedThreadState(shared.persistence.stores.log, {
199 threadId: THREAD,
200 })
201 expect(stored.interrupted?.interrupts.map(({ id }) => id)).toEqual([
202 approval.id,
203 ])
204
205 const second = await openOn(shared, { tools: [remove] }, [
206 () => text('Removed.'),
207 ])
208 expect(second.session.snapshot()).toMatchObject({
209 status: 'requires_action',
210 pendingWaits: [{ waitId: approval.id, turn: true }],
211 })
212 const receipt = await second.session.resolve({
213 resume: [{ interruptId: approval.id, status: 'resolved', payload: true }],
214 })
215 await second.session.operation(receipt.operationId ?? '')
216
217 expect(execute).toHaveBeenCalledOnce()
218 expect(turnInterrupts(second.session.snapshot())).toEqual([])
219 const after = await storedThreadState(shared.persistence.stores.log, {
220 threadId: THREAD,
221 })
222 expect(after.interrupted).toBeNull()
223 expect(shared.written).toEqual([])
224 await second.host.close()
225 })
226
227 it('runs a turn that a host stopped again with its named overrides', async () => {
228 const shared = sharedStores()
229 const note: Array<ModelMessage> = [
230 { role: 'user', content: 'Today is Friday.' },
231 ]
232 const stalled = mockAdapter([untilAborted()])
233 const first = await openOn(
234 shared,
235 { models: { strong: stalled.adapter } },
236 [],
237 CRASHING_OWNERSHIP,
238 )
239 void first.session
240 .send('Plan the week.', {
241 inputId: 'in-1',
242 overrides: { model: 'strong', reasoning: HIGH },
243 systemPreamble: ['You plan weeks.'],
244 ephemeral: note,
245 })
246 .then(
247 () => {},
248 () => {},
249 )
250 await waitFor(() => expect(stalled.calls).toHaveLength(1))
251 // The first host stops: its ownership of the log expires.
252 await ownershipExpired()
253
254 const strong = mockAdapter([() => text('Monday: plan.')])
255 const second = await openOn(shared, { models: { strong: strong.adapter } })
256
257 expect(await second.session.settled({ inputId: 'in-1' })).toMatchObject({
258 outcome: 'completed',
259 })
260 // The named model ran it, not the harness adapter.
261 expect(second.calls).toHaveLength(0)
262 expect(strong.calls).toHaveLength(1)
263 const [call] = strong.calls
264 expect(call.reasoning).toEqual(HIGH)
265 expect(messageTexts(call)).toEqual(['Plan the week.', 'Today is Friday.'])
266 expect(JSON.stringify(call.systemPrompts)).toContain('You plan weeks.')
267 expect(shared.written).toEqual([])
268 await first.host.close().catch(() => {})
269 await second.host.close()
270 })
271
272 it('keeps the raw result of an agent run', async () => {
273 const shared = sharedStores()
274 // Longer than a model gets: the compacted copy would omit it.
275 const report = { summary: 'x'.repeat(3000), files: 2 }
276 const reporter = defineAgent({
277 name: 'reporter',
278 description: 'Reports',
279 run: async () => report,
280 })
281 const first = await openOn(shared, { agents: [reporter] })
282 const reporting = first.session.agent('reporter')
283 if (!reporting) throw new Error('The harness has no reporter.')
284 const run = reporting.start({})
285 expect(await run).toEqual(report)
286 await first.host.close()
287
288 const second = await openOn(shared, { agents: [reporter] })
289
290 expect(second.session.agentResult({ runId: run.id })).toEqual(report)
291 await expect(second.session.agentRun(run.id)).resolves.toEqual(report)
292 expect(second.session.agentResult({ runId: 'op-unknown' })).toBeUndefined()
293 expect(shared.written).toEqual([])
294 await second.host.close()
295 })
296})