Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { createSandboxComputerDriver, sandboxComputer } from '../src/index'
3import type {
4 ExecResult,
5 SandboxHandle,
6 SandboxProvider,
7} from '@tanstack/ai-sandbox'
8
9const PNG = new Uint8Array([137, 80, 78, 71])
10const PNG_BASE64 = 'iVBORw=='
11const XDPYINFO =
12 'name of display: :0\n dimensions: 1024x768 pixels (271x203 millimeters)\n'
13
14interface FakeOptions {
15 /** Whether an X display already runs. */
16 running?: boolean
17 /** Tools that `command -v` does not find. */
18 missing?: Array<string>
19 /** The size xdpyinfo reports. */
20 size?: string
21}
22
23/** A fake sandbox. Each command adds one line to `calls`, prefixed with `exec` or `spawn`. */
24function fakeSandbox({ running = true, missing = [], size }: FakeOptions = {}) {
25 const calls: Array<string> = []
26 let started = running
27 const ok = (stdout = ''): ExecResult => ({ stdout, stderr: '', exitCode: 0 })
28 const exec = vi.fn(async (command: string): Promise<ExecResult> => {
29 calls.push(`exec ${command}`)
30 if (command.startsWith('for t in')) return ok(missing.join('\n'))
31 if (command.endsWith('xdpyinfo >/dev/null 2>&1')) {
32 return started ? ok() : { stdout: '', stderr: '', exitCode: 1 }
33 }
34 if (command.endsWith('xdpyinfo')) {
35 return ok(size ? XDPYINFO.replace('1024x768', size) : XDPYINFO)
36 }
37 if (command.includes('base64 -w0')) return ok(`${PNG_BASE64}\n`)
38 if (command.endsWith('getmouselocation')) {
39 return ok('x:12 y:34 screen:0 window:1\n')
40 }
41 return ok()
42 })
43 const spawn = vi.fn(async (command: string) => {
44 calls.push(`spawn ${command}`)
45 if (command.startsWith('Xvfb')) started = true
46 return {} as never
47 })
48 const destroy = vi.fn(async () => {
49 calls.push('destroy')
50 })
51 const sandbox = {
52 process: { exec, spawn },
53 destroy,
54 } as unknown as SandboxHandle
55 return { sandbox, calls, exec, destroy }
56}
57
58/** A driver on a sandbox whose display already runs. `calls` holds only the actions. */
59async function setup() {
60 const fake = fakeSandbox()
61 const driver = await createSandboxComputerDriver({ sandbox: fake.sandbox })
62 fake.calls.length = 0
63 return { driver, calls: fake.calls }
64}
65
66function fakeProvider(fakes: Array<ReturnType<typeof fakeSandbox>>) {
67 let next = 0
68 const provider = {
69 name: 'fake',
70 create: vi.fn(async () => {
71 const fake = fakes[next++]
72 if (!fake) throw new Error('no more sandboxes')
73 return fake.sandbox
74 }),
75 } as unknown as SandboxProvider
76 return provider
77}
78
79describe('createSandboxComputerDriver', () => {
80 it('uses a display that already runs and reports linux', async () => {
81 const { sandbox, calls } = fakeSandbox()
82 const driver = await createSandboxComputerDriver({ sandbox })
83 expect(driver.display).toEqual({ width: 1024, height: 768 })
84 expect(driver.environment).toBe('linux')
85 expect('zoom' in driver).toBe(false)
86 expect(calls.some((call) => call.startsWith('spawn'))).toBe(false)
87 })
88
89 it('starts Xvfb and the session when no display runs', async () => {
90 const { sandbox, calls } = fakeSandbox({ running: false })
91 await createSandboxComputerDriver({
92 sandbox,
93 display: { width: 800, height: 600 },
94 })
95 const spawns = calls.filter((call) => call.startsWith('spawn'))
96 expect(spawns).toEqual([
97 'spawn Xvfb :0 -ac -screen 0 800x600x24 -nolisten tcp >/dev/null 2>&1',
98 'spawn command -v startxfce4 >/dev/null && DISPLAY=:0 startxfce4 >/dev/null 2>&1',
99 ])
100 })
101
102 it('names the missing desktop tools', async () => {
103 const { sandbox } = fakeSandbox({ missing: ['xdotool', 'scrot'] })
104 await expect(createSandboxComputerDriver({ sandbox })).rejects.toThrow(
105 'The sandbox has no desktop tools: xdotool, scrot.',
106 )
107 })
108
109 it('takes screenshots with ImageMagick import when the image has no scrot', async () => {
110 const fake = fakeSandbox({ missing: ['@import'] })
111 const driver = await createSandboxComputerDriver({ sandbox: fake.sandbox })
112 fake.calls.length = 0
113 expect(await driver.screenshot()).toEqual(PNG)
114 expect(fake.calls[0]).toMatch(
115 /^exec DISPLAY=:0 import -window root \/tmp\/tanstack-screenshot-\S+\.png && base64 -w0 /,
116 )
117 })
118
119 it('throws with the exit code and stderr when a command fails', async () => {
120 const { sandbox, exec } = fakeSandbox()
121 const driver = await createSandboxComputerDriver({ sandbox })
122 exec.mockResolvedValueOnce({ stdout: '', stderr: 'no X', exitCode: 1 })
123 await expect(driver.move(1, 2)).rejects.toThrow(
124 'Sandbox command failed with exit code 1: DISPLAY=:0 xdotool mousemove 1 2\nno X',
125 )
126 })
127
128 it('decodes the screenshot and deletes the file in one command', async () => {
129 const { driver, calls } = await setup()
130 expect(await driver.screenshot()).toEqual(PNG)
131 expect(calls).toHaveLength(1)
132 expect(calls[0]).toMatch(
133 /^exec DISPLAY=:0 scrot --pointer (\/tmp\/tanstack-screenshot-\S+\.png) && base64 -w0 \1; code=\$\?; rm -f \1; exit \$code$/,
134 )
135 })
136
137 it('reads the cursor position', async () => {
138 const { driver } = await setup()
139 expect(await driver.cursorPosition?.()).toEqual({ x: 12, y: 34 })
140 })
141
142 it.each([
143 ['left', 1, 1],
144 ['left', 2, 1],
145 ['right', 1, 3],
146 ['middle', 1, 2],
147 ['back', 1, 8],
148 ['forward', 1, 9],
149 ] as const)('clicks %s x%i in one command', async (button, count, number) => {
150 const { driver, calls } = await setup()
151 await driver.click(0, 5, { button, count })
152 expect(calls).toEqual([
153 `exec DISPLAY=:0 xdotool mousemove 0 5 click --repeat ${count} ${number}`,
154 ])
155 })
156
157 it('rounds a coordinate to the nearest pixel', async () => {
158 const { driver, calls } = await setup()
159 await driver.move(1.5, 2.2)
160 expect(calls).toEqual(['exec DISPLAY=:0 xdotool mousemove 2 2'])
161 })
162
163 it('presses and releases buttons', async () => {
164 const { driver, calls } = await setup()
165 await driver.mouseDown('left')
166 await driver.mouseUp('forward')
167 expect(calls).toEqual([
168 'exec DISPLAY=:0 xdotool mousedown 1',
169 'exec DISPLAY=:0 xdotool mouseup 9',
170 ])
171 })
172
173 it('scrolls down and right in 100 px clicks', async () => {
174 const { driver, calls } = await setup()
175 await driver.scroll(5, 6, 200, 300)
176 expect(calls).toEqual([
177 'exec DISPLAY=:0 xdotool mousemove 5 6 click --repeat 3 5 click --repeat 2 7',
178 ])
179 })
180
181 it('scrolls up and left, at least one click', async () => {
182 const { driver, calls } = await setup()
183 await driver.scroll(5, 6, -10, -40)
184 expect(calls).toEqual([
185 'exec DISPLAY=:0 xdotool mousemove 5 6 click --repeat 1 4 click --repeat 1 6',
186 ])
187 })
188
189 it('maps key names to xdotool names', async () => {
190 const { driver, calls } = await setup()
191 await driver.press(['Control', 'Shift', 'ArrowLeft'])
192 await driver.press([' '])
193 await driver.keyDown('Meta')
194 await driver.keyUp('Enter')
195 expect(calls).toEqual([
196 "exec DISPLAY=:0 xdotool key -- 'ctrl+shift+Left'",
197 "exec DISPLAY=:0 xdotool key -- 'space'",
198 "exec DISPLAY=:0 xdotool keydown -- 'super'",
199 "exec DISPLAY=:0 xdotool keyup -- 'Return'",
200 ])
201 })
202
203 it('quotes a key name with shell characters', async () => {
204 const { driver, calls } = await setup()
205 await driver.keyDown("a'; rm -rf / #")
206 expect(calls).toEqual([
207 `exec DISPLAY=:0 xdotool keydown -- 'a'"'"'; rm -rf / #'`,
208 ])
209 })
210
211 it('types quoted text in chunks of 25 characters in one command', async () => {
212 const { driver, calls } = await setup()
213 await driver.type(`${'a'.repeat(25)}it's`)
214 expect(calls).toEqual([
215 `exec DISPLAY=:0 xdotool type --delay 75 -- '${'a'.repeat(25)}' && DISPLAY=:0 xdotool type --delay 75 -- 'it'"'"'s'`,
216 ])
217 })
218
219 it('sends nothing for empty text', async () => {
220 const { driver, calls } = await setup()
221 await driver.type('')
222 expect(calls).toEqual([])
223 })
224})
225
226describe('sandboxComputer', () => {
227 it('reports a linux desktop with cursor position only', () => {
228 const factory = sandboxComputer({ provider: fakeProvider([]) })
229 expect(factory.display).toEqual({ width: 1024, height: 768 })
230 expect(factory.environment).toBe('linux')
231 expect(factory.capabilities).toEqual({
232 zoom: false,
233 cursorPosition: true,
234 navigate: false,
235 })
236 expect(factory.close).toBeUndefined()
237 })
238
239 it('creates one sandbox for each thread', async () => {
240 const fakes = [fakeSandbox(), fakeSandbox()]
241 const factory = sandboxComputer({ provider: fakeProvider(fakes) })
242 const a = await factory.create({ threadId: 'a' })
243 const b = await factory.create({ threadId: 'b' })
244 for (const fake of fakes) fake.calls.length = 0
245 await a.move(1, 2)
246 await b.move(3, 4)
247 expect(fakes.map(({ calls }) => calls)).toEqual([
248 ['exec DISPLAY=:0 xdotool mousemove 1 2'],
249 ['exec DISPLAY=:0 xdotool mousemove 3 4'],
250 ])
251 })
252
253 it('destroys only the sandbox of the closed driver', async () => {
254 const fakes = [fakeSandbox(), fakeSandbox()]
255 const factory = sandboxComputer({ provider: fakeProvider(fakes) })
256 const a = await factory.create({ threadId: 'a' })
257 await factory.create({ threadId: 'b' })
258 await a.close?.()
259 expect(fakes[0]?.destroy).toHaveBeenCalledOnce()
260 expect(fakes[1]?.destroy).not.toHaveBeenCalled()
261 })
262
263 it('destroys the sandbox when the running display has another size', async () => {
264 const fake = fakeSandbox({ size: '1280x800' })
265 const factory = sandboxComputer({ provider: fakeProvider([fake]) })
266 await expect(factory.create({ threadId: 'a' })).rejects.toThrow(
267 'The sandbox display is 1280x800, not 1024x768.',
268 )
269 expect(fake.destroy).toHaveBeenCalledOnce()
270 })
271
272 it('keeps the setup error when the destroy throws', async () => {
273 const error = vi.spyOn(console, 'error').mockImplementation(() => {})
274 const fake = fakeSandbox({ missing: ['scrot'] })
275 fake.destroy.mockRejectedValueOnce(new Error('destroy failed'))
276 const factory = sandboxComputer({ provider: fakeProvider([fake]) })
277 await expect(factory.create({ threadId: 'a' })).rejects.toThrow(
278 'The sandbox has no desktop tools: scrot.',
279 )
280 expect(error).toHaveBeenCalledWith(
281 'Failed to destroy the sandbox after setup failed.',
282 expect.any(Error),
283 )
284 error.mockRestore()
285 })
286})