The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
/// <reference lib="es2024.promise" />
import type { Ctx } from './ctx'
import type { AppRow, EnvRow, LogLine } from './db'
import { Scheduler } from './scheduler'
import type { Spec } from './spec'
function fixture(schedules: Spec['schedules']) {
const app = { id: 'reminders', name: 'reminders' } as AppRow
const env = {
id: 'main',
name: 'main',
app_id: app.id,
live_deployment: 7,
active_box_id: 'box',
public_url: 'https://reminders.example.test',
box_url: 'https://box.example.test',
forward_secret: 'gateway',
} as EnvRow
const runs = new Map<string, { last_run: string; status: number }>()
const logs: LogLine[] = []
const store = {
organizationId: 'org',
all: jest.fn(async () => [env]),
appById: jest.fn(async () => app),
deployment: jest.fn(async (): Promise<{ live_at: string } | undefined> => ({ live_at: '2026-05-02T08:59:00Z' })),
get: async (_sql: string, id: string, job: string) => runs.get(id + '/' + job),
run: async (_sql: string, id: string, job: string, at: string, status: number) =>
runs.set(id + '/' + job, { last_run: at, status }),
appendLogs: jest.fn(async (_id: string, entries: LogLine[]) => {
logs.push(...entries)
return entries
}),
}
const resources = {
currentSpec: async () => ({ schedules }),
appUrl: async () => env.public_url,
boxStatus: jest.fn().mockResolvedValue('running'),
wakeFailure: () => null,
wake: jest.fn(),
}
const scheduler = new Scheduler({ store, resources, bus: { publish: jest.fn() } } as unknown as Ctx)
return { app, env, runs, logs, resources, store, scheduler }
}
const everyMinute = { name: 'remind', cron: '* * * * *', target: 'web:/tasks/remind' }
describe('hosted App schedules', () => {
beforeEach(() => jest.useFakeTimers({ now: new Date('2026-05-02T09:00:00Z') }))
afterEach(() => {
jest.useRealTimers()
jest.restoreAllMocks()
})
it('wakes a sleeping Box, retries next tick and records one invocation after downtime', async () => {
const h = fixture([everyMinute, { name: 'nightly', cron: '0 23 * * *', target: 'web:/archive' }])
h.resources.boxStatus.mockResolvedValueOnce('stopped')
const fetch = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 202 }))
await h.scheduler.tick()
expect(h.resources.wake).toHaveBeenCalledWith('box')
expect(fetch).not.toHaveBeenCalled()
expect(h.logs).toContainEqual(
expect.objectContaining({ source: 'schedule', level: 'info', line: 'remind: Box is starting, will retry' }),
)
expect(h.runs.size).toBe(0)
h.scheduler.start()
await jest.advanceTimersByTimeAsync(30_000)
expect(fetch).toHaveBeenCalledTimes(1)
const [url, options] = fetch.mock.calls[0]
expect(url).toBe('https://box.example.test/tasks/remind')
expect(options?.method).toBe('POST')
const headers = new Headers(options?.headers)
expect(headers.get('x-boxlite-schedule')).toBe('remind')
expect(headers.get('x-forwarded-host')).toBe('reminders.example.test')
expect(h.runs.get('main/remind')).toEqual({ last_run: '2026-05-02T09:00:30.000Z', status: 202 })
h.scheduler.stop()
h.scheduler.stop()
await jest.advanceTimersByTimeAsync(10 * 60_000)
await h.scheduler.tick()
await h.scheduler.tick()
expect(fetch).toHaveBeenCalledTimes(2)
expect(h.runs.get('main/remind')?.last_run).toBe('2026-05-02T09:10:30.000Z')
expect(h.runs.has('main/nightly')).toBe(false)
})
it('dispatches independent schedules together and excludes overlapping ticks', async () => {
const h = fixture([everyMinute, { ...everyMinute, name: 'clean', target: 'web:/clean' }])
const slow = Promise.withResolvers<Response>()
const fetch = jest
.spyOn(globalThis, 'fetch')
.mockImplementation(async (url) =>
String(url).endsWith('remind') ? slow.promise : new Response('invalid job', { status: 422 }),
)
const first = h.scheduler.tick()
await jest.advanceTimersByTimeAsync(1)
expect(h.runs.get('main/clean')?.status).toBe(422)
expect(h.logs).toContainEqual(
expect.objectContaining({ deployment: 7, level: 'error', line: expect.stringContaining('POST /clean → 422') }),
)
await h.scheduler.tick()
expect(h.store.all).toHaveBeenCalledTimes(1)
slow.resolve(new Response(null, { status: 204 }))
await first
expect(fetch).toHaveBeenCalledTimes(2)
expect(h.runs.get('main/remind')?.status).toBe(204)
await expect(h.scheduler.run(h.app, h.env, 'removed')).rejects.toMatchObject({ code: 'not_found' })
})
it('continues after a failed log write, and ignores deleted Apps and schedules without a due occurrence', async () => {
const h = fixture([everyMinute])
const report = jest.spyOn(console, 'error').mockImplementation(() => undefined)
const fetch = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 204 }))
h.store.appendLogs.mockRejectedValueOnce(new Error('store unavailable'))
await h.scheduler.tick()
expect(h.runs.size).toBe(0)
expect(report).toHaveBeenCalledWith('[scheduler] reminders/main/remind: store unavailable')
h.store.deployment.mockResolvedValueOnce(undefined)
await h.scheduler.tick()
h.store.appById.mockResolvedValueOnce({ ...h.app, deleted_at: '2026-05-01' })
await h.scheduler.tick()
expect(fetch).toHaveBeenCalledTimes(1)
await h.scheduler.tick()
expect(h.runs.get('main/remind')?.status).toBe(204)
})
})