Open History to see the last commit
1import { tmpdir } from 'node:os'
2import { join, resolve, sep } from 'node:path'
3import { createFileRoute } from '@tanstack/react-router'
4import { EventType } from '@tanstack/ai'
5import { createAnthropicChat } from '@tanstack/ai-anthropic'
6import {
7 createHarnessHost,
8 defineHarness,
9 definePlugin,
10 logIdOf,
11} from '@tanstack/ai-harness'
12import {
13 WorkspaceStranded,
14 hostBackend,
15 workspaceTools,
16} from '@tanstack/ai-harness/plugins/coding'
17import { memoryPersistence } from '@tanstack/ai-persistence'
18import { sandboxWorkspaceBackend } from '@tanstack/ai-sandbox/harness'
19import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
20import type { AnyTextAdapter } from '@tanstack/ai'
21import type { HarnessPersistence, HarnessPlugin } from '@tanstack/ai-harness'
22import type {
23 WorkspaceBinder,
24 WorkspaceBinding,
25} from '@tanstack/ai-harness/plugins/coding'
26
27/**
28 * The workspace of the coding tools for many threads and many hosts. Body:
29 * `{ scenario, root }`. `root` must be a folder in the temp folder that the
30 * test made. The answer is JSON with what the test checks.
31 *
32 * - `env`: `bash` prints a server env var. The command must not see it.
33 * - `other-root`: each thread gets its own folder in `root`. The thread
34 * `beta` tries to read a file of the thread `alpha`.
35 * - `sandbox-move`: a thread works in a local-process sandbox on `root`.
36 * Its host closes, and a second host continues the thread. The second
37 * host gets the sandbox from `reattach`, and does not call `bind`.
38 * - `stranded`: the same, but the second host has no `reattach`. The tool
39 * call fails, and the stranded event comes.
40 * - `pin`: hosts with `ownership.hostId`. A folder thread runs on `pod-a`.
41 * `pod-b` does not run the next input: it waits for `pod-a`, which runs
42 * it after a restart.
43 *
44 * A custom `fetch` answers with canned Anthropic streams, so no aimock
45 * fixture is needed.
46 */
47
48const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
49const MODEL = 'claude-sonnet-5-5'
50/** The server env var of the `env` scenario. */
51const SECRET_NAME = 'E2E_CODING_SERVER_SECRET'
52const SECRET_VALUE = 'server-only-value'
53
54type AnthropicEvent = { type: string } & Record<string, unknown>
55
56const sseOf = (events: Array<AnthropicEvent>) =>
57 events
58 .map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
59 .join('')
60
61const messageStart = (id: string): AnthropicEvent => ({
62 type: 'message_start',
63 message: {
64 id,
65 type: 'message',
66 role: 'assistant',
67 content: [],
68 model: MODEL,
69 stop_reason: null,
70 stop_sequence: null,
71 usage: { input_tokens: 5, output_tokens: 0 },
72 },
73})
74
75const ending = (stopReason: string): Array<AnthropicEvent> => [
76 { type: 'content_block_stop', index: 0 },
77 {
78 type: 'message_delta',
79 delta: { stop_reason: stopReason, stop_sequence: null },
80 usage: { output_tokens: 1 },
81 },
82 { type: 'message_stop' },
83]
84
85/** An answer that calls the tool `name` with `input`. */
86const call = (name: string, input: Record<string, unknown>) => (id: string) =>
87 sseOf([
88 messageStart(id),
89 {
90 type: 'content_block_start',
91 index: 0,
92 content_block: { type: 'tool_use', id: `toolu_${id}`, name, input: {} },
93 },
94 {
95 type: 'content_block_delta',
96 index: 0,
97 delta: {
98 type: 'input_json_delta',
99 partial_json: JSON.stringify(input),
100 },
101 },
102 ...ending('tool_use'),
103 ])
104
105/** An answer with the text `text`. */
106const reply = (text: string) => (id: string) =>
107 sseOf([
108 messageStart(id),
109 {
110 type: 'content_block_start',
111 index: 0,
112 content_block: { type: 'text', text: '' },
113 },
114 {
115 type: 'content_block_delta',
116 index: 0,
117 delta: { type: 'text_delta', text },
118 },
119 ...ending('end_turn'),
120 ])
121
122/**
123 * A model that answers with `answers`, in order. `calls` counts its
124 * requests. Each model needs its own `prefix`: the log keeps the result of
125 * each tool call id.
126 */
127function scriptedModel(prefix: string, answers: Array<(id: string) => string>) {
128 const counter = { calls: 0 }
129 const scriptedFetch: typeof fetch = async () => {
130 counter.calls += 1
131 const answer = answers[counter.calls - 1] ?? reply('No more answers.')
132 return new Response(answer(`msg_${prefix}_${counter.calls}`), {
133 headers: { 'Content-Type': 'text/event-stream' },
134 })
135 }
136 const adapter = createAnthropicChat(MODEL, DUMMY_KEY, {
137 fetch: scriptedFetch,
138 })
139 return { adapter, counter }
140}
141
142/** A model that reads `path` with `read_file`, then answers `text`. */
143const reader = (prefix: string, path: string, text: string) =>
144 scriptedModel(prefix, [call('read_file', { path }), reply(text)])
145
146/** A host on `persistence`, with `ownership.hostId` when `hostId` is set. */
147const hostOn = (persistence: HarnessPersistence, hostId?: string) =>
148 createHarnessHost({
149 persistence,
150 ...(hostId !== undefined ? { ownership: { hostId } } : {}),
151 })
152
153/** A harness with `adapter` and `plugins`. */
154const harnessOf = (adapter: AnyTextAdapter, plugins: Array<HarnessPlugin>) =>
155 defineHarness({
156 name: 'e2e/coding-workspace',
157 adapter,
158 plugins: () => plugins,
159 })
160
161/** Send `message` and read the turn. Gives the tool results that the client gets. */
162async function turnOf(
163 session: {
164 send: (message: string) => { stream: () => AsyncIterable<unknown> }
165 },
166 message: string,
167) {
168 const results: Array<string> = []
169 for await (const chunk of session.send(message).stream()) {
170 if (typeof chunk !== 'object' || chunk === null) continue
171 if (Reflect.get(chunk, 'type') === EventType.TOOL_CALL_RESULT) {
172 results.push(String(Reflect.get(chunk, 'content')))
173 }
174 }
175 return { results }
176}
177
178/** `bash` prints the server env var {@link SECRET_NAME}. */
179async function envScenario(root: string) {
180 // The server has the var. A command must not get it.
181 process.env[SECRET_NAME] = SECRET_VALUE
182 const model = scriptedModel('env', [
183 call('bash', {
184 command: `node -e "process.stdout.write('secret=' + (process.env.${SECRET_NAME} ?? 'unset'))"`,
185 }),
186 reply('The command ran.'),
187 ])
188 const host = hostOn(memoryPersistence())
189 try {
190 const session = await host.open(
191 harnessOf(model.adapter, [workspaceTools({ root, web: false })]),
192 { threadId: 'coding-env' },
193 )
194 const turn = await turnOf(session, 'print the secret')
195 return {
196 ...turn,
197 serverHasSecret: process.env[SECRET_NAME] === SECRET_VALUE,
198 }
199 } finally {
200 await host.close()
201 }
202}
203
204/**
205 * Each thread works in its own folder of `root`. The thread `alpha` reads
206 * its file. The thread `beta` tries the same file by its full path and by
207 * a relative path.
208 */
209async function otherRootScenario(root: string) {
210 const secret = join(root, 'alpha', 'secret.txt')
211 const workspace: WorkspaceBinder = {
212 bind: async ({ run }) => ({
213 ...hostBackend,
214 root: join(root, run.threadId),
215 }),
216 }
217 const alpha = reader('alpha', 'secret.txt', 'Read my file.')
218 const beta = scriptedModel('beta', [
219 call('read_file', { path: secret }),
220 call('read_file', { path: '../alpha/secret.txt' }),
221 reply('I cannot read it.'),
222 ])
223 const host = hostOn(memoryPersistence())
224 try {
225 const plugins = [workspaceTools({ workspace, web: false })]
226 const a = await host.open(harnessOf(alpha.adapter, plugins), {
227 threadId: 'alpha',
228 })
229 const b = await host.open(harnessOf(beta.adapter, plugins), {
230 threadId: 'beta',
231 })
232 return {
233 alpha: await turnOf(a, 'read your file'),
234 beta: await turnOf(b, 'read the file of alpha'),
235 }
236 } finally {
237 await host.close()
238 }
239}
240
241/**
242 * A thread in a local-process sandbox on `root` moves to a second host.
243 * With `withReattach`, the second host resumes the sandbox. Without it, the
244 * sandbox counts as gone.
245 */
246async function sandboxMoveScenario(root: string, withReattach: boolean) {
247 const provider = localProcessSandbox({ dir: root })
248 const persistence = memoryPersistence()
249 const threadId = 'coding-sandbox-move'
250 const bindOf = (counter: { calls: number }) => async () => {
251 counter.calls += 1
252 return {
253 ...sandboxWorkspaceBackend(await provider.create({})),
254 root: '/workspace',
255 }
256 }
257 const strandedOf = (list: Array<WorkspaceBinding>) =>
258 definePlugin({
259 name: 'e2e/stranded',
260 setup: (ctx) => {
261 ctx.on(WorkspaceStranded, (event) => list.push(event.binding))
262 },
263 })
264
265 // The first host binds the sandbox, and closes.
266 const firstBind = { calls: 0 }
267 const first = hostOn(persistence)
268 let firstTurn: Awaited<ReturnType<typeof turnOf>>
269 try {
270 const model = reader('first', 'notes.txt', 'Read notes.txt.')
271 const session = await first.open(
272 harnessOf(model.adapter, [
273 workspaceTools({ workspace: { bind: bindOf(firstBind) }, web: false }),
274 ]),
275 { threadId },
276 )
277 firstTurn = await turnOf(session, 'read notes.txt')
278 } finally {
279 await first.close()
280 }
281
282 // The second host continues the thread.
283 const bind = { calls: 0 }
284 const reattached: Array<WorkspaceBinding> = []
285 const stranded: Array<WorkspaceBinding> = []
286 const workspace: WorkspaceBinder = {
287 bind: bindOf(bind),
288 ...(withReattach
289 ? {
290 reattach: async ({ binding }) => {
291 reattached.push(binding)
292 if (binding.kind !== 'sandbox') return 'gone'
293 const handle = await provider.resume({ id: binding.sandboxId })
294 return handle
295 ? { ...sandboxWorkspaceBackend(handle), root: binding.root }
296 : 'gone'
297 },
298 }
299 : {}),
300 }
301 const second = hostOn(persistence)
302 try {
303 const model = reader('second', 'notes.txt', 'Read notes.txt again.')
304 const session = await second.open(
305 harnessOf(model.adapter, [
306 strandedOf(stranded),
307 workspaceTools({ workspace, web: false }),
308 ]),
309 { threadId },
310 )
311 const secondTurn = await turnOf(session, 'read notes.txt again')
312 return {
313 first: { ...firstTurn, bindCalls: firstBind.calls },
314 second: {
315 ...secondTurn,
316 bindCalls: bind.calls,
317 reattached,
318 stranded,
319 },
320 }
321 } finally {
322 await second.close()
323 }
324}
325
326/**
327 * A folder thread on hosts with `ownership.hostId`. `pod-a` runs the first
328 * turn. `pod-b` does not run the next input: the input waits for `pod-a`,
329 * and `pod-a` runs it after a restart with the same id.
330 */
331async function pinScenario(root: string) {
332 const persistence = memoryPersistence()
333 const threadId = 'coding-pin'
334 const tools = () => [workspaceTools({ root, web: false })]
335
336 const a = reader('pod_a', 'notes.txt', 'Read notes.txt on pod-a.')
337 const first = hostOn(persistence, 'pod-a')
338 try {
339 const session = await first.open(harnessOf(a.adapter, tools()), {
340 threadId,
341 })
342 await session.send('read notes.txt')
343 } finally {
344 await first.close()
345 }
346
347 const b = reader('pod_b', 'notes.txt', 'Read notes.txt on pod-b.')
348 const other = hostOn(persistence, 'pod-b')
349 const restarted = hostOn(persistence, 'pod-a')
350 try {
351 const session = await other.open(harnessOf(b.adapter, tools()), {
352 threadId,
353 })
354 const sent = Promise.resolve(session.send('read notes.txt again'))
355 // pod-b offers the input to the host of the thread.
356 const logId = logIdOf({ logId: threadId })
357 const deadline = Date.now() + 5000
358 let offers = 0
359 while (Date.now() < deadline) {
360 offers = (await persistence.stores.log.listOfferedInputs({ logId }))
361 .length
362 if (offers > 0) break
363 await new Promise((done) => setTimeout(done, 50))
364 }
365 const podBCallsBefore = b.counter.calls
366
367 // pod-a after a restart takes the input and runs it.
368 const again = reader(
369 'pod_a2',
370 'notes.txt',
371 'Read notes.txt on pod-a again.',
372 )
373 const view = await restarted.open(harnessOf(again.adapter, tools()), {
374 threadId,
375 })
376 // The send of pod-b ends when pod-a ran the input.
377 const podBSendEnded = await Promise.race([
378 sent.then(() => true),
379 new Promise<boolean>((done) => setTimeout(() => done(false), 10_000)),
380 ])
381 const transcript = await view.transcript()
382 const records = await persistence.stores.log.read({ logId })
383 return {
384 offers,
385 podBCalls: podBCallsBefore,
386 podBCallsAfter: b.counter.calls,
387 podBSendEnded,
388 restartedCalls: again.counter.calls,
389 answers: transcript
390 .filter((message) => message.role === 'assistant')
391 .map((message) =>
392 typeof message.content === 'string' ? message.content : '',
393 )
394 .filter((text) => text !== ''),
395 bindings: records
396 .map(({ record }) => record)
397 .filter((record) => record.type === 'harness.workspace.bound')
398 .map((record) => Reflect.get(record, 'binding')),
399 }
400 } finally {
401 await other.close()
402 await restarted.close()
403 }
404}
405
406export const Route = createFileRoute('/api/coding-workspace')({
407 server: {
408 handlers: {
409 POST: async ({ request }) => {
410 const body: unknown = await request.json()
411 const field = (name: string) =>
412 typeof body === 'object' && body !== null && name in body
413 ? Reflect.get(body, name)
414 : undefined
415 const scenario = field('scenario')
416 const rootField = field('root')
417 const root = typeof rootField === 'string' ? resolve(rootField) : ''
418 if (!root.startsWith(resolve(tmpdir()) + sep)) {
419 return new Response('root must be in the temp folder', {
420 status: 400,
421 })
422 }
423 try {
424 switch (scenario) {
425 case 'env':
426 return Response.json(await envScenario(root))
427 case 'other-root':
428 return Response.json(await otherRootScenario(root))
429 case 'sandbox-move':
430 return Response.json(await sandboxMoveScenario(root, true))
431 case 'stranded':
432 return Response.json(await sandboxMoveScenario(root, false))
433 case 'pin':
434 return Response.json(await pinScenario(root))
435 default:
436 return new Response('unknown scenario', { status: 400 })
437 }
438 } catch (error) {
439 return Response.json({
440 error: error instanceof Error ? error.message : String(error),
441 })
442 }
443 },
444 },
445 },
446})