Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

10.5 KB
Raw Blame
import { afterEach, describe, expect, it, vi } from 'vitest'
import { SERVICE_RUNNERS, startServiceProcess, type ServiceProcessOptions } from './serviceProcess.js'
import type { ServiceHost, ServiceHostOptions, ServiceProcess } from './services/process.js'
import { KNOWN_SERVICES, UPDATER_HOST } from './harnessd/services.js'

const local = vi.hoisted(() => ({ socket: '/data/daemon-18473.sock' as string | null }))
vi.mock('./lib/localSocket.js', async (real) => ({ ...await real<object>(), unixSocketPath: () => local.socket }))
// The test's own console stays as it is: it is shared with every other test in this worker.
const stamped = vi.hoisted(() => ({ times: 0 }))
vi.mock('./lib/log.js', async (real) => ({ ...await real<object>(), installTimestampedConsole: () => { stamped.times++ } }))
// What the master said leaves process.env as the process starts (lib/harnessdEnv.ts): held here, as there,
// but in a store each test starts empty, since the process is every test's in this worker.
const harnessd = vi.hoisted(() => ({ held: {} as Record<string, string> }))
vi.mock('./lib/harnessdEnv.js', async (real) => {
  const actual = await real<typeof import('./lib/harnessdEnv.js')>()
  return {
    ...actual,
    holdHarnessdEnv: () => {
      for (const name of Object.keys(process.env).filter(actual.isHarnessdVariable)) {
        harnessd.held[name] = process.env[name]!
        delete process.env[name]
      }
    },
    harnessdEnv: () => ({ ...process.env, ...harnessd.held }),
  }
})

