Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

app.test.ts

227 lines · 9.1 KB · TypeScript
import assert from 'node:assert/strict'
import { registerHooks } from 'node:module'
import { test } from 'node:test'

// In-memory stand-in for kody:runtime so the app can run under node --test.
const STUB = `
const store = globalThis.__factoryStore ??= new Map();
globalThis.__factoryWrites ??= { n: 0 };
export const packageStorage = () => ({
  async get(k) { return store.get(k) ?? null },
  async set(k, v) { globalThis.__factoryWrites.n++; store.set(k, JSON.stringify(v)) },
});
export const packageContext = { appBasePath: '/apps/factory/' };
export async function credential() { throw new Error('no credentials in tests') }
export async function credentials() { return [] }
export const kody = {};
export const workflows = null;
`
registerHooks({
	resolve(spec, ctx, next) {
		// Wake alerts can post to Discord; tests stub it (wake-transport tests also swap it out).
		if (spec === 'kody:@kody/discord/post-message') return { url: `data:text/javascript,${encodeURIComponent('export default async () => ({ ok: true })')}`, shortCircuit: true }
		if (spec === 'kody:runtime') {
			return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true }
		}
		return next(spec, ctx)
	},
})

const { default: app } = await import('./entry.ts')
const { seedKentProjects, setProjectEnabled } = await import('../projects/config.ts')
const { patchSettings } = await import('../lib/settings.ts')
const { CLIENT_JS } = await import('./client.ts')
const { renderShell } = await import('./ui.ts')
const { parseCreateInput } = await import('./create-input.ts')
const { normalizeProject, KENT_SEED_PROJECTS } = await import('../projects/model.ts')

const g = globalThis as unknown as { __factoryWrites: { n: number } }
const BASE = 'https://app.test/apps/factory'
const get = (path: string) => app.fetch(new Request(BASE + path))
const postJson = (path: string, body: unknown) =>
	app.fetch(
		new Request(BASE + path, {
			method: 'POST',
			headers: { 'content-type': 'application/json' },
			body: JSON.stringify(body),
		}),
	)

await seedKentProjects()
await setProjectEnabled('mediarss', false)
await patchSettings({ cloudflareAccountId: 'abcdef0123456789abcdef0123456789' })

test('every view renders a non-blank shell without writing storage', async () => {
	const before = g.__factoryWrites.n
	for (const [path, marker] of [
		['/', 'Move work forward.'],
		['/work', 'Work queue'],
		['/projects', 'Every repository'],
		['/projects/kody', 'Loading project'],
		['/notifications', 'Notifications'],
		['/settings', 'Run safely'],
		['/manage', 'Manage projects'],
	] as const) {
		const res = await get(path)
		assert.equal(res.status, 200, path)
		assert.match(res.headers.get('content-type') ?? '', /text\/html/)
		const html = await res.text()
		assert.ok(html.includes(marker), `${path} has ${marker}`)
		assert.ok(html.includes('data-base="/apps/factory"'), `${path} carries basePath`)
		assert.ok(html.includes('aria-label="Main"'))
		assert.doesNotMatch(html, /\son[a-z]+\s*=/i, `${path} has no inline handlers`)
		assert.doesNotMatch(html, /https?:\/\/fonts\./, 'no external fonts')
	}
	assert.equal(g.__factoryWrites.n, before, 'GET never writes')
})

test('client script is valid plain JS with no template placeholders', () => {
	assert.ok(!CLIENT_JS.includes('`'))
	assert.ok(!CLIENT_JS.includes('${'))
	assert.doesNotThrow(() => new Function(CLIENT_JS))
})

test('shell escapes the base path', () => {
	const html = renderShell({ basePath: '"><script>x', view: 'overview', title: 't' })
	assert.ok(!html.includes('"><script>x'))
})

test('manage page hides the account id and offers disable confirmation', async () => {
	const html = await (await get('/manage')).text()
	assert.ok(!html.includes('abcdef0123456789abcdef0123456789'))
	assert.ok(html.includes('Account configured'))
	assert.ok(html.includes('data-confirm='))
	assert.ok(html.includes('Single agent (preview only)'))
})

test('legacy project link redirects to the project detail page', async () => {
	const res = await get('/project/kody')
	assert.equal(res.status, 303)
	assert.equal(res.headers.get('location'), '/apps/factory/projects/kody')
})

test('project detail shell renders with skeleton that client will fill', async () => {
	const res = await get('/projects/kody')
	assert.equal(res.status, 200)
	const html = await res.text()
	assert.ok(html.includes('id="pd-title"'))
	assert.ok(html.includes('id="pd-crumb"'))
	assert.ok(html.includes('Loading project'))
})

test('project detail API returns data for a known project and 404 for unknown', async () => {
	const good = await get('/api/projects/kody/overview')
	assert.equal(good.status, 200)
	const data = await good.json()
	assert.equal(data.project.id, 'kody')
	assert.ok(data.flow)
	assert.ok(data.agents)
	assert.ok(data.prs)
	const bad = await get('/api/projects/no-such-project/overview')
	assert.equal(bad.status, 404)
})

