The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import { Hono } from 'hono'
import { createCloudAppStore } from '../../../test/cloud-app-store'
import { buildCtx } from './server'
import { createApp } from './services/apps'
import { detailView, environmentViews, summaryView } from './console-views'
import { deploymentChanges } from './console-deployment'
import { activityView } from './console-activity'
import { withAccessLog } from './console-access'
import { now, type AppRow, type EnvRow, type Deployment } from './db'
import type { Config } from './config'
import type { Ctx, Deps } from './ctx'
import type { Spec } from './spec'
import type { ServiceState } from './supervisor'
const suite = process.env.DB_HOST ? describe : describe.skip
suite('Dashboard App overview', () => {
let fixture: Awaited<ReturnType<typeof createCloudAppStore>>
let ctx: Ctx
let app: AppRow
let env: EnvRow
const appUrl = 'https://portal.example.test'
const config = {
publicUrl: 'https://api.example.test',
managementUrl: 'https://api.example.test/v1',
runtimeImages: { node: 'node:22' },
domainsEnabled: true,
supervisorUrl: appUrl,
artifactUrl: appUrl,
svBinDir: '.',
agentMdPath: 'agent.md',
sessionSecret: 'sample',
identityPrivateKey: '',
diskSizeGb: 10,
autoStopSeconds: 900,
} satisfies Config
beforeAll(async () => {
fixture = await createCloudAppStore()
})
afterAll(() => fixture?.close())
beforeEach(async () => {
await fixture.source.query(`TRUNCATE ${fixture.schema}.apps CASCADE`)
ctx = buildCtx(config, {
store: fixture.store,
origins: { envUrl: () => appUrl },
volumes: { list: async () => [{ name: 'mc-portal-main-data', id: 'vol', sizeBytes: 2048, state: 'ready' }] },
domains: { list: async () => [] },
boxlite: { getBox: async () => ({ status: 'running' }) },
} as unknown as Deps)
app = await createApp(ctx, 'portal')
env = (await ctx.store.envByName(app.id, 'main'))!
})
function deploy(update: Partial<Deployment> = {}) {
return ctx.store.insertDeployment(
{
kind: 'deploy',
status: 'live',
by: 'key:…abcd',
created_at: now(),
started_at: now(),
finished_at: now(),
message: null,
steps: [],
changes: [],
error: null,
request: { kind: 'deploy' },
base_version: 0,
spec_version: 1,
snapshot_id: null,
idempotency_key: null,
release: 1,
box_id: 'runtime',
built: true,
restore_point: null,
live_at: now(),
...update,
},
env.id,
)
}
it('shows the serving release, a subsequent failure and observations from the running Box', async () => {
const spec = {
app: app.name,
environment: env.name,
version: 1,
deployment: 1,
base_version: 0,
assigned: { box_id: 'runtime', app_url: appUrl, box_url: null, db_host: null, db_branch: null },
domains: { builtin: 'portal', custom: [] },
public_paths: [],
access: 'public',
runtime: { image: 'node', size: 'small', build: [], output: null },
services: [
{ name: 'web', command: 'node server.js', port: 3000, health: '/health' },
{ name: 'assets', static: 'public' },
],
volumes: [
{ name: 'data', mount: '/data', mode: 'rw', from: null, path: null },
{ name: 'uploads', mount: '/uploads', mode: 'rw', from: null, path: null },
],
variables: { LOG_LEVEL: 'info' },
secrets: { MAIL: 'app/mail' },
database: { migrations: 'migrations/', applied: [] },
schedules: [],
auth: null,
} as Spec
await ctx.store.insertSpec(env.id, spec)
await deploy({ steps: [{ name: 'build', status: 'done', ms: 2500 }] })
await ctx.store.updateEnv(env.id, {
live_deployment: 1,
active_box_id: 'runtime',
public_url: appUrl,
box_url: 'https://box.example.test',
db_url: 'postgresql://reader:[email protected]/portal',
})
env = (await ctx.store.envById(env.id))!
await deploy({
status: 'failed',
release: null,
request: { kind: 'deploy', manifest: { ...spec, database: { migrations: 'migrations/' } }, migrations: [] },
error: {
step: 'build',
message: 'npm run build exited with code 1',
log_tail: ['npm ERR! missing script: build'],
},
live_at: null,
})
const service = {
name: 'web',
state: 'restarting',
health: 'unhealthy',
port: 3000,
pid: 55,
restarts: 4,
last_exit_code: 1,
memory_bytes: 128,
} as ServiceState
const probe = jest.spyOn(ctx.resources, 'liveServices').mockResolvedValue({
box: 'running',
services: [service],
fresh: true,
usage: { memory_total_bytes: 1000, memory_available_bytes: 10, disk_total_bytes: 1000, disk_free_bytes: 10 },
})
await ctx.store.appendLogs(env.id, [
{ ts: now(), source: 'web', level: 'error', line: 'MAIL_TOKEN is not set', deployment: 1 },
])
const view = await detailView(ctx, ctx.accessLog, app, env)
expect(view).toMatchObject({
status: 'degraded',
activeRelease: '#1',
attention: expect.stringContaining('#2 failed'),
resources: { database: true, storage: 2 },
database: { name: 'portal', injectedInto: ['web'] },
storages: [
{ name: 'data', volumeId: 'vol', sizeBytes: 2048, state: 'ready' },
{ name: 'uploads', mountPath: '/uploads', volumeId: null, sizeBytes: null, state: null },
],
variables: { LOG_LEVEL: 'info' },
releases: [
{ id: '#2', status: 'failed' },
{ id: '#1', current: true, buildSeconds: 2.5 },
],
services: [
{ name: 'web', restarts: 4, healthPath: '/health', memoryBytes: 128 },
{ name: 'assets', staticDir: 'public' },
],
})
expect(view.problems.map((p) => p.summary).join('\n')).toMatch(/web keeps crashing/)
expect(view.problems.length).toBeGreaterThanOrEqual(4)
expect(JSON.stringify(view)).not.toContain('reader:secret')
expect(await summaryView(ctx, app)).toMatchObject({
lastDeploy: { releaseId: '#2' },
attention: expect.stringContaining('failed at build'),
})
expect(await environmentViews(ctx, app)).toMatchObject([{ name: 'main', box: 'runtime', url: appUrl + '/' }])
for (const observed of [
{ name: 'web', state: 'running', health: 'unhealthy' },
{ name: 'web', state: 'failed', health: 'none', last_exit_code: 3 },
]) {
probe.mockResolvedValue({ box: 'running', fresh: true, services: [observed as ServiceState], usage: null })
const observedView = await detailView(ctx, ctx.accessLog, app, env)
const problem = observedView.problems.find((p) => p.summary.startsWith('web'))!
expect(problem.summary).toBe(observed.state === 'failed' ? 'web has crashed' : 'web is failing its health check')
expect(problem.detail).toContain('MAIL_TOKEN')
}
probe.mockResolvedValue({ box: 'stopped', services: [service], fresh: true, usage: null })
expect(await detailView(ctx, ctx.accessLog, app, env)).toMatchObject({
status: 'sleeping',
services: [{ state: 'asleep' }, { state: 'asleep' }],
})
})
it('shows deployment progress before the app has served its first release', async () => {
await deploy({ kind: 'apply', request: { kind: 'apply' }, release: null, box_id: null })
expect((await summaryView(ctx, app)).status).toBe('draft')
const deployment = await deploy({
status: 'queued',
started_at: null,
finished_at: null,
release: null,
live_at: null,
})
expect(await summaryView(ctx, app)).toMatchObject({ status: 'building', progress: 'Deploying #2 · queued' })
const details = () => detailView(ctx, ctx.accessLog, app, env)
expect(await details()).toMatchObject({
statusDetail: 'Deploying #2 · queued',
deploying: { step: null, since: deployment.created_at },
activeRelease: null,
})
await ctx.store.updateDeployment(env.id, deployment.number, {
status: 'building',
steps: [{ name: 'build', status: 'running' }],
})
expect((await summaryView(ctx, app)).progress).toBe('Deploying #2 · build')
expect((await details()).statusDetail).toBe('Deploying #2 · build')
await ctx.store.updateDeployment(env.id, deployment.number, {
steps: [{ name: 'build', status: 'running', detail: 'installing packages' }],
})
expect((await details()).statusDetail).toBe('Deploying #2 · build (installing packages)')
await ctx.store.updateDeployment(env.id, deployment.number, {
status: 'failed',
error: { step: 'build', message: 'Build failed' },
})
const failed = await details()
expect(failed).toMatchObject({ status: 'failed', deploying: null, activeRelease: null })
expect(failed.problems[0].summary).toBe('Deployment #2 failed at build')
expect(failed.problems[0]).not.toHaveProperty('serving')
})
it('shows a saved release preview and reports only the service and usage evidence available', async () => {
const deployment = await deploy({ started_at: null })
await ctx.store.updateEnv(env.id, { live_deployment: deployment.number, active_box_id: 'runtime' })
const capturedAt = now()
await ctx.store.run(
'INSERT INTO previews (env_id,captured_at,deployment,image) VALUES (?,?,?,?)',
env.id,
capturedAt,
deployment.number,
Buffer.from('image'),
)
const src = `/apps/portal/preview?env=main&v=${encodeURIComponent(capturedAt)}`
expect((await summaryView(ctx, app)).previewSrc).toBe(src)
const probe = jest.spyOn(ctx.resources, 'liveServices').mockResolvedValue({
box: 'running',
fresh: true,
services: [
{ name: 'api', state: 'running', health: 'unhealthy' },
{ name: 'jobs', state: 'failed', restarts: 1 },
{ name: 'queue', state: 'restarting', restarts: 4 },
{ name: 'sync', state: 'restarting' },
],
usage: { memory_total_bytes: 1000, memory_available_bytes: 10, disk_total_bytes: 1000, disk_free_bytes: 500 },
})
const details = () => detailView(ctx, ctx.accessLog, app, env)
const view = await details()
expect(view.preview).toEqual({ src, capturedAt, releaseId: '#1' })
expect(view.services[0]).toMatchObject({ name: 'api', command: [], exposed: false, recentErrors: [] })
expect(view.problems.map((p) => [p.summary, p.detail])).toEqual([
['api is failing its health check', 'It answers its health check with an error.'],
['jobs has crashed', 'It stopped. Restarted 1 time so far.'],
['Running low on memory', '10 B free of 1000 B. A service that runs out of memory is stopped and restarted.'],
])
probe.mockResolvedValue({ box: null, fresh: false, services: [], usage: null })
expect((await details()).box).toEqual({ id: 'runtime', state: 'unknown', usage: null })
})
it('compares the two release manifests and identifies infrastructure and config changes', async () => {
for (const [id, files] of [
[
'first',
[
['app.js', '1'],
['old.txt', '2'],
],
],
[
'second',
[
['app.js', '3'],
['new.txt', '4'],
],
],
] as const) {
await ctx.store.run(
'INSERT INTO snapshots (id,app_id,manifest,files,bytes,created_at) VALUES (?,?,?,?,?,?)',
id,
app.id,
JSON.stringify(files.map(([path, sha256]) => ({ path, sha256, size: 1, mode: 420 }))),
2,
2,
now(),
)
}
await deploy({ snapshot_id: 'first' })
const latest = await deploy({
snapshot_id: 'second',
changes: [
{ kind: '~', path: 'runtime.image', from: 'node18', to: 'node22' },
{ kind: '+', path: 'variables.FLAG', to: 'on' },
],
})
expect(await deploymentChanges(ctx, app, env, latest)).toEqual({
infrastructure: ['Image: node18 → node22'],
configuration: ['New variable FLAG'],
code: { added: 1, changed: 1, removed: 1, files: 2, comparedWith: 1 },
})
})
it('counts HTTP requests and errors by hour and strips one-time values from recorded URLs', async () => {
const access = ctx.accessLog
expect(await access.metrics(env.id)).toBeNull()
const site = new Hono().get('*', (c) => withAccessLog(access, env, c, async () => new Response('ok')))
expect((await site.request('https://portal.example.test/page?code=once&state=random&tab=new')).status).toBe(200)
const rows = await access.since(env.id, '2000-01-01')
expect(rows).toMatchObject([{ method: 'GET', path: '/page?tab=new', status: 200 }])
const hour = 3600000
const at = Date.now()
for (const [ago, status, ms] of [
[25, 200, 20],
[1, 502, 500],
[1, 200, 100],
])
await access.record(env.id, { ts: new Date(at - ago * hour).toISOString(), method: 'GET', path: '/', status, ms })
const metrics = (await access.metrics(env.id, at))!
expect(metrics.previousRequests).toBe(1)
expect(metrics.requests.slice(-2)).toEqual([2, 1])
expect(metrics.errors.slice(-2)).toEqual([1, 0])
expect(metrics.p95Ms[22]).toBe(500)
})
it('describes recorded App, deployment and database actions while hiding internal upload steps', async () => {
await deploy({ message: 'First release' })
const activity = [
['db.sql.write', { statements: ['UPDATE'] }],
['db.proxy', { role: 'owner', connections: 1, open: 1, duration_ms: 3000, refused: 2 }],
['db.export', { format: 'csv', table: 'notes' }],
['db.import', { table: 'notes', rows: 2 }],
['db.reset', { dropped: ['notes'] }],
['app.delete', { purge_after: '2026-10-08T18:05:00Z' }],
['auth.user.block', { email: '[email protected]' }],
['POST /envs/main/deployments', {}],
['POST /envs/main/deployments/1/cancel', {}],
['PUT /uploads/one', {}],
] as const
for (const [action, detail] of activity) await ctx.store.recordActivity(app.id, 'main', 'key:…abcd', action, detail)
const rows = await activityView(ctx, app, 'main', 20)
expect(rows.map((r) => r.detail)).toEqual(
expect.arrayContaining([
'UPDATE',
'read-write (owner) · open for 3 s · 1 connection · 2 refused',
'csv of notes',
'2 rows into notes',
'dropped 1 table',
'kept until 2026-10-08 18:05 UTC',
'[email protected]',
'#1 · First release',
]),
)
expect(rows[0]).toMatchObject({
action: 'cancelled #1',
actorKind: 'agent',
link: { tab: 'deployments', deployment: 1 },
})
expect(rows.some((r) => r.action.includes('uploads'))).toBe(false)
})
it('displays the running step until it finishes and attaches the event time to the release', async () => {
const { releaseViews } = await import('./console-releases')
const dep = await deploy({
status: 'building',
live_at: null,
release: null,
started_at: null,
steps: [{ name: 'build', status: 'running', detail: 'installing dependencies' }],
})
const list = () => releaseViews(ctx, app, env)
expect((await list())[0].running).toMatchObject({ name: 'build', since: null })
await ctx.store.insertEvent(env.id, dep.number, 'step', { name: 'build', status: 'running' })
await ctx.store.insertEvent(env.id, dep.number, 'step', { name: 'upload', status: 'done' })
expect((await list())[0].running).toMatchObject({
detail: 'installing dependencies',
since: expect.stringMatching(/^\d{4}-/),
})
await ctx.store.updateDeployment(env.id, dep.number, { steps: [{ name: 'build', status: 'done' }] })
expect((await list())[0].running).toBeNull()
await ctx.store.updateDeployment(env.id, dep.number, { status: 'live' })
expect((await list())[0].status).toBe('live')
})
it('links management activity to the corresponding dashboard tabs', async () => {
const cases = [
['secret.update', 'replaced a secret', 'variables'],
['secret.delete', 'deleted a secret', 'variables'],
['volume.delete', 'deleted a file on a volume', 'volumes'],
['auth.purge_test_users', 'removed the test users', 'auth'],
['auth.email.set', 'set up the sign-in email sender', 'auth'],
['auth.email.test', 'sent a test sign-in email', 'auth'],
['auth.email.remove', 'removed the sign-in email sender', 'auth'],
['auth.user.signout', 'signed a user out', 'auth'],
['auth.user.unblock', 'unblocked a user', 'auth'],
['auth.test_session', 'opened a test session', 'auth'],
['POST /uploads', 'uploaded the project', 'deployments'],
['domain.add', 'added a custom domain', 'domains'],
['domain.verify', 'verified a custom domain', 'domains'],
['domain.remove', 'removed a custom domain', 'domains'],
['finding.ack', 'acknowledged a finding as intended', 'overview'],
['finding.unack', 'brought back an acknowledged finding', 'overview'],
['note.add', 'kept a note for the next session', 'overview'],
['note.forget', 'removed a note', 'overview'],
['box.sleep', 'put the Box to sleep', 'overview'],
['POST /envs/main/services/all/restart', 'restarted all services', 'deployments'],
['POST /envs/main/services/web/restart', 'restarted web', 'deployments'],
['POST /envs/main/schedules/daily/run', 'ran schedule daily', 'deployments'],
['POST /envs/main/db/snapshots', 'took a database backup', 'database'],
['POST /envs/main/db/restore', 'restored the database', 'database'],
['POST /envs/main/db/reset', 'reset the database', 'database'],
]
for (const [action] of cases) await ctx.store.recordActivity(app.id, env.name, 'console', action)
expect((await activityView(ctx, app, env.name, cases.length)).map((r) => [r.action, r.link?.tab])).toEqual(
cases.map((r) => r.slice(1)).reverse(),
)
})
it('keeps activity readable when the environment no longer exists', async () => {
for (const action of ['POST /envs/preview/deployments', 'read status', 'read context'])
await ctx.store.recordActivity(app.id, 'preview', 'console', action)
await ctx.store.recordActivity(app.id, null, 'console', 'DELETE /envs/preview')
const rows = await activityView(ctx, app, 'preview', 4)
expect(rows.map((row) => [row.action, row.link, row.detail])).toEqual([
['deleted environment preview', undefined, undefined],
['read the context', undefined, undefined],
['read the status', undefined, undefined],
['started a deployment', { tab: 'deployments' }, undefined],
])
})
it('formats whole database dumps, single-row imports and completed read-only proxy sessions', async () => {
for (const [action, detail] of [
['db.proxy', { role: 'reader', duration_ms: 125000, connections: 2 }],
['db.proxy', { role: 'reader', session: 'new-session', started_at: now() }],
['db.export', { format: 'sql' }],
['db.import', { table: 'notes', rows: 1 }],
['db.reset', { dropped: ['notes', 'tags'] }],
] as const)
await ctx.store.recordActivity(app.id, env.name, 'console', action, detail)
expect((await activityView(ctx, app, env.name, 5)).map((row) => row.detail)).toEqual([
'dropped 2 tables',
'1 row into notes',
'sql dump',
'read-only · 0 s · 0 connections',
'read-only · 2 min · 2 connections',
])
})
it('counts distinct signed-in users in each hour until revocation or expiry', async () => {
const { upsertUser, createSession } = await import('./enduser/sessions')
const a = await upsertUser(ctx, app, env, 'github', { id: 'one', name: 'Alice', email: null, avatarUrl: null })
const b = await upsertUser(ctx, app, env, 'github', { id: 'two', name: 'Bob', email: null, avatarUrl: null })
await createSession(ctx, a, 'oauth', 3600)
await createSession(ctx, a, 'oauth', 3600)
await createSession(ctx, b, 'oauth', 3600)
const at = Date.parse('2026-10-06T12:00:00Z')
await ctx.store.run(
'UPDATE app_sessions SET created_at=?,expires_at=?',
'2026-10-06T09:15:00Z',
'2026-10-06T11:45:00Z',
)
await ctx.store.run('UPDATE app_sessions SET revoked_at=? WHERE user_id=?', '2026-10-06T10:15:00Z', b.id)
const metrics = await ctx.accessLog.metrics(env.id, at)
expect(metrics?.activeUsers.slice(-3)).toEqual([2, 2, 1])
expect(metrics?.requests.slice(-3)).toEqual([0, 0, 0])
expect(metrics?.p95Ms.slice(-3)).toEqual([null, null, null])
})
})