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

coding-agents.test.ts

383 lines12.3 KB

1import { mkdtempSync, writeFileSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { describe, expect, it } from 'vitest'
5import { EventType } from '@tanstack/ai'
6import { memoryPersistence } from '@tanstack/ai-persistence'
7import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
8import { permissions } from '@tanstack/ai-harness/plugins'
9import { codingAgents } from '../src/harness'
10import { defineSandbox } from '../src/sandbox'
11import { InMemorySandboxInstanceStore } from '../src/instance-store'
12import { defineWorkspace } from '../src/workspace'
13import { makeFakeProvider } from './fakes'
14import type { AnyTextAdapter, StreamChunk } from '@tanstack/ai'
15​
16const now = () => Date.now()
17// A small local project the sandboxes start from.
18const project = mkdtempSync(join(tmpdir(), 'coding-agents-'))
19writeFileSync(join(project, 'README.md'), '# demo\n')
20const TYPES = {
21 providerOptions: {} as Record<string, unknown>,
22 inputModalities: ['text'] as readonly ['text'],
23 messageMetadataByModality: {
24 text: undefined as unknown,
25 image: undefined as unknown,
26 audio: undefined as unknown,
27 video: undefined as unknown,
28 document: undefined as unknown,
29 },
30 toolCapabilities: [] as ReadonlyArray<string>,
31 toolCallMetadata: undefined as unknown,
32 systemPromptMetadata: undefined as never,
34​
35function textChunks(content: string): Array<StreamChunk> {
36 return [
37 {
38 type: EventType.TEXT_MESSAGE_START,
39 messageId: `m-${content}`,
40 role: 'assistant',
41 timestamp: now(),
42 },
43 {
44 type: EventType.TEXT_MESSAGE_CONTENT,
45 messageId: `m-${content}`,
46 delta: content,
47 timestamp: now(),
48 },
49 {
50 type: EventType.TEXT_MESSAGE_END,
51 messageId: `m-${content}`,
52 timestamp: now(),
53 },
54 {
55 type: EventType.RUN_FINISHED,
56 runId: 'r',
57 threadId: 't',
58 timestamp: now(),
59 metadata: { tanstack: { finishReason: 'stop' } },
60 },
61 ]
63​
64/** A lead model that calls the given tools in one step, then answers. */
65function lead(steps: Array<Array<[string, string]>>) {
66 let call = 0
67 const adapter: AnyTextAdapter = {
68 kind: 'text',
69 name: 'lead',
70 model: 'lead',
71 '~types': TYPES,
72 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
73 chatStream: () => {
74 const step = steps[call]
75 call += 1
76 return (async function* (): AsyncGenerator<StreamChunk> {
77 yield {
78 type: EventType.RUN_STARTED,
79 runId: 'r',
80 threadId: 't',
81 timestamp: now(),
82 }
83 if (!step) {
84 yield* textChunks('lead done')
85 return
86 }
87 for (const [index, [tool, task]] of step.entries()) {
88 const id = `call-${call}-${index}`
89 yield {
90 type: EventType.TOOL_CALL_START,
91 toolCallId: id,
92 toolCallName: tool,
93 timestamp: now(),
94 }
95 yield {
96 type: EventType.TOOL_CALL_ARGS,
97 toolCallId: id,
98 delta: JSON.stringify({ task }),
99 timestamp: now(),
100 }
101 yield {
102 type: EventType.TOOL_CALL_END,
103 toolCallId: id,
104 timestamp: now(),
105 }
106 }
107 yield {
108 type: EventType.RUN_FINISHED,
109 runId: 'r',
110 threadId: 't',
111 timestamp: now(),
112 metadata: { tanstack: { finishReason: 'tool_calls' } },
113 }
114 })()
115 },
116 }
117 return adapter
119​
120/**
121 * A stand-in coding agent. It records each call, reports a new session id the
122 * way Claude Code does (`<name>.session-id`), and answers with the task.
123 */
124function codingAgent(name: string, options: { wait?: Promise<void> } = {}) {
125 const calls: Array<any> = []
126 const log: Array<string> = []
127 const adapter: AnyTextAdapter = {
128 kind: 'text',
129 name,
130 model: `${name}-model`,
131 '~types': TYPES,
132 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
133 chatStream: (chatOptions: any) => {
134 calls.push(chatOptions)
135 const index = calls.length
136 return (async function* (): AsyncGenerator<StreamChunk> {
137 log.push(`${name} start ${index}`)
138 yield {
139 type: EventType.RUN_STARTED,
140 runId: 'c',
141 threadId: 't',
142 timestamp: now(),
143 }
144 yield {
145 type: EventType.CUSTOM,
146 name: `${name}.session-id`,
147 value: { sessionId: `${name}-session-${index}` },
148 timestamp: now(),
149 }
150 if (options.wait) await options.wait
151 const task = String(chatOptions.messages.at(-1)?.content ?? '')
152 yield* textChunks(`${name} did: ${task}`)
153 log.push(`${name} end ${index}`)
154 })()
155 },
156 }
157 return { adapter, calls, log }
159​
160async function open(input: {
161 leadSteps: Array<Array<[string, string]>>
162 agents: Record<
163 string,
164 { adapter: AnyTextAdapter; planModelOptions?: Record<string, unknown> }
165 >
166 workspace?: 'shared' | 'per-agent'
167 persistence?: ReturnType<typeof memoryPersistence>
168}) {
169 const provider = makeFakeProvider()
170 const persistence = input.persistence ?? memoryPersistence()
171 const host = createHarnessHost({ persistence })
172 const harness = defineHarness({
173 name: 'test/coding-lead',
174 adapter: lead(input.leadSteps),
175 plugins: () => [
176 permissions(),
177 codingAgents({
178 sandbox: defineSandbox({
179 id: 'code',
180 provider,
181 workspace: defineWorkspace({
182 source: { type: 'local', path: project },
183 }),
184 }),
185 agents: Object.fromEntries(
186 Object.entries(input.agents).map(([name, agent]) => [
187 name,
188 { description: `The ${name} agent`, ...agent },
189 ]),
190 ),
191 ...(input.workspace ? { workspace: input.workspace } : {}),
192 // A store per test, so no test resumes a sandbox of another test.
193 sandboxOptions: { instances: new InMemorySandboxInstanceStore() },
194 }),
195 ],
196 })
197 const session = await host.open(harness, { threadId: 't' })
198 return { host, session, provider, persistence, harness }
200​
201describe('codingAgents', () => {
202 it('runs a delegate in the sandbox and resumes its session on the next call', async () => {
203 const claude = codingAgent('claude-code')
204 const { host, session, provider } = await open({
205 leadSteps: [
206 [['claude_code', 'add a test']],
207 [],
208 [['claude_code', 'fix the test']],
209 ],
210 agents: { claude_code: { adapter: claude.adapter } },
211 })
212 await session.send('first')
213 await session.send('second')
214​
215 expect(claude.calls).toHaveLength(2)
216 expect(claude.calls[0].messages).toEqual([
217 { role: 'user', content: 'add a test' },
218 ])
219 expect(claude.calls[0].modelOptions?.sessionId).toBeUndefined()
220 // The second call resumes the session the first call reported.
221 expect(claude.calls[1].modelOptions).toEqual({
222 sessionId: 'claude-code-session-1',
223 })
224 expect(claude.calls[0].threadId).toBe('t')
225 // One sandbox for the thread, created once.
226 expect(provider.calls.create).toBe(1)
227 await host.close()
228 })
229​
230 it('lists the delegates as session agents and forgets sessions with /fresh', async () => {
231 const claude = codingAgent('claude-code')
232 const codex = codingAgent('codex')
233 const { host, session } = await open({
234 leadSteps: [
235 [['claude_code', 'one']],
236 [],
237 [['codex', 'two']],
238 [],
239 [['claude_code', 'three']],
240 ],
241 agents: {
242 claude_code: { adapter: claude.adapter },
243 codex: { adapter: codex.adapter },
244 },
245 })
246 expect(session.registry.list().map((agent) => agent.name)).toEqual([
247 'claude_code',
248 'codex',
249 ])
250 await session.send('a')
251 await session.send('b')
252 expect(await session.runCommand({ name: 'fresh', input: 'nope' })).toBe(
253 'Unknown coding agent "nope". Agents: claude_code, codex.',
254 )
255 expect(
256 await session.runCommand({ name: 'fresh', input: 'claude_code' }),
257 ).toBe('claude_code starts a new session next time.')
258 await session.send('c')
259 expect(claude.calls[1].modelOptions?.sessionId).toBeUndefined()
260 expect(await session.runCommand({ name: 'fresh' })).toBe(
261 'Every coding agent starts a new session next time.',
262 )
263 await host.close()
264 })
265​
266 it('keeps sessions across a host restart', async () => {
267 const persistence = memoryPersistence()
268 const first = codingAgent('claude-code')
269 const before = await open({
270 leadSteps: [[['claude_code', 'start']]],
271 agents: { claude_code: { adapter: first.adapter } },
272 persistence,
273 })
274 await before.session.send('go')
275 await before.host.close()
276​
277 const second = codingAgent('claude-code')
278 const after = await open({
279 leadSteps: [[['claude_code', 'continue']]],
280 agents: { claude_code: { adapter: second.adapter } },
281 persistence,
282 })
283 await after.session.send('go on')
284 expect(second.calls[0].modelOptions).toEqual({
285 sessionId: 'claude-code-session-1',
286 })
287 await after.host.close()
288 })
289​
290 it('runs shared-workspace delegates one at a time, and per-agent ones side by side', async () => {
291 let release = () => {}
292 const gate = new Promise<void>((resolve) => (release = resolve))
293 const claude = codingAgent('claude-code', { wait: gate })
294 const codex = codingAgent('codex')
295 const shared = await open({
296 leadSteps: [],
297 agents: {
298 claude_code: { adapter: claude.adapter },
299 codex: { adapter: codex.adapter },
300 },
301 })
302 // Two background runs at once, like two /agent commands.
303 const first = shared.session.agent('claude_code')?.start({ task: 'edit a' })
304 const second = shared.session.agent('codex')?.start({ task: 'edit b' })
305 await new Promise((resolve) => setTimeout(resolve, 30))
306 // Codex waits for the lock while Claude Code holds the shared workspace.
307 expect(claude.calls).toHaveLength(1)
308 expect(codex.calls).toHaveLength(0)
309 release()
310 await first
311 await second
312 expect(codex.calls).toHaveLength(1)
313 expect(codex.calls[0].threadId).toBe('t')
314 expect(shared.provider.calls.create).toBe(1)
315 await shared.host.close()
316​
317 let releaseSlow = () => {}
318 const slowGate = new Promise<void>((resolve) => (releaseSlow = resolve))
319 const slow = codingAgent('claude-code', { wait: slowGate })
320 const fast = codingAgent('codex')
321 const apart = await open({
322 leadSteps: [],
323 agents: {
324 claude_code: { adapter: slow.adapter },
325 codex: { adapter: fast.adapter },
326 },
327 workspace: 'per-agent',
328 })
329 const slowRun = apart.session
330 .agent('claude_code')
331 ?.start({ task: 'edit a' })
332 const fastRun = apart.session.agent('codex')?.start({ task: 'edit b' })
333 await fastRun
334 // Codex finished while Claude Code still works in its own sandbox.
335 expect(fast.calls[0].threadId).toBe('t:codex')
336 expect(slow.log).toEqual(['claude-code start 1'])
337 releaseSlow()
338 await slowRun
339 expect(slow.calls[0].threadId).toBe('t:claude_code')
340 expect(apart.provider.calls.create).toBe(2)
341 await apart.host.close()
342 })
343​
344 it('starts delegates read-only in plan mode, and refuses one without plan options', async () => {
345 const claude = codingAgent('claude-code')
346 const codex = codingAgent('codex')
347 const other = codingAgent('grok-build')
348 const custom = codingAgent('acp')
349 const { host, session } = await open({
350 // Two steps: tool calls in one step run at the same time, and the
351 // harness runs at most 3 subagents at once.
352 leadSteps: [
353 [
354 ['claude_code', 'look'],
355 ['codex', 'look'],
356 ['grok', 'look'],
357 ],
358 [['custom', 'look']],
359 ],
360 agents: {
361 claude_code: { adapter: claude.adapter },
362 codex: { adapter: codex.adapter },
363 grok: { adapter: other.adapter },
364 custom: {
365 adapter: custom.adapter,
366 planModelOptions: { readOnly: true },
367 },
368 },
369 })
370 await session.setPluginSetting({ key: 'mode', value: 'plan' })
371 await session.send('plan it')
372 expect(claude.calls[0].modelOptions).toMatchObject({
373 permissionMode: 'plan',
374 })
375 expect(codex.calls[0].modelOptions).toMatchObject({
376 sandboxMode: 'read-only',
377 })
378 // No plan options for grok-build: it does not run in plan mode.
379 expect(other.calls).toHaveLength(0)
380 expect(custom.calls[0].modelOptions).toMatchObject({ readOnly: true })
381 await host.close()
382 })
383})