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

sync-pwa.test.ts

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

// kody:runtime stand-in. credential('github') behavior is switched per test via globalThis.
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(key) {
  globalThis.__credCalls = (globalThis.__credCalls ?? 0) + 1;
  if (key !== 'github' || !globalThis.__githubFetch) throw new Error('credential not mapped');
  return { name: 'github', fetch: globalThis.__githubFetch };
}
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:@kody/github/events/ingest') return { url: `data:text/javascript,${encodeURIComponent('export default async () => ({ ok: true, emitted: [] })')}`, shortCircuit: true }
		if (spec === 'kody:runtime') return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true }
		return next(spec, ctx)
	},
})

const g = globalThis as unknown as {
	__factoryWrites: { n: number }
	__factoryStore: Map<string, string>
	__githubFetch?: (url: string, init?: RequestInit) => Promise<Response>
}
const { default: app } = await import('./entry.ts')
const { default: sync } = await import('../exports/sync.ts')
const { default: webhook, applySourceLifecycle } = await import('../webhooks/github-issues.ts')
const { upsertProject } = await import('../projects/config.ts')
const { patchSettings } = await import('../lib/settings.ts')
const { renderServiceWorker, buildManifest } = await import('./pwa.ts')
const { loadJson, storageKeys } = await import('../lib/storage.ts')
const { emptyLedger } = await import('../core/work-item.ts')
const { CLIENT_JS } = await import('./client.ts')
type Ledger = import('../core/work-item.ts').Ledger

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

await upsertProject({ id: 'demo', displayName: 'Demo', enabled: true, defaultRunnerId: 'devin', repos: [
	{ id: 'acme__app', repoRef: 'acme/app', host: 'github', enabled: true },
	{ id: 'acme__off', repoRef: 'acme/off', host: 'github', enabled: false },
] })
await upsertProject({ id: 'off', displayName: 'Off', enabled: false, defaultRunnerId: 'devin', repos: [
	{ id: 'acme__hidden', repoRef: 'acme/hidden', host: 'github', enabled: true },
] })

await patchSettings({ pilotScope: { mode: 'allowlist', projectIds: ['demo'], repoRefs: [] } })

const ISSUES = [
	{ number: 1, title: 'Crash on save', body: 'x', html_url: 'https://github.com/acme/app/issues/1', labels: [{ name: 'P1' }] },
	{ number: 2, title: 'A PR', html_url: 'https://github.com/acme/app/pull/2', labels: [], pull_request: { url: 'x' } },
	{ number: 3, title: 'Owner call', html_url: 'https://github.com/acme/app/issues/3', labels: [{ name: 'needs-kent' }, { name: 'P0' }] },
]
const calls: string[] = []
function mockGithub(body: unknown = ISSUES, status = 200) {
	g.__githubFetch = async (u) => {
		// The client's one setup probe is not a repository read.
		if (u.endsWith('/rate_limit')) return Response.json({ resources: {} })
		calls.push(u)
		return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
	}
}

test('bootstrap mirrors canonical routes and never writes', async () => {
	const before = g.__factoryWrites.n
	const b = await (await get('/api/bootstrap')).json()
	const status = await (await get('/api/status')).json()
	const projects = await (await get('/api/projects')).json()
	const queue = await (await get('/api/queue')).json()
	const settings = await (await get('/api/settings')).json()
	assert.deepEqual(Object.keys(b).sort(), ['board', 'finished', 'generatedAt', 'projects', 'queue', 'settings', 'snapshot', 'unreadNotifications'])
	const strip = (s: Record<string, unknown>) => { const { generatedAt: _, ...rest } = s; return rest }
	assert.deepEqual(strip(b.snapshot), strip(status))
	assert.deepEqual(b.projects, projects)
	assert.deepEqual(b.queue, queue)
	assert.deepEqual(b.settings, settings)
	assert.equal(g.__factoryWrites.n, before)
})

test('sync without a github credential reports setup, no writes, no network', async () => {
	g.__githubFetch = undefined
	const before = g.__factoryWrites.n
	const r = await sync({})
	assert.equal(r.ok, false)
	assert.equal(r.setup, 'github-credential-missing')
	assert.match(r.message ?? '', /credential "github"/)
	assert.equal(g.__factoryWrites.n, before)
	const res = await postJson('/api/sync', {})
	assert.equal(res.status, 424)
})

