-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathmanaged-container.test.ts
More file actions
636 lines (571 loc) · 20.4 KB
/
Copy pathmanaged-container.test.ts
File metadata and controls
636 lines (571 loc) · 20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/**
* @license
* Copyright 2025 BrowserOS
*/
import { afterEach, describe, expect, it } from 'bun:test'
import { mkdtempSync } from 'node:fs'
import { rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import {
ContainerNotReadyError,
type ContainerState,
ManagedContainer,
type ManagedContainerDeps,
type MountRoot,
PathOutsideMountsError,
ResetNotSupportedError,
} from '../../../../src/lib/container/managed'
import { ContainerNameInUseError } from '../../../../src/lib/vm/errors'
import type {
ContainerInfo,
ContainerSpec,
} from '../../../../src/lib/container/types'
interface FakeCli {
inspectContainer: (name: string) => Promise<ContainerInfo | null>
removeContainer: (name: string, opts?: { force?: boolean }) => Promise<void>
waitForContainerNameRelease: () => Promise<void>
createContainer: (spec: ContainerSpec) => Promise<void>
startContainer: (name: string) => Promise<void>
waitForContainerRunning: (name: string) => Promise<void>
exec: (name: string, cmd: string[]) => Promise<number>
}
interface FakeLoader {
ensureImageLoaded: (ref: string) => Promise<void>
}
interface FakeVm {
ensureReady: () => Promise<void>
getDefaultGateway: () => Promise<string>
}
class TestContainer extends ManagedContainer {
readonly descriptor = {
adapterId: 'test',
displayName: 'Test',
defaultImage: 'docker.io/test:latest',
containerName: 'test-container',
platforms: ['darwin' as NodeJS.Platform],
}
probeOutcome: boolean | Error = true
probeCalls = 0
protected mountRoots(): readonly MountRoot[] {
return [
{
hostPath: '/host/root',
containerPath: '/data/root',
kind: 'shared',
},
]
}
protected async buildContainerSpec(): Promise<ContainerSpec> {
return {
name: this.descriptor.containerName,
image: this.descriptor.defaultImage,
env: { FOO: 'bar' },
}
}
protected async readinessProbe(): Promise<boolean> {
this.probeCalls += 1
if (this.probeOutcome instanceof Error) throw this.probeOutcome
return this.probeOutcome
}
// Expose the protected helper for one specific test.
triggerErrored(message: string) {
// biome-ignore lint/complexity/useLiteralKeys: protected method access for tests
this['setState']('errored', message)
}
}
function makeFakeDeps(opts: { lockDir: string }): ManagedContainerDeps & {
fakeCli: FakeCli
fakeLoader: FakeLoader
fakeVm: FakeVm
} {
const fakeCli: FakeCli = {
inspectContainer: async () => ({
id: 'cid',
name: 'test-container',
image: 'docker.io/test:latest',
status: 'running',
running: true,
}),
removeContainer: async () => {},
waitForContainerNameRelease: async () => {},
createContainer: async () => {},
startContainer: async () => {},
waitForContainerRunning: async () => {},
exec: async () => 0,
}
const fakeLoader: FakeLoader = {
ensureImageLoaded: async () => {},
}
const fakeVm: FakeVm = {
ensureReady: async () => {},
getDefaultGateway: async () => '192.168.5.2',
}
return {
cli: fakeCli as unknown as ManagedContainerDeps['cli'],
loader: fakeLoader as unknown as ManagedContainerDeps['loader'],
vm: fakeVm as unknown as ManagedContainerDeps['vm'],
limactlPath: '/opt/homebrew/bin/limactl',
limaHome: '/Users/dev/.browseros/lima',
vmName: 'browseros-vm',
lockDir: opts.lockDir,
fakeCli,
fakeLoader,
fakeVm,
}
}
describe('ManagedContainer', () => {
const tempDirs: string[] = []
afterEach(async () => {
await Promise.all(
tempDirs.map((dir) => rm(dir, { recursive: true, force: true })),
)
tempDirs.length = 0
})
function mkTempDir(): string {
const dir = mkdtempSync(join(tmpdir(), 'managed-container-test-'))
tempDirs.push(dir)
return dir
}
describe('state machine', () => {
it('transitions through start() to running', async () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
const transitions: ContainerState[] = []
c.subscribeState((s) => transitions.push(s))
expect(c.getState()).toBe('not_installed')
await c.start()
expect(c.getState()).toBe('running')
// installing → starting → running (the base goes through these
// phases on every start).
expect(transitions).toEqual(['installing', 'starting', 'running'])
})
it('lands in errored when readiness probe returns false', async () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
c.probeOutcome = false
await expect(c.start()).rejects.toThrow(/probe failed/i)
expect(c.getState()).toBe('errored')
expect(c.getStatusSnapshot().lastError).toMatch(/probe failed/i)
})
it('stop() force-transitions to stopped even from errored', async () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
c.probeOutcome = false
await expect(c.start()).rejects.toThrow()
expect(c.getState()).toBe('errored')
await c.stop()
expect(c.getState()).toBe('stopped')
})
it('install() calls vm.ensureReady before loader.ensureImageLoaded (cold-boot regression)', async () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const calls: string[] = []
deps.fakeVm.ensureReady = async () => {
calls.push('vm.ensureReady')
}
deps.fakeLoader.ensureImageLoaded = async () => {
calls.push('loader.ensureImageLoaded')
}
const c = new TestContainer(deps)
await c.install()
expect(calls).toEqual(['vm.ensureReady', 'loader.ensureImageLoaded'])
expect(c.getState()).toBe('installed')
})
})
describe('execProcess gating', () => {
it('rejects with ContainerNotReadyError when not_installed', async () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
await expect(
c.execProcess({ argv: ['/bin/echo', 'hi'] }),
).rejects.toBeInstanceOf(ContainerNotReadyError)
try {
await c.execProcess({ argv: ['/bin/echo', 'hi'] })
} catch (err) {
if (err instanceof ContainerNotReadyError) {
expect(err.reason).toBe('not_installed')
expect(err.state).toBe('not_installed')
expect(err.containerId).toBe('test-container')
}
}
})
it('rejects with reason=errored when in errored state', async () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
c.triggerErrored('probe boom')
try {
await c.execProcess({ argv: ['/bin/echo', 'hi'] })
throw new Error('unreachable')
} catch (err) {
expect(err).toBeInstanceOf(ContainerNotReadyError)
if (err instanceof ContainerNotReadyError) {
expect(err.reason).toBe('errored')
expect(err.lastError).toBe('probe boom')
}
}
})
it('waits through starting and resolves when running', async () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
// Skip directly to a starting state without running the start
// pipeline, then flip to running asynchronously.
// biome-ignore lint/complexity/useLiteralKeys: test reaches into protected
c['setState']('starting')
// Ensure execProcess waits, not resolves immediately.
const execPromise = c.execProcess(
{
argv: ['/bin/echo', 'hi'],
env: { FOO: 'bar' },
},
{ execGateTimeoutMs: 1_000 },
)
// Flip to running on next tick — execProcess should resolve.
setTimeout(() => {
// biome-ignore lint/complexity/useLiteralKeys: test reaches into protected
c['setState']('running')
}, 10)
const proc = await execPromise
proc.kill()
// Bun spawned a real process — it will exit quickly. Drain so
// the test doesn't leak resources.
await proc.exited.catch(() => undefined)
})
it('rejects with reason=timeout when starting never resolves', async () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
// biome-ignore lint/complexity/useLiteralKeys: test reaches into protected
c['setState']('starting')
try {
await c.execProcess(
{ argv: ['/bin/echo', 'hi'] },
{ execGateTimeoutMs: 50 },
)
throw new Error('unreachable')
} catch (err) {
expect(err).toBeInstanceOf(ContainerNotReadyError)
if (err instanceof ContainerNotReadyError) {
expect(err.reason).toBe('timeout')
}
}
})
})
describe('buildExecArgv', () => {
it('produces the canonical limactl/nerdctl chain', () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
const out = c.buildExecArgv({
argv: ['/opt/hermes/.venv/bin/hermes', 'acp'],
env: { HERMES_HOME: '/data/agents/harness/a/home' },
})
// Single source of truth for the chain — pin the exact string
// so future edits are explicit.
expect(out).toBe(
[
'env',
'LIMA_HOME=/Users/dev/.browseros/lima',
'/opt/homebrew/bin/limactl',
'shell',
'--workdir',
'/',
'browseros-vm',
'--',
'nerdctl',
'exec',
'-i',
'-e',
'HERMES_HOME=/data/agents/harness/a/home',
'test-container',
'/opt/hermes/.venv/bin/hermes',
'acp',
].join(' '),
)
})
it('omits -e flags when env is empty', () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
const out = c.buildExecArgv({ argv: ['/bin/version'] })
expect(out).not.toContain('-e ')
expect(out).toContain('test-container /bin/version')
})
})
describe('reset', () => {
it('throws ResetNotSupportedError for every level', async () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
await expect(c.reset('soft')).rejects.toBeInstanceOf(
ResetNotSupportedError,
)
await expect(c.reset('wipe-agent')).rejects.toBeInstanceOf(
ResetNotSupportedError,
)
await expect(c.reset('hard')).rejects.toBeInstanceOf(
ResetNotSupportedError,
)
})
})
describe('path translation', () => {
it('round-trips host ↔ container paths under a declared mount', () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
const host = '/host/root/agents/a/home/file.txt'
const inContainer = c.toContainerPath(host)
expect(inContainer).toBe('/data/root/agents/a/home/file.txt')
expect(c.toHostPath(inContainer)).toBe(host)
})
it('rejects host paths outside any declared mount', () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
expect(() => c.toContainerPath('/etc/passwd')).toThrow(
PathOutsideMountsError,
)
expect(() => c.toHostPath('/proc/cpuinfo')).toThrow(
PathOutsideMountsError,
)
})
it('translates the mount root itself (no suffix)', () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
expect(c.toContainerPath('/host/root')).toBe('/data/root')
expect(c.toHostPath('/data/root')).toBe('/host/root')
})
})
describe('subscribeState', () => {
it('fires every transition and stops after unsubscribe', async () => {
const lockDir = mkTempDir()
const deps = makeFakeDeps({ lockDir })
const c = new TestContainer(deps)
const transitions: ContainerState[] = []
const unsubscribe = c.subscribeState((s) => transitions.push(s))
await c.start()
expect(transitions.at(-1)).toBe('running')
unsubscribe()
await c.stop()
// No new transitions recorded after unsubscribe.
expect(transitions.at(-1)).toBe('running')
})
})
describe('isImageCurrent', () => {
function attachImageRef(
deps: ReturnType<typeof makeFakeDeps>,
ref: string | null,
): void {
// biome-ignore lint/suspicious/noExplicitAny: extending the fake at runtime
;(deps.cli as any).containerImageRef = async () => ref
}
it('returns true when ref matches descriptor.defaultImage', async () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
attachImageRef(deps, 'docker.io/test:latest')
expect(await new TestContainer(deps).isImageCurrent()).toBe(true)
})
it('returns true for SHA-pinned variants of the expected ref', async () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
attachImageRef(deps, 'docker.io/test:latest@sha256:deadbeef')
expect(await new TestContainer(deps).isImageCurrent()).toBe(true)
})
it('returns false when ref differs', async () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
attachImageRef(deps, 'docker.io/test:older')
expect(await new TestContainer(deps).isImageCurrent()).toBe(false)
})
it('returns false when the container is missing', async () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
attachImageRef(deps, null)
expect(await new TestContainer(deps).isImageCurrent()).toBe(false)
})
})
describe('getLogs / tailLogs', () => {
it('getLogs collects lines from cli.runCommand', async () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
let captured: string[] = []
// biome-ignore lint/suspicious/noExplicitAny: extending the fake at runtime
;(deps.cli as any).runCommand = async (
args: string[],
onLog?: (line: string) => void,
) => {
captured = args
onLog?.('line-a')
onLog?.('line-b')
return { exitCode: 0, stdout: '', stderr: '' }
}
const c = new TestContainer(deps)
const lines = await c.getLogs(120)
expect(lines).toEqual(['line-a', 'line-b'])
expect(captured).toEqual(['logs', '-n', '120', 'test-container'])
})
it('getLogs returns [] when the container does not exist', async () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
// biome-ignore lint/suspicious/noExplicitAny: extending the fake at runtime
;(deps.cli as any).runCommand = async (
_args: string[],
onLog?: (line: string) => void,
) => {
onLog?.('Error: no such container: test-container')
return {
exitCode: 1,
stdout: '',
stderr: 'Error: no such container: test-container',
}
}
const lines = await new TestContainer(deps).getLogs()
expect(lines).toEqual([])
})
it('getLogs throws on non-zero exit that is not a no-such-container error', async () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
// biome-ignore lint/suspicious/noExplicitAny: extending the fake at runtime
;(deps.cli as any).runCommand = async () => ({
exitCode: 2,
stdout: '',
stderr: 'permission denied',
})
await expect(new TestContainer(deps).getLogs()).rejects.toThrow(
/exited 2.*permission denied/,
)
})
it('tailLogs returns the unsubscribe handle from cli.tailLogs', () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
let unsubscribed = false
let receivedName: string | null = null
// biome-ignore lint/suspicious/noExplicitAny: extending the fake at runtime
;(deps.cli as any).tailLogs = (name: string, _onLine: unknown) => {
receivedName = name
return () => {
unsubscribed = true
}
}
const c = new TestContainer(deps)
const stop = c.tailLogs(() => {})
expect(receivedName).toBe('test-container')
stop()
expect(unsubscribed).toBe(true)
})
})
describe('runOneShot', () => {
type OneShotFakes = {
removed: string[]
created: ContainerSpec[]
runCalls: string[][]
runResult: { exitCode: number; stdout: string; stderr: string }
}
function attachOneShotFakes(
deps: ReturnType<typeof makeFakeDeps>,
): OneShotFakes {
const state: OneShotFakes = {
removed: [],
created: [],
runCalls: [],
runResult: { exitCode: 0, stdout: 'hi', stderr: '' },
}
const cli = deps.cli as unknown as Record<string, unknown>
cli.removeContainer = async (
name: string,
_opts?: { force?: boolean },
) => {
state.removed.push(name)
}
cli.waitForContainerNameRelease = async () => {}
cli.createContainer = async (spec: ContainerSpec) => {
state.created.push(spec)
}
cli.runCommand = async (args: string[]) => {
state.runCalls.push(args)
return state.runResult
}
return state
}
it('creates a sibling -setup container with no ports/health and the requested argv', async () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
const fakes = attachOneShotFakes(deps)
const c = new TestContainer(deps)
const result = await c.runOneShot(['echo', 'hello'], {
env: { EXTRA: '1' },
})
expect(result).toEqual({ exitCode: 0, stdout: 'hi', stderr: '' })
expect(fakes.created).toHaveLength(1)
const setupSpec = fakes.created[0]
expect(setupSpec.name).toBe('test-container-setup')
expect(setupSpec.image).toBe('docker.io/test:latest')
expect(setupSpec.restart).toBe('no')
expect(setupSpec.ports).toBeUndefined()
expect(setupSpec.health).toBeUndefined()
expect(setupSpec.command).toEqual(['echo', 'hello'])
expect(setupSpec.env).toEqual({ FOO: 'bar', EXTRA: '1' })
expect(fakes.runCalls).toEqual([['start', '-a', 'test-container-setup']])
expect(
fakes.removed.filter((n) => n === 'test-container-setup'),
).toHaveLength(2)
})
it('force-removes the sibling even when the inner command throws', async () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
const fakes = attachOneShotFakes(deps)
const cli = deps.cli as unknown as Record<string, unknown>
cli.runCommand = async () => {
throw new Error('boom')
}
const c = new TestContainer(deps)
await expect(c.runOneShot(['noop'])).rejects.toThrow(/boom/)
expect(
fakes.removed.filter((n) => n === 'test-container-setup'),
).toHaveLength(2)
})
it('drops onLog calls fired by the underlying runCommand after a timeout', async () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
attachOneShotFakes(deps)
const cli = deps.cli as unknown as Record<string, unknown>
let capturedOnLog: ((line: string) => void) | undefined
cli.runCommand = async (
_args: string[],
onLog?: (line: string) => void,
) => {
capturedOnLog = onLog
await new Promise((resolve) => setTimeout(resolve, 100))
return { exitCode: 0, stdout: '', stderr: '' }
}
const seen: string[] = []
const c = new TestContainer(deps)
await expect(
c.runOneShot(['noop'], {
processTimeoutMs: 5,
onLog: (line) => seen.push(line),
}),
).rejects.toThrow(/exceeded timeout/)
capturedOnLog?.('post-timeout-line')
expect(seen).toEqual([])
})
it('retries createContainer on ContainerNameInUseError', async () => {
const deps = makeFakeDeps({ lockDir: mkTempDir() })
const fakes = attachOneShotFakes(deps)
const cli = deps.cli as unknown as Record<string, unknown>
let createAttempts = 0
cli.createContainer = async (spec: ContainerSpec) => {
createAttempts += 1
if (createAttempts < 2) {
throw new ContainerNameInUseError(
spec.name,
'nerdctl create',
1,
`container name "${spec.name}" is already used`,
)
}
fakes.created.push(spec)
}
const c = new TestContainer(deps)
await c.runOneShot(['echo'])
expect(createAttempts).toBe(2)
expect(fakes.created).toHaveLength(1)
})
})
})