Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/grok-bot

Wake a named Grok Bot from Kody by posting a prompt to that bot's own Cursor webhook.

FollowFork

Files

wake-quiet.node.test.ts

149 lines · 5.7 KB · TypeScript
import '../test/kody-mocks.mjs'
import assert from 'node:assert/strict'
import { afterEach, beforeEach, describe, it } from 'node:test'
// @ts-expect-error plain JS test helper
import { createStorageMock } from '../test/storage-mock.mjs'

// Ids must match stamp-declared kody.credentials slots (fetch is mocked; nothing is sent).
const BOT_ID = '021d6409-01e7-4af0-a59c-4cbf2785cb50'
const LILLY_ID = '57072205-edee-46ed-b4fa-a24b657ef369'
let mock = createStorageMock()
let statusImpl: (input: { bot?: string }) => unknown = async () => ({ quiet: false })
const statusCalls: Array<{ bot?: string }> = []

const mocks = (globalThis as any).__kodyMocks
mocks['kody:runtime'] = {
	packageStorage: () => mock.storage,
	packageContext: undefined,
	kody: {
		secretList: async () => [BOT_ID, LILLY_ID].map((id) => ({
			name: `grokBotWake.${id}`,
			scope: 'package',
			allowed_hosts: ['api2.cursor.sh'],
			allowedHosts: ['api2.cursor.sh'],
		})),
	},
}
mocks['kody:@kentcdodds/quiet-hours/status'] = {
	default: (input: { bot?: string }) => {
		statusCalls.push(input)
		return statusImpl(input)
	},
}

const { quietStamp } = await import('./quiet-stamp.ts')
const { default: wake, buildWakeBody, normalizeWakeFields } = await import('./wake.ts')
const { writeBotRecord, secretNameFor } = (await import('./registry.ts')) as any

const posted: any[] = []
const originalFetch = globalThis.fetch

async function seedBot(id: string, name: string) {
	await writeBotRecord({
		id,
		name,
		aliases: [name.toLowerCase()],
		url: 'https://api2.cursor.sh/automations/webhook/test-' + name,
		secretName: secretNameFor ? secretNameFor(id) : `grokBotWake.${id}`,
	})
}

beforeEach(async () => {
	mock = createStorageMock()
	statusCalls.length = 0
	posted.length = 0
	globalThis.fetch = (async (_url: unknown, init?: RequestInit) => {
		posted.push(JSON.parse(String(init?.body)))
		return new Response('{}', { status: 200 })
	}) as typeof fetch
	await seedBot(BOT_ID, 'Cole')
	await seedBot(LILLY_ID, 'Lilly')
})
afterEach(() => {
	globalThis.fetch = originalFetch
})

const UNTIL = '2026-10-18T14:00:00.000Z'

describe('quietStamp', () => {
	it('stamps during quiet hours and asks status for this bot', async () => {
		const stamp = await quietStamp('Cole', { status: async () => ({ quiet: true, until: UNTIL }) })
		assert.deepEqual(stamp, { quiet: true, quietUntil: UNTIL })
	})
	it('no stamp when not quiet, on error, on timeout, or on garbage', async () => {
		assert.equal(await quietStamp('Cole', { status: async () => ({ quiet: false, until: UNTIL }) }), null)
		assert.equal(await quietStamp('Cole', { status: async () => { throw new Error('down') } }), null)
		assert.equal(await quietStamp('Cole', { status: () => new Promise(() => {}), timeoutMs: 20 }), null)
		assert.equal(await quietStamp('Cole', { status: async () => ({ quiet: true }) }), null)
	})
})

describe('buildWakeBody', () => {
	it('adds quiet + quietUntil only when stamped; other fields unchanged', () => {
		const fields = normalizeWakeFields({ bot: 'Cole', prompt: 'hi', discordChannelId: '42' })
		const record = { id: BOT_ID, name: 'Cole' }
		assert.deepEqual(buildWakeBody(record, fields), { id: BOT_ID, name: 'Cole', prompt: 'hi', discordChannelId: '42' })
		assert.deepEqual(buildWakeBody(record, fields, { quiet: true, quietUntil: UNTIL }), {
			id: BOT_ID,
			name: 'Cole',
			prompt: 'hi',
			discordChannelId: '42',
			quiet: true,
			quietUntil: UNTIL,
		})
	})
})

describe('wake end to end (mocked webhook)', () => {
	it('stamps every wake sent during quiet hours', async () => {
		statusImpl = async () => ({ quiet: true, until: UNTIL, override: null })
		const result = await wake({ bot: 'Cole', prompt: 'Sentry spike' })
		assert.equal(result.ok, true)
		assert.equal(posted.length, 1)
		assert.equal(posted[0].quiet, true)
		assert.equal(posted[0].quietUntil, UNTIL)
		assert.equal(posted[0].prompt, 'Sentry spike', 'prompt text is untouched')
		assert.deepEqual(statusCalls.at(-1), { bot: 'Cole' })
	})
	it('daytime wakes carry no quiet fields', async () => {
		statusImpl = async () => ({ quiet: false, until: UNTIL, override: null })
		await wake({ bot: 'Cole', prompt: 'hi' })
		assert.equal('quiet' in posted[0], false)
		assert.equal('quietUntil' in posted[0], false)
	})
	it('Lilly is not stamped (quiet-hours reports her excluded)', async () => {
		statusImpl = async (input) =>
			input.bot?.toLowerCase() === 'lilly'
				? { quiet: false, until: UNTIL, override: null, excluded: true }
				: { quiet: true, until: UNTIL, override: null }
		await wake({ bot: 'Lilly', prompt: 'hi' })
		assert.equal('quiet' in posted[0], false)
	})
	it('quiet-hours failure still wakes the bot (unstamped)', async () => {
		statusImpl = async () => {
			throw new Error('quiet-hours unreachable')
		}
		const result = await wake({ bot: 'Cole', prompt: 'hi' })
		assert.equal(result.ok, true)
		assert.equal(posted.length, 1)
		assert.equal('quiet' in posted[0], false)
	})
	it('dryRun reports the stamp without posting', async () => {
		statusImpl = async () => ({ quiet: true, until: UNTIL, override: null })
		const result: any = await wake({ bot: 'Cole', prompt: 'hi', dryRun: true })
		assert.equal(result.dryRun, true)
		assert.equal(result.quiet, true)
		assert.equal(result.quietUntil, UNTIL)
		assert.equal(posted.length, 0)
	})
})

describe('serializeWakeBody', () => {
	it('never emits a raw {{ placeholder opener but round-trips the prompt', async () => {
		const { serializeWakeBody } = await import('./wake.ts')
		const prompt = 'issue text uses `{{secret:githubAccessToken}}` and {{{x}}}'
		const raw = serializeWakeBody({ id: 'a', name: 'b', prompt, nested: { k: [{ v: 1 }] } })
		assert.equal(raw.includes('{{'), false)
		assert.deepEqual(JSON.parse(raw), { id: 'a', name: 'b', prompt, nested: { k: [{ v: 1 }] } })
	})
})