test('sync dry run reads only enabled repos, skips PRs, parses priority, never writes', async () => {
	calls.length = 0
	mockGithub()
	const before = g.__factoryWrites.n
	const r = await sync({ perRepoLimit: 500 })
	assert.equal(r.ok, true)
	assert.equal(r.dryRun, true)
	assert.equal(r.perRepoLimit, 50)
	assert.equal(calls.filter((c) => c.includes('/issues')).length, 1)
	assert.equal(calls.filter((c) => c.includes('/pulls?state=open')).length, 1, 'one open-PR list for overlap')
	assert.ok(calls.every((c) => new URL(c).host === 'api.github.com'))
	assert.match(calls[0]!, /\/repos\/acme\/app\/issues\?state=open.*per_page=50/)
	assert.equal(r.totals.skippedPullRequests, 1)
	assert.equal(r.totals.eligible, 2)
	const owner = r.issues.find((i) => i.number === 3)!
	assert.equal(owner.priority, 0)
	assert.equal(owner.needsKent, true)
	assert.equal(r.issues.find((i) => i.number === 1)!.url, 'https://github.com/acme/app/issues/1')
	assert.equal(g.__factoryWrites.n, before, 'dry run never writes')
	const viaApp = await (await postJson('/api/sync', { projectId: 'demo' })).json()
	assert.equal(viaApp.dryRun, true)
	assert.equal(g.__factoryWrites.n, before)
})

test('sync ingest creates shadow intake items once, then reports them as already queued', async () => {
	mockGithub()
	const r = await sync({ dryRun: false })
	assert.equal(r.totals.created, 2)
	const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
	const made = r.created.map((id) => ledger.items[id]!)
	assert.ok(made.every((i) => i.state === 'intake' && i.shadow === true && i.runId === null))
	assert.ok(made.some((i) => i.fingerprint === 'github-issue:acme/app:1'))
	const again = await sync({ dryRun: false })
	assert.equal(again.totals.created, 0)
	assert.equal(again.totals.alreadyQueued, 2)
})

test('sync handles GitHub 401 and malformed bodies without leaking', async () => {
	mockGithub({ message: 'Bad credentials' }, 401)
	const r = await sync({})
	assert.equal(r.setup, 'github-credential-missing')
	mockGithub({ not: 'a list' })
	const m = await sync({})
	assert.match(m.repos[0]!.error ?? '', /non-list/)
})

const event = (action: string, extra: Record<string, unknown> = {}) => ({
	request: { json: { action, repository: { full_name: 'acme/app' }, issue: { number: 1, title: 'Crash on save', labels: [], state: action === 'closed' ? 'closed' : 'open', ...extra } } },
})

test('synthetic webhook deliveries never write', async () => {
	const before = g.__factoryWrites.n
	const r = (await webhook({ ...event('opened', { number: 99 }), synthetic: true })) as Record<string, unknown>
	assert.equal(r.synthetic, true)
	assert.equal(r.wrote, false)
	assert.equal(g.__factoryWrites.n, before, 'synthetic writes nothing')
	const body = event('opened', { number: 98 })
	;(body.request.json as Record<string, unknown>).synthetic = true
	const forged = (await webhook(body)) as Record<string, unknown>
	assert.equal(forged.synthetic, false, 'body-level synthetic flag is ignored')
	assert.ok(g.__factoryWrites.n > before, 'the forged (real) delivery writes')
})

test('webhook ignores pull requests and closes queued work by fingerprint', async () => {
	const pr = (await webhook({ request: { json: { action: 'opened', repository: { full_name: 'acme/app' }, issue: { number: 5, pull_request: {} } } } })) as Record<string, unknown>
	assert.equal(pr.skipped, true)
	const closed = (await webhook(event('closed'))) as Record<string, unknown>
	assert.equal(closed.change, 'dropped')
	const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
	const item = Object.values(ledger.items).find((i) => i.fingerprint === 'github-issue:acme/app:1')!
	assert.equal(item.state, 'dropped')
	const reopened = (await webhook(event('reopened'))) as Record<string, unknown>
	assert.equal(reopened.change, 'reopened')
})

