Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import {
3 defaultSpawn,
4 mapSbxError,
5 parseJsonAfterBanner,
6 parseSbxLs,
7 runSbx,
8 sbxExecArgs,
9} from '../src/sbx/cli'
10import type { SbxSpawn } from '../src/sbx/cli'
11
12function trackingSignal(): { signal: AbortSignal; wasRemoved: () => boolean } {
13 const real = new AbortController()
14 let removed = false
15 const signal = Object.create(real.signal) as AbortSignal
16 const origAdd = real.signal.addEventListener.bind(real.signal)
17 const origRemove = real.signal.removeEventListener.bind(real.signal)
18 signal.addEventListener = ((
19 type: string,
20 listener: EventListenerOrEventListenerObject | null,
21 opts?: boolean | AddEventListenerOptions,
22 ) => {
23 if (listener) origAdd(type, listener, opts)
24 }) as AbortSignal['addEventListener']
25 signal.removeEventListener = ((
26 type: string,
27 listener: EventListenerOrEventListenerObject | null,
28 opts?: boolean | EventListenerOptions,
29 ) => {
30 removed = true
31 if (listener) origRemove(type, listener, opts)
32 }) as AbortSignal['removeEventListener']
33 return { signal, wasRemoved: () => removed }
34}
35
36function fakeSpawn(result: {
37 stdout?: string
38 stderr?: string
39 exitCode?: number
40 err?: NodeJS.ErrnoException
41}): SbxSpawn {
42 return (_bin, _args, opts) => {
43 queueMicrotask(() => {
44 if (result.err) {
45 opts.onError(result.err)
46 return
47 }
48 opts.onClose({
49 stdout: result.stdout ?? '',
50 stderr: result.stderr ?? '',
51 exitCode: result.exitCode ?? 0,
52 })
53 })
54 return { kill: () => {} }
55 }
56}
57
58describe('sbxExecArgs', () => {
59 it('puts flags before the sandbox name', () => {
60 expect(
61 sbxExecArgs('deadbeefdeadbeef', 'pwd', {
62 cwd: '/home/user/work',
63 env: { XAI_API_KEY: 'secret' },
64 }),
65 ).toEqual([
66 'exec',
67 '-w',
68 '/home/user/work',
69 '-e',
70 'XAI_API_KEY=secret',
71 '--',
72 'deadbeefdeadbeef',
73 'sh',
74 '-c',
75 'pwd',
76 ])
77 })
78
79 it('omits -w and -e when cwd and env are unset', () => {
80 expect(sbxExecArgs('deadbeefdeadbeef', 'pwd')).toEqual([
81 'exec',
82 '--',
83 'deadbeefdeadbeef',
84 'sh',
85 '-c',
86 'pwd',
87 ])
88 })
89})
90
91describe('runSbx', () => {
92 it('returns stdout on exit 0', async () => {
93 const result = await runSbx(['ls', '--json'], {
94 binary: 'sbx',
95 spawn: fakeSpawn({ stdout: '[]' }),
96 })
97 expect(result.stdout).toBe('[]')
98 expect(result.exitCode).toBe(0)
99 })
100
101 it('throws with install help when the binary is missing', async () => {
102 const err = Object.assign(new Error('spawn sbx ENOENT'), {
103 code: 'ENOENT',
104 })
105 const error = await runSbx(['ls'], {
106 binary: 'sbx',
107 spawn: fakeSpawn({ err }),
108 }).catch((caught: unknown) => caught)
109 expect(error).toBeInstanceOf(Error)
110 if (!(error instanceof Error)) {
111 throw new Error('expected Error')
112 }
113 expect(error.message).toContain('brew trust docker/tap')
114 expect(error.message).toContain('brew install docker/tap/sbx')
115 expect(error.message).toContain('HypervisorPlatform')
116 expect(error.message).toContain('winget install -h Docker.sbx')
117 expect(error.message).toContain('REPO_ONLY=1')
118 expect(error.message).toContain('apt-get install docker-sbx')
119 expect(error.message).toContain('kvm')
120 })
121
122 it('throws with login help when stderr says not logged in', async () => {
123 await expect(
124 runSbx(['ls'], {
125 binary: 'sbx',
126 spawn: fakeSpawn({
127 exitCode: 1,
128 stderr: 'Error: not logged in. Run sbx login',
129 }),
130 }),
131 ).rejects.toThrow(/sbx login --password-stdin/)
132 })
133
134 it('throws with login help when stderr says not authenticated', async () => {
135 await expect(
136 runSbx(['ls', '--json'], {
137 binary: 'sbx',
138 spawn: fakeSpawn({
139 exitCode: 1,
140 stderr:
141 'ERROR: Not authenticated to Docker\n\nSign in with: sbx login',
142 }),
143 }),
144 ).rejects.toThrow(/sbx login --password-stdin/)
145 })
146
147 it('throws with stderr on any other non-zero exit', async () => {
148 await expect(
149 runSbx(['create'], {
150 binary: 'sbx',
151 spawn: fakeSpawn({
152 exitCode: 2,
153 stderr: 'unknown template',
154 }),
155 }),
156 ).rejects.toThrow(/unknown template/)
157 })
158
159 it('does not treat guest exec stdout 401 Unauthorized as a login error', async () => {
160 const result = await runSbx(sbxExecArgs('name', 'echo unauthorized'), {
161 allowNonZero: true,
162 spawn: fakeSpawn({
163 exitCode: 1,
164 stdout: '401 Unauthorized',
165 }),
166 })
167 expect(result.exitCode).toBe(1)
168 expect(result.stdout).toBe('401 Unauthorized')
169 })
170
171 it('exec stderr unauthorized is NOT a login error', async () => {
172 const error = await runSbx(
173 sbxExecArgs('name', 'curl https://example.invalid'),
174 {
175 spawn: fakeSpawn({
176 exitCode: 1,
177 stderr: '401 unauthorized',
178 }),
179 },
180 ).catch((caught: unknown) => caught)
181 expect(error).toBeInstanceOf(Error)
182 if (!(error instanceof Error)) {
183 throw new Error('expected Error')
184 }
185 expect(error.message).toMatch(/unauthorized/)
186 expect(error.message).not.toContain('sbx login --password-stdin')
187 })
188
189 it('host ls stderr auth phrase IS a login error', async () => {
190 await expect(
191 runSbx(['ls'], {
192 binary: 'sbx',
193 spawn: fakeSpawn({
194 exitCode: 1,
195 stderr: 'Not authenticated to Docker',
196 }),
197 }),
198 ).rejects.toThrow(/sbx login --password-stdin/)
199 })
200})
201
202describe('parseSbxLs', () => {
203 it('reads a top-level array of { name }', () => {
204 expect(parseSbxLs('[{"name":"abc","status":"running"}]')).toEqual([
205 { name: 'abc', status: 'running' },
206 ])
207 })
208
209 it('reads { sandboxes: [...] }', () => {
210 expect(
211 parseSbxLs('{"sandboxes":[{"Name":"xyz","State":"stopped"}]}'),
212 ).toEqual([{ name: 'xyz', status: 'stopped' }])
213 })
214
215 it('strips a sandboxd banner then parses a JSON array', () => {
216 expect(parseSbxLs('sandboxd starting...\n[{"name":"abc"}]')).toEqual([
217 { name: 'abc' },
218 ])
219 })
220
221 it('strips a banner then parses { sandboxes: [...] }', () => {
222 expect(
223 parseSbxLs('sandboxd starting...\n{"sandboxes":[{"Name":"xyz"}]}'),
224 ).toEqual([{ name: 'xyz' }])
225 })
226})
227
228describe('mapSbxError', () => {
229 it('does not swallow a generic Error', () => {
230 expect(mapSbxError(new Error('boom'), 'sbx').message).toContain('boom')
231 })
232})
233
234describe('parseJsonAfterBanner', () => {
235 it('skips a brace in the banner and parses the later object', () => {
236 expect(
237 parseJsonAfterBanner(
238 'sandboxd starting {pid: 12}...\n{"sandboxes":[{"name":"abc"}]}',
239 ),
240 ).toEqual({ sandboxes: [{ name: 'abc' }] })
241 })
242
243 it('skips a bracket in the banner and parses the later array', () => {
244 expect(
245 parseJsonAfterBanner('log: saw [warn] token\n[{"name":"abc"}]'),
246 ).toEqual([{ name: 'abc' }])
247 })
248})
249
250describe('defaultSpawn', () => {
251 it('adds the abort listener before it reads signal.aborted', () => {
252 const order: Array<string> = []
253 const real = new AbortController()
254 real.abort()
255 const signal = Object.create(real.signal) as AbortSignal
256 Object.defineProperty(signal, 'aborted', {
257 get() {
258 order.push('check-aborted')
259 return true
260 },
261 })
262 signal.addEventListener = ((
263 type: string,
264 listener: EventListenerOrEventListenerObject | null,
265 opts?: boolean | AddEventListenerOptions,
266 ) => {
267 order.push('add-listener')
268 if (listener) real.signal.addEventListener(type, listener, opts)
269 }) as AbortSignal['addEventListener']
270 signal.removeEventListener = real.signal.removeEventListener.bind(
271 real.signal,
272 )
273 const handle = defaultSpawn(
274 'node',
275 ['-e', 'setTimeout(() => {}, 30_000)'],
276 {
277 signal,
278 onClose: () => {},
279 onError: () => {},
280 },
281 )
282 handle.kill()
283 expect(order[0]).toBe('add-listener')
284 expect(order).toContain('check-aborted')
285 })
286
287 it('removes the abort listener after close', async () => {
288 const { signal, wasRemoved } = trackingSignal()
289 await new Promise<void>((resolve, reject) => {
290 defaultSpawn('node', ['-e', 'process.exit(0)'], {
291 signal,
292 onClose: () => resolve(),
293 onError: (err) => reject(err),
294 })
295 })
296 expect(wasRemoved()).toBe(true)
297 })
298
299 it('removes the abort listener when kill() is called before close', async () => {
300 const { signal, wasRemoved } = trackingSignal()
301 const handle = defaultSpawn(
302 'node',
303 ['-e', 'setTimeout(() => {}, 30_000)'],
304 {
305 signal,
306 onClose: () => {},
307 onError: () => {},
308 },
309 )
310 handle.kill()
311 expect(wasRemoved()).toBe(true)
312 })
313})