Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

4.4 KB
Raw Blame
/*
 * Copyright 2026 BoxLite AI
 * SPDX-License-Identifier: AGPL-3.0
 */

import { validateSync } from 'class-validator'
import { RunnerService } from './runner.service'
import { RunnerHealthcheckDto } from '../dto/runner-health.dto'
import { RunnerState } from '../enums/runner-state.enum'
import type { Runner } from '../entities/runner.entity'

describe('RunnerService.findAvailableRunners capability filtering', () => {
  const capable = { id: 'memory-runner', availabilityScore: 50, capabilities: ['filestore', 'memory_checkpoint'] }
  const undeclared = { id: 'undeclared-runner', availabilityScore: 90, capabilities: null }
  const unrelated = { id: 'filestore-runner', availabilityScore: 80, capabilities: ['filestore'] }

  function serviceWithRunners(runners: Pick<Runner, 'id' | 'availabilityScore' | 'capabilities'>[]): RunnerService {
    const service = Object.create(RunnerService.prototype) as RunnerService
    return Object.assign(service, { runnerRepository: { find: jest.fn().mockResolvedValue(runners) } })
  }

  it('excludes runners with no declaration or without the required capability', async () => {
    const service = serviceWithRunners([undeclared, capable, unrelated])
    await expect(
      service.findAvailableRunners({ availabilityScoreThreshold: 1, requiredCapability: 'memory_checkpoint' }),
    ).resolves.toEqual([capable])
  })

  it('filters out higher-scoring incompatible runners before taking the top ten', async () => {
    const incompatible = Array.from({ length: 10 }, (_, index) => ({ ...unrelated, id: `filestore-${index}` }))
    const service = serviceWithRunners([...incompatible, capable])
    await expect(
      service.findAvailableRunners({ availabilityScoreThreshold: 1, requiredCapability: 'memory_checkpoint' }),
    ).resolves.toEqual([capable])
  })

  it('keeps runners regardless of capability when none is required', async () => {
    const service = serviceWithRunners([capable, unrelated, undeclared])
    await expect(service.findAvailableRunners({ availabilityScoreThreshold: 1 })).resolves.toEqual([
      undeclared,
      unrelated,
      capable,
    ])
  })
})

describe('Runner capability declarations', () => {
  it.each([[undefined], [['filestore']], [[]]] as [string[] | undefined][])(
    'persists declaration %p verbatim, absent as null',
    async (capabilities) => {
      const service = Object.create(RunnerService.prototype) as RunnerService
      const write = jest.fn().mockResolvedValue(true)
      Object.assign(service, {
        logger: { debug: jest.fn() },
        findOne: jest.fn().mockResolvedValue({ id: 'runner', state: RunnerState.READY }),
        updateRunnerUnlessDecommissioned: write,
        eventEmitter: { emit: jest.fn() },
      })
      await service.updateRunnerHealth('runner', undefined, undefined, undefined, undefined, undefined, 'dev', false, {
        capabilities,
      })
      expect((service as any).logger.debug).toHaveBeenCalledWith(
        expect.objectContaining({
          event: 'runner.health.persisted',
          runnerId: 'runner',
          appVersion: 'dev',
          capabilities: capabilities ?? [],
          infoFailed: false,
        }),
        'Runner health persisted',
      )
      expect(write).toHaveBeenCalledWith(
        'runner',
        expect.objectContaining({
          capabilities: capabilities ?? null,
        }),
      )
    },
  )

  it('does not replace capabilities after an info-read failure', async () => {
    const service = Object.create(RunnerService.prototype) as RunnerService
    const write = jest.fn().mockResolvedValue(true)
    Object.assign(service, {
      logger: { debug: jest.fn() },
      findOne: jest.fn().mockResolvedValue({ id: 'runner', state: RunnerState.READY }),
      updateRunnerUnlessDecommissioned: write,
      eventEmitter: { emit: jest.fn() },
    })
    await service.updateRunnerHealth(
      'runner',
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      { infoFailed: true, capabilities: ['filestore'] },
    )
    expect(write.mock.calls[0][1]).not.toHaveProperty('capabilities')
  })

  it.each([null, 'filestore', 1, ['filestore', 1]])(
    'rejects invalid capabilities %p on the heartbeat boundary',
    (value) => {
      const dto = Object.assign(new RunnerHealthcheckDto(), {
        appVersion: 'dev',
        capabilities: value,
      })
      expect(validateSync(dto).map((error) => error.property)).toEqual(expect.arrayContaining(['capabilities']))
    },
  )
})