test('closing an issue with an agent running records it but does not stop or drop', () => {
	const ledger: Ledger = { version: 1, items: { w1: { id: 'w1', projectId: 'p', fingerprint: 'f', state: 'running', events: [], updatedAt: '' } as never } }
	const r = applySourceLifecycle(ledger, { projectId: 'p', fingerprint: 'f', action: 'closed' })
	assert.equal(r.change, 'noted')
	assert.equal(ledger.items.w1!.state, 'running')
	const del = applySourceLifecycle({ version: 1, items: {} }, { projectId: 'p', fingerprint: 'f', action: 'deleted' })
	assert.equal(del.change, 'none')
})

test('closing an issue that is planned but never started drops it; a started plan is only noted', () => {
	const ledger: Ledger = { version: 1, items: { w1: { id: 'w1', projectId: 'p', fingerprint: 'f', state: 'planned', events: [], updatedAt: '' } as never, w2: { id: 'w2', projectId: 'p', fingerprint: 'g', state: 'planned', runId: 'run_1', events: [], updatedAt: '' } as never } }
	assert.equal(applySourceLifecycle(ledger, { projectId: 'p', fingerprint: 'f', action: 'closed' }).change, 'dropped')
	assert.equal(ledger.items.w1!.state, 'dropped')
	assert.equal(applySourceLifecycle(ledger, { projectId: 'p', fingerprint: 'g', action: 'closed' }).change, 'noted')
	assert.equal(ledger.items.w2!.state, 'planned')
})

test('create with an idempotency key adds exactly one item on retry', async () => {
	const body = { projectId: 'demo', title: 'Offline draft', idempotencyKey: 'abcDEF123456' }
	const a = await postJson('/api/create', body)
	const b = await postJson('/api/create', body)
	assert.equal(a.status, 201)
	assert.equal(b.status, 200)
	const ja = await a.json(), jb = await b.json()
	assert.equal(jb.replayed, true)
	assert.equal(ja.item.id, jb.item.id)
	assert.equal((await postJson('/api/create', { ...body, idempotencyKey: 'bad key!' })).status, 400)
})