describe('a service in its own process', () => {
  const title = process.title
  afterEach(() => { process.title = title; local.socket = '/data/daemon-18473.sock'; harnessd.held = {}; vi.restoreAllMocks() })

  it('can run every service the master knows, and the updater it runs beside them, and loads each one\'s runner on its own', async () => {
    expect([...SERVICE_RUNNERS.keys()].sort()).toEqual([...KNOWN_SERVICES, ...UPDATER_HOST.services].sort())
    for (const [name, load] of SERVICE_RUNNERS) expect(typeof await load(), name).toBe('function')
    // Every service's own code, imported: seconds on a loaded machine, not the default five.
  }, 60_000)

  /** A process that touches no channel, signal or exit: what it was asked to run, and what it was given. */
  const fakeHost = () => {
    const hosted: Array<{ options: ServiceHostOptions; services: ServiceProcess[] }> = []
    const host = (options: ServiceHostOptions): ServiceHost => {
      const entry = { options, services: [] as ServiceProcess[] }
      hosted.push(entry)
      return { add: (service) => { entry.services.push(service) }, leave: () => {} }
    }
    return { host, hosted }
  }

  it('runs the one it is named, against the core\'s socket, with the master\'s token', async () => {
    const seen: ServiceProcessOptions[] = []
    const handle = { stop: vi.fn() }
    const loaded: string[] = []
    // What a service would hand anything it starts (a viewer's server, an engine), as it loads.
    const inherited: Array<string | undefined> = []
    const runners = new Map([
      ['search', async () => { loaded.push('search'); inherited.push(process.env.HARNESSD_SERVICE_TOKEN); return (options: ServiceProcessOptions) => { seen.push(options); return handle } }],
      ['viewers', async () => { loaded.push('viewers'); return () => handle }],
    ])
    const { host, hosted } = fakeHost()
    process.env.HARNESSD_SERVICE_TOKEN = 'token'
    try {
      await startServiceProcess('search', { runners, host })
    } finally { delete process.env.HARNESSD_SERVICE_TOKEN }
    expect(loaded).toEqual(['search'])
    // The token is the service's to connect with, and no child's: out of process.env before any service loads.
    expect(inherited).toEqual([undefined])
    expect(process.title).toBe('harnessd-search')
    // Its lines are stamped like the core's and the master's in the log they share.
    expect(stamped.times).toBe(1)
    expect(seen).toEqual([{ dataDir: expect.any(String), socketPath: '/data/daemon-18473.sock', machineId: expect.any(String), token: 'token' }])
    expect(hosted).toEqual([{ options: { name: 'search', services: ['search'] }, services: [handle] }])
  })

  it('runs several in one process, as its master names it, each started on its own; stopping it stops each', async () => {
    const started: string[] = []
    const stops = { workspaces: vi.fn(), usage: vi.fn(async () => {}) }
    const runners = new Map(Object.entries(stops).map(([name, stop]) => [name, async () => () => { started.push(name); return { stop } }]))
    const { host, hosted } = fakeHost()
    process.env.HARNESSD_SERVICE = 'edge'
    try {
      const running = await startServiceProcess(' workspaces,usage ,workspaces', { runners, host })
      await running.stop()
    } finally { delete process.env.HARNESSD_SERVICE }
    expect(started).toEqual(['workspaces', 'usage'])
    expect(process.title).toBe('harnessd-edge')
    expect(hosted[0].options).toEqual({ name: 'edge', services: ['workspaces', 'usage'] })
    expect(hosted[0].services).toHaveLength(2)
    expect(stops.workspaces).toHaveBeenCalledOnce()
    expect(stops.usage).toHaveBeenCalledOnce()
  })

  // The review of #1765: with the Swarm off, the edge host still loaded its retention and the agent cleanup kept its
  // members. Its side is loaded only on, only for a service that acts on it, and handed to it there.
  it('hands the Swarm\'s side only to the services that act on it, only while the Swarm is on', async () => {
    const swarm = { retainedHarnesses: () => new Set(['member']) } as never
    const load = vi.fn(async () => swarm)
    const run = async (named: string, env: Record<string, string | undefined>) => {
      const seen: ServiceProcessOptions[] = []
      const runners = new Map(['agentCleanup', 'sharing', 'handoff', 'models', 'search', 'workspaces'].map(name =>
        [name, async () => (options: ServiceProcessOptions) => { seen.push(options); return { stop: vi.fn() } }]))
      const saved = process.env.HARNESS_SWARM
      if (env.HARNESS_SWARM === undefined) delete process.env.HARNESS_SWARM; else process.env.HARNESS_SWARM = env.HARNESS_SWARM
      try { await startServiceProcess(named, { runners, host: fakeHost().host, swarm: load }) } finally {
        if (saved === undefined) delete process.env.HARNESS_SWARM; else process.env.HARNESS_SWARM = saved
      }
      return seen.map(options => options.swarm)
    }
    for (const named of ['agentCleanup', 'sharing', 'handoff', 'models']) expect(await run(named, {}), named).toEqual([swarm])
    expect(await run('workspaces,agentCleanup', {})).toEqual([swarm, swarm])
    expect(load).toHaveBeenCalledTimes(5)
    expect(await run('search,workspaces', {})).toEqual([undefined, undefined])
    for (const off of ['off', 'OFF', '0', 'false', 'no']) expect(await run('workspaces,agentCleanup,models', { HARNESS_SWARM: off }), off).toEqual([undefined, undefined, undefined])
    expect(load).toHaveBeenCalledTimes(5)
  })

  it('leaves off a service that cannot start and runs the others; with none started it fails as a lone one did', async () => {
    const error = vi.spyOn(console, 'error').mockImplementation(() => {})
    const fails = async () => () => { throw new Error('injected fault: usage') }
    const runners = new Map([['usage', fails], ['monitor', async () => () => ({ stop: () => {} })]])
    const { host, hosted } = fakeHost()
    await startServiceProcess('usage,monitor', { runners, host })
    expect(hosted[0].services).toHaveLength(1)
    expect(error).toHaveBeenCalledWith('[service usage] did not start · injected fault: usage')
    await expect(startServiceProcess('usage', { runners, host })).rejects.toThrow('injected fault: usage')
    // Nothing started, no process beats for it: the master sees it end before its first heartbeat.
    expect(hosted).toHaveLength(1)
    const thrown = new Map([['usage', async () => () => { throw 'not an error' }]])
    await expect(startServiceProcess('usage', { runners: thrown, host })).rejects.toBe('not an error')
    expect(error).toHaveBeenCalledWith('[service usage] did not start · not an error')
  })

  it('refuses, with exit 2 and why, a service this build does not know or a core with no socket', async () => {
    const error = vi.spyOn(console, 'error').mockImplementation(() => {})
    const exit = vi.fn((code: number): never => { throw new Error(`exit ${code}`) })
    await expect(startServiceProcess('nope', { runners: new Map(), exit })).rejects.toThrow('exit 2')
    await expect(startServiceProcess(undefined, { runners: new Map(), exit })).rejects.toThrow('exit 2')
    await expect(startServiceProcess(' , ', { runners: new Map(), exit })).rejects.toThrow('exit 2')
    // One name it does not know refuses the process: its master is from another build.
    await expect(startServiceProcess('search,nope', { exit })).rejects.toThrow('exit 2')
    local.socket = null
    await expect(startServiceProcess('search', { exit })).rejects.toThrow('exit 2')
    expect(error.mock.calls.map((call) => call[0])).toEqual([
      '[service] nope: no such service in this build',
      '[service] (none): no such service in this build',
      '[service] (none): no such service in this build',
      '[service] nope: no such service in this build',
      '[service] search: the core has no local socket to reach',
    ])
    const processExit = vi.spyOn(process, 'exit').mockImplementation(((code: number) => { throw new Error(`process.exit ${code}`) }) as never)
    await expect(startServiceProcess('nope', { runners: new Map() })).rejects.toThrow('process.exit 2')
    expect(processExit).toHaveBeenCalledWith(2)
  })

  it('runs the updater with no socket, since it speaks to the master alone, but nothing named with it that needs one', async () => {
    const error = vi.spyOn(console, 'error').mockImplementation(() => {})
    const exit = vi.fn((code: number): never => { throw new Error(`exit ${code}`) })
    const seen: ServiceProcessOptions[] = []
    const runners = new Map([
      ['updater', async () => (options: ServiceProcessOptions) => { seen.push(options); return { stop: () => {} } }],
      ['search', async () => () => ({ stop: () => {} })],
    ])
    const { host, hosted } = fakeHost()
    local.socket = null
    await startServiceProcess('updater', { runners, host, exit })
    expect(seen).toEqual([expect.objectContaining({ socketPath: '' })])
    expect(hosted[0].options).toEqual({ name: 'updater', services: ['updater'] })
    await expect(startServiceProcess('updater,search', { runners, host, exit })).rejects.toThrow('exit 2')
    expect(error).toHaveBeenCalledWith('[service] updater,search: the core has no local socket to reach')
  })
})