test('project overview API degrades when runList/credentials throw', async () => {
	const res = await get('/api/projects/kody/overview')
	assert.equal(res.status, 200)
	const data = await res.json()
	// Agents section should report devin error (credential not mapped in test)
	assert.ok(data.agents.devinLive.error || Array.isArray(data.agents.devinLive))
	// Runs section should degrade (kody.runList is {} in test stub)
	assert.ok(data.runs.error || data.runs.groups)
})

test('conventional icon URLs resolve', async () => {
	const { readFileSync } = await import('node:fs')
	const fav = readFileSync(new URL('../../public/favicon.svg', import.meta.url), 'utf8').trim()
	for (const path of ['/favicon.svg', '/favicon.ico']) {
		const res = await get(path)
		assert.equal(res.status, 200)
		assert.match(res.headers.get('content-type') ?? '', /image\/svg\+xml/)
		assert.equal((await res.text()).trim(), fav)
	}
	const touch = await get('/apple-touch-icon.png')
	assert.equal(touch.status, 308)
	assert.equal(touch.headers.get('location'), '/apps/factory/_assets/apple-touch-icon.png')
})

test('create route validates and creates parked manual work', async () => {
	const form = await app.fetch(
		new Request(BASE + '/api/create', { method: 'POST', body: new URLSearchParams({ projectId: 'kody', title: 'x' }) }),
	)
	assert.equal(form.status, 415)
	assert.equal((await get('/api/create')).status, 405)
	assert.equal((await postJson('/api/create', { projectId: 'nope', title: 'x' })).status, 400)
	const disabled = await postJson('/api/create', { projectId: 'mediarss', title: 'x' })
	assert.equal(disabled.status, 400)
	assert.match((await disabled.json()).error, /disabled/)

	const res = await postJson('/api/create', {
		projectId: 'kody',
		title: '  Polish the dashboard  ',
		body: 'details',
		kind: 'friction',
		priority: 1,
		repoRef: 'kody-hq/kody',
	})
	assert.equal(res.status, 201)
	const { ok, item } = await res.json()
	assert.equal(ok, true)
	assert.equal(item.state, 'intake')
	const queue = await (await get('/api/queue')).json()
	const stored = queue.items.find((i: { id: string }) => i.id === item.id)
	assert.equal(stored.title, 'Polish the dashboard')
	assert.equal(stored.source, 'manual')
	assert.deepEqual(stored.labels, ['friction', 'kind:friction', 'source:manual'])
	assert.equal(stored.priority, 1)
	assert.equal(stored.shadow, true)
})

test('queue api can include finished work', async () => {
	const open = await (await get('/api/queue')).json()
	const all = await (await get('/api/queue?includeTerminal=1')).json()
	assert.ok(all.total >= open.total)
})

test('parseCreateInput rules', () => {
	const state = {
		version: 2 as const,
		defaultProjectId: 'kody',
		projects: { kody: normalizeProject(KENT_SEED_PROJECTS[0]!) },
	}
	assert.equal(parseCreateInput({ projectId: 'kody', title: '' }, state).ok, false)
	assert.equal(parseCreateInput({ projectId: 'kody', title: 'a', priority: 4 }, state).ok, false)
	assert.equal(parseCreateInput({ projectId: 'kody', title: 'a', kind: 'bogus' }, state).ok, false)
	assert.equal(parseCreateInput({ projectId: 'kody', title: 'a', repoRef: 'other/repo' }, state).ok, false)
	const ok = parseCreateInput({ projectId: 'kody', title: 'a', priority: '', source: 'manual' }, state)
	assert.ok(ok.ok && ok.input.priority === undefined && ok.input.labels.length === 0)
})

test('project costs route returns 200 for a known project', async () => {
	const res = await get('/api/projects/kody/costs')
	assert.equal(res.status, 200)
	const data = await res.json()
	assert.equal(data.projectId, 'kody')
	assert.equal(typeof data.runsStarted, 'number')
})

test('notifications API returns empty list and accepts mark-all-read', async () => {
	const listRes = await get('/api/notifications')
	assert.equal(listRes.status, 200)
	const list = await listRes.json()
	assert.ok(Array.isArray(list.notifications))
	assert.equal(typeof list.unread, 'number')

	const markRes = await postJson('/api/notifications/mark-read', { all: true })
	assert.equal(markRes.status, 200)
	const mark = await markRes.json()
	assert.equal(typeof mark.marked, 'number')
})

test('notifications rules API returns default rules', async () => {
	const res = await get('/api/notifications/rules')
	assert.equal(res.status, 200)
	const rules = await res.json()
	assert.ok(rules.defaults)
	assert.ok(typeof rules.defaults.discordEnabled === 'boolean')
})