test('manifest and service worker are scoped to the app mount', async () => {
	const m = await get('/manifest.webmanifest')
	assert.match(m.headers.get('content-type') ?? '', /manifest\+json/)
	const man = await m.json()
	assert.deepEqual(man, buildManifest('/apps/factory'))
	assert.equal(man.scope, '/apps/factory/')
	assert.ok(man.icons.some((i: { purpose: string; sizes: string }) => i.purpose === 'maskable' && i.sizes === '512x512'))
	assert.ok(man.icons.every((i: { src: string }) => i.src.startsWith('/apps/factory/_assets/')))
	const sw = await get('/sw.js')
	assert.equal(sw.headers.get('service-worker-allowed'), '/apps/factory/')
	const src = await sw.text()
	assert.equal(src, renderServiceWorker())
	new Function(src)
	assert.doesNotMatch(src, /\/api\//, 'SW never touches /api')
	assert.doesNotMatch(src, /'\/manage'/, 'SW never caches /manage')
	assert.match(src, /SKIP_WAITING/)
	assert.doesNotMatch(src.split("addEventListener('install'")[1]!.split('});')[0]!, /skipWaiting/, 'install never skips waiting')
	const html = await (await get('/')).text()
	assert.match(html, /rel="manifest" href="\/apps\/factory\/manifest\.webmanifest"/)
	assert.match(html, /id="net" class="net" role="status"/)
})

test('client caches a settings-free snapshot and only registers the SW off localhost', () => {
	assert.match(CLIENT_JS, /settings: null/)
	assert.match(CLIENT_JS, /localhost\|127/)
	assert.match(CLIENT_JS, /if \(accepted\) \{ reload\(\); return; \}/)
	assert.doesNotMatch(CLIENT_JS, /setInterval/)
	assert.equal((CLIENT_JS.match(/getJson\('/g) ?? []).length, 7, 'data request paths: /api/bootstrap, /api/plans/get, /api/projects/, /api/config/export, /api/config/templates, /api/projects/.../costs, /api/notifications')
})

test('SW revision is a content hash: changes with shipped code, stable otherwise', async () => {
	const { contentRevision, appRevision } = await import('./pwa.ts')
	assert.equal(appRevision(), appRevision())
	assert.match(appRevision(), /^[0-9a-f]{16}$/)
	const a = contentRevision(['sw2', 'client v1', 'css'])
	assert.equal(a, contentRevision(['sw2', 'client v1', 'css']))
	assert.notEqual(a, contentRevision(['sw2', 'client v2', 'css']))
	assert.notEqual(renderServiceWorker(a), renderServiceWorker(contentRevision(['sw2', 'client v2', 'css'])))
	assert.match(await (await get('/sw.js')).text(), new RegExp(appRevision()))
})

/** Run the client's setupServiceWorker against a fake browser. */
async function runSwClient(opts: { waiting: boolean; controllerChanges: boolean }) {
	const src = CLIENT_JS.slice(CLIENT_JS.indexOf('const SW_RELOAD_TIMEOUT_MS'))
	const fn = src.slice(0, src.indexOf('\n}\n') + 2)
	const listeners: Record<string, Array<() => void>> = {}
	const posted: unknown[] = []
	let reloads = 0
	const timers: Array<() => void> = []
	const waitingWorker = { state: 'installed', postMessage: (m: unknown) => { posted.push(m); if (opts.controllerChanges) queueMicrotask(() => listeners.controllerchange?.forEach((f) => f())) }, addEventListener() {} }
	const reg = { waiting: opts.waiting ? waitingWorker : null, installing: null, addEventListener() {}, update: async () => {} }
	const btn: { listeners: Array<() => Promise<void>>; disabled: boolean; textContent: string; addEventListener: (t: string, f: () => Promise<void>) => void } = { listeners: [], disabled: false, textContent: 'Refresh', addEventListener(_t, f) { this.listeners.push(f) } }
	const NET: { update: unknown } = { update: null }
	const navigator = { serviceWorker: { controller: { id: 'old' }, addEventListener: (t: string, f: () => void) => { (listeners[t] ??= []).push(f) }, register: async () => reg, getRegistration: async () => reg } }
	const location = { hostname: 'kody-factory--kody.kody.run', search: '', reload: () => { reloads++ } }
	const run = new Function('navigator', 'location', 'document', 'sessionStorage', '$', 'NET', 'setNet', 'url', 'BP', 'setTimeout', fn + '\nsetupServiceWorker();')
	run(navigator, location, { addEventListener() {} }, { getItem: () => null, setItem() {} }, () => btn, NET, () => {}, (p: string) => p, '', (f: () => void) => { timers.push(f) })
	await new Promise((r) => setTimeout(r, 0))
	const bannerShown = NET.update !== null
	await btn.listeners[0]!()
	await new Promise((r) => setTimeout(r, 0))
	const reloadsBeforeTimeout = reloads
	timers.forEach((f) => f())
	return { posted, reloadsBeforeTimeout, reloads, bannerShown }
}

test('Refresh activates the waiting worker and reloads once on controllerchange', async () => {
	const r = await runSwClient({ waiting: true, controllerChanges: true })
	assert.equal(r.bannerShown, true)
	assert.deepEqual(r.posted, [{ type: 'SKIP_WAITING' }, 'SKIP_WAITING'])
	assert.equal(r.reloadsBeforeTimeout, 1)
	assert.equal(r.reloads, 1, 'timeout fallback does not reload twice')
})

test('Refresh still reloads when controllerchange never fires, and with no waiting worker', async () => {
	const stuck = await runSwClient({ waiting: true, controllerChanges: false })
	assert.equal(stuck.reloadsBeforeTimeout, 0)
	assert.equal(stuck.reloads, 1)
	const none = await runSwClient({ waiting: false, controllerChanges: false })
	assert.equal(none.bannerShown, false)
	assert.equal(none.reloads, 1)
})

test('SW takes over on both SKIP_WAITING message forms and claims clients', () => {
	const src = renderServiceWorker('t')
	const handlers: Record<string, (e: unknown) => void> = {}
	let skipped = 0
	const self = { location: { pathname: '/apps/factory/sw.js', origin: 'https://x' }, addEventListener: (t: string, f: (e: unknown) => void) => { handlers[t] = f }, skipWaiting: () => { skipped++ }, registration: {}, clients: { claim: async () => {} } }
	new Function('self', 'caches', 'fetch', src)(self, {}, () => {})
	handlers.message!({ data: 'SKIP_WAITING' })
	handlers.message!({ data: { type: 'SKIP_WAITING' } })
	handlers.message!({ data: 'other' })
	assert.equal(skipped, 2)
	assert.match(src, /self\.clients\.claim\(\)/)
})