mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Add cron-based scheduling with prompt templates integration (#164)
This commit is contained in:
1 parent
cbd0ee2958
commit
1e863c5fc5
63 files changed
+7797
-64
No files matched your search
@@ -0,0 +1,164 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
promptService: {
|
||||
list: vi.fn(),
|
||||
getById: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/prompt-templates', () => ({
|
||||
PromptTemplateService: vi.fn().mockImplementation(() => mocks.promptService),
|
||||
PromptTemplateServiceError: class PromptTemplateServiceError extends Error {
|
||||
constructor(message: string, public statusCode: number = 500) {
|
||||
super(message)
|
||||
this.name = 'PromptTemplateServiceError'
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { createPromptTemplateRoutes } from '../../src/routes/prompt-templates'
|
||||
import { PromptTemplateServiceError } from '../../src/services/prompt-templates'
|
||||
|
||||
describe('prompt template routes', () => {
|
||||
let app: ReturnType<typeof createPromptTemplateRoutes>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.promptService.list.mockReset()
|
||||
mocks.promptService.getById.mockReset()
|
||||
mocks.promptService.create.mockReset()
|
||||
mocks.promptService.update.mockReset()
|
||||
mocks.promptService.delete.mockReset()
|
||||
|
||||
app = createPromptTemplateRoutes({} as never)
|
||||
})
|
||||
|
||||
it('lists all templates including seeded ones from migration', async () => {
|
||||
const mockTemplates = [
|
||||
{ id: 1, title: 'Repo Health Report', category: 'Health', cadence_hint: 'Daily', suggested_name: 'repo-health', suggested_description: 'Report', description: 'Report', prompt: 'Check health' },
|
||||
{ id: 2, title: 'Dependency Watchlist', category: 'Dependencies', cadence_hint: 'Weekly', suggested_name: 'dep-watch', suggested_description: 'Watch deps', description: 'Watch', prompt: 'Watch deps' },
|
||||
]
|
||||
mocks.promptService.list.mockReturnValue(mockTemplates)
|
||||
|
||||
const response = await app.request('/')
|
||||
expect(response.status).toBe(200)
|
||||
|
||||
const body = await response.json() as { templates: Array<{ id: number; title: string }> }
|
||||
expect(body.templates.length).toBe(2)
|
||||
expect(body.templates[0]?.title).toBe('Repo Health Report')
|
||||
expect(body.templates[1]?.title).toBe('Dependency Watchlist')
|
||||
})
|
||||
|
||||
it('creates a template and returns 201', async () => {
|
||||
const newTemplate = {
|
||||
title: 'Test Template',
|
||||
category: 'Test',
|
||||
cadenceHint: 'Daily',
|
||||
suggestedName: 'Test job name',
|
||||
suggestedDescription: 'Test description',
|
||||
description: 'Test description',
|
||||
prompt: 'Test prompt content',
|
||||
}
|
||||
|
||||
const createdTemplate = { id: 1, ...newTemplate }
|
||||
mocks.promptService.create.mockReturnValue(createdTemplate)
|
||||
|
||||
const response = await app.request('/', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(newTemplate),
|
||||
})
|
||||
|
||||
expect(response.status).toBe(201)
|
||||
const body = await response.json() as { template: { id: number; title: string } }
|
||||
expect(body.template.title).toBe('Test Template')
|
||||
expect(body.template.id).toBe(1)
|
||||
})
|
||||
|
||||
it('gets a template by id', async () => {
|
||||
const mockTemplate = { id: 1, title: 'Get Test', category: 'Test', cadence_hint: 'Daily', suggested_name: 'get-test', suggested_description: '', description: '', prompt: 'Test prompt' }
|
||||
mocks.promptService.getById.mockReturnValue(mockTemplate)
|
||||
|
||||
const getResponse = await app.request('/1')
|
||||
expect(getResponse.status).toBe(200)
|
||||
|
||||
const body = await getResponse.json() as { template: { id: number; title: string } }
|
||||
expect(body.template.id).toBe(1)
|
||||
expect(body.template.title).toBe('Get Test')
|
||||
})
|
||||
|
||||
it('returns 404 for missing template', async () => {
|
||||
mocks.promptService.getById.mockImplementation(() => {
|
||||
throw new PromptTemplateServiceError('Template not found', 404)
|
||||
})
|
||||
|
||||
const response = await app.request('/99999')
|
||||
expect(response.status).toBe(404)
|
||||
|
||||
const body = await response.json() as { error: string }
|
||||
expect(body.error).toBe('Template not found')
|
||||
})
|
||||
|
||||
it('updates a template', async () => {
|
||||
const updatedTemplate = { id: 1, title: 'Updated Title', category: 'Test', cadence_hint: 'Daily', suggested_name: 'updated', suggested_description: '', description: '', prompt: 'Test prompt' }
|
||||
mocks.promptService.update.mockReturnValue(updatedTemplate)
|
||||
|
||||
const updateResponse = await app.request('/1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: 'Updated Title' }),
|
||||
})
|
||||
|
||||
expect(updateResponse.status).toBe(200)
|
||||
const body = await updateResponse.json() as { template: { title: string } }
|
||||
expect(body.template.title).toBe('Updated Title')
|
||||
})
|
||||
|
||||
it('returns 404 when updating missing template', async () => {
|
||||
mocks.promptService.update.mockImplementation(() => {
|
||||
throw new PromptTemplateServiceError('Template not found', 404)
|
||||
})
|
||||
|
||||
const response = await app.request('/99999', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: 'Nope' }),
|
||||
})
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('deletes a template and returns 204', async () => {
|
||||
mocks.promptService.delete.mockReturnValue(undefined)
|
||||
|
||||
const deleteResponse = await app.request('/1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(deleteResponse.status).toBe(204)
|
||||
})
|
||||
|
||||
it('returns 404 when deleting missing template', async () => {
|
||||
mocks.promptService.delete.mockImplementation(() => {
|
||||
throw new PromptTemplateServiceError('Template not found', 404)
|
||||
})
|
||||
|
||||
const response = await app.request('/99999', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,231 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
class MockScheduleServiceError extends Error {
|
||||
status: number
|
||||
|
||||
constructor(message: string, status: number) {
|
||||
super(message)
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
MockScheduleServiceError,
|
||||
scheduleService: {
|
||||
listJobs: vi.fn(),
|
||||
createJob: vi.fn(),
|
||||
getJob: vi.fn(),
|
||||
updateJob: vi.fn(),
|
||||
deleteJob: vi.fn(),
|
||||
runJob: vi.fn(),
|
||||
listRuns: vi.fn(),
|
||||
getRun: vi.fn(),
|
||||
cancelRun: vi.fn(),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../src/services/schedules', () => ({
|
||||
ScheduleService: vi.fn().mockImplementation(() => mocks.scheduleService),
|
||||
ScheduleServiceError: mocks.MockScheduleServiceError,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { createScheduleRoutes } from '../../src/routes/schedules'
|
||||
|
||||
describe('Schedule Routes', () => {
|
||||
let app: Hono
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
app = new Hono()
|
||||
app.route('/repos/:id/schedules', createScheduleRoutes({} as never))
|
||||
})
|
||||
|
||||
it('lists jobs for a repo', async () => {
|
||||
mocks.scheduleService.listJobs.mockReturnValue([{ id: 7, name: 'Weekly engineering summary' }])
|
||||
|
||||
const response = await app.request('/repos/42/schedules')
|
||||
const body = await response.json() as { jobs: Array<{ id: number }> }
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.jobs).toHaveLength(1)
|
||||
expect(mocks.scheduleService.listJobs).toHaveBeenCalledWith(42)
|
||||
})
|
||||
|
||||
it('creates a schedule from a valid request body', async () => {
|
||||
mocks.scheduleService.createJob.mockReturnValue({ id: 7, name: 'Daily release summary' })
|
||||
|
||||
const response = await app.request('/repos/42/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Daily release summary',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
prompt: 'Summarize release readiness.',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as { job: { id: number } }
|
||||
|
||||
expect(response.status).toBe(201)
|
||||
expect(body.job.id).toBe(7)
|
||||
expect(mocks.scheduleService.createJob).toHaveBeenCalledWith(42, expect.objectContaining({ name: 'Daily release summary' }))
|
||||
})
|
||||
|
||||
it('runs a schedule manually', async () => {
|
||||
mocks.scheduleService.runJob.mockResolvedValue({ id: 5, status: 'running' })
|
||||
|
||||
const response = await app.request('/repos/42/schedules/7/run', {
|
||||
method: 'POST',
|
||||
})
|
||||
const body = await response.json() as { run: { id: number; status: string } }
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.run).toEqual({ id: 5, status: 'running' })
|
||||
expect(mocks.scheduleService.runJob).toHaveBeenCalledWith(42, 7, 'manual')
|
||||
})
|
||||
|
||||
it('cancels a running schedule run', async () => {
|
||||
mocks.scheduleService.cancelRun.mockResolvedValue({ id: 5, status: 'cancelled' })
|
||||
|
||||
const response = await app.request('/repos/42/schedules/7/runs/5/cancel', {
|
||||
method: 'POST',
|
||||
})
|
||||
const body = await response.json() as { run: { status: string } }
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.run.status).toBe('cancelled')
|
||||
expect(mocks.scheduleService.cancelRun).toHaveBeenCalledWith(42, 7, 5)
|
||||
})
|
||||
|
||||
it('maps service conflicts to HTTP 409 responses', async () => {
|
||||
mocks.scheduleService.runJob.mockRejectedValue(new mocks.MockScheduleServiceError('Schedule is already running', 409))
|
||||
|
||||
const response = await app.request('/repos/42/schedules/7/run', {
|
||||
method: 'POST',
|
||||
})
|
||||
const body = await response.json() as { error: string }
|
||||
|
||||
expect(response.status).toBe(409)
|
||||
expect(body.error).toBe('Schedule is already running')
|
||||
})
|
||||
|
||||
it('returns 400 for invalid route ids before reaching the service', async () => {
|
||||
const response = await app.request('/repos/not-a-number/schedules')
|
||||
const body = await response.json() as { error: string }
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body.error).toBe('Invalid repo id')
|
||||
expect(mocks.scheduleService.listJobs).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('loads and updates a single schedule job', async () => {
|
||||
mocks.scheduleService.getJob.mockReturnValue({ id: 7, name: 'Weekly engineering summary' })
|
||||
mocks.scheduleService.updateJob.mockReturnValue({ id: 7, name: 'Updated engineering summary' })
|
||||
|
||||
const getResponse = await app.request('/repos/42/schedules/7')
|
||||
const getBody = await getResponse.json() as { job: { name: string } }
|
||||
|
||||
const patchResponse = await app.request('/repos/42/schedules/7', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Updated engineering summary' }),
|
||||
})
|
||||
const patchBody = await patchResponse.json() as { job: { name: string } }
|
||||
|
||||
expect(getResponse.status).toBe(200)
|
||||
expect(getBody.job.name).toBe('Weekly engineering summary')
|
||||
expect(patchResponse.status).toBe(200)
|
||||
expect(patchBody.job.name).toBe('Updated engineering summary')
|
||||
})
|
||||
|
||||
it('lists runs, loads a single run, and deletes a schedule', async () => {
|
||||
mocks.scheduleService.listRuns.mockReturnValue([{ id: 5, status: 'completed' }])
|
||||
mocks.scheduleService.getRun.mockReturnValue({ id: 5, status: 'completed' })
|
||||
mocks.scheduleService.deleteJob.mockReturnValue(undefined)
|
||||
|
||||
const runsResponse = await app.request('/repos/42/schedules/7/runs?limit=5')
|
||||
const runsBody = await runsResponse.json() as { runs: Array<{ id: number }> }
|
||||
|
||||
const runResponse = await app.request('/repos/42/schedules/7/runs/5')
|
||||
const runBody = await runResponse.json() as { run: { id: number } }
|
||||
|
||||
const deleteResponse = await app.request('/repos/42/schedules/7', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
const deleteBody = await deleteResponse.json() as { success: boolean }
|
||||
|
||||
expect(runsResponse.status).toBe(200)
|
||||
expect(runsBody.runs[0]?.id).toBe(5)
|
||||
expect(runResponse.status).toBe(200)
|
||||
expect(runBody.run.id).toBe(5)
|
||||
expect(deleteResponse.status).toBe(200)
|
||||
expect(deleteBody.success).toBe(true)
|
||||
expect(mocks.scheduleService.deleteJob).toHaveBeenCalledWith(42, 7)
|
||||
})
|
||||
|
||||
it('rejects non-positive run list limits', async () => {
|
||||
const response = await app.request('/repos/42/schedules/7/runs?limit=0')
|
||||
const body = await response.json() as { error: string }
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body.error).toBe('Limit must be greater than 0')
|
||||
expect(mocks.scheduleService.listRuns).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clamps large run list limits', async () => {
|
||||
mocks.scheduleService.listRuns.mockReturnValue([])
|
||||
|
||||
const response = await app.request('/repos/42/schedules/7/runs?limit=500')
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mocks.scheduleService.listRuns).toHaveBeenCalledWith(42, 7, 100)
|
||||
})
|
||||
|
||||
it('returns 404 when schedule job is not found', async () => {
|
||||
mocks.scheduleService.getJob.mockReturnValue(null)
|
||||
|
||||
const response = await app.request('/repos/42/schedules/7')
|
||||
const body = await response.json() as { error: string }
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body.error).toBe('Schedule not found')
|
||||
})
|
||||
|
||||
it('creates a cron schedule from a valid request body', async () => {
|
||||
mocks.scheduleService.createJob.mockReturnValue({ id: 8, name: 'Morning report' })
|
||||
|
||||
const response = await app.request('/repos/42/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Morning report',
|
||||
enabled: true,
|
||||
scheduleMode: 'cron',
|
||||
cronExpression: '0 9 * * *',
|
||||
timezone: 'America/New_York',
|
||||
prompt: 'Generate the daily report.',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as { job: { id: number } }
|
||||
|
||||
expect(response.status).toBe(201)
|
||||
expect(body.job.id).toBe(8)
|
||||
expect(mocks.scheduleService.createJob).toHaveBeenCalledWith(42, expect.objectContaining({
|
||||
scheduleMode: 'cron',
|
||||
cronExpression: '0 9 * * *',
|
||||
timezone: 'America/New_York',
|
||||
}))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,150 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
resolveOpenCodeModel: vi.fn(),
|
||||
fetch: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-models', () => ({
|
||||
resolveOpenCodeModel: mocks.resolveOpenCodeModel,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
ENV: {
|
||||
OPENCODE: { PORT: 5551 },
|
||||
},
|
||||
}))
|
||||
|
||||
import { createTitleRoutes } from '../../src/routes/title'
|
||||
|
||||
function jsonResponse(body: unknown, status: number = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
function textResponse(body: string, status: number = 200): Response {
|
||||
return new Response(body, { status })
|
||||
}
|
||||
|
||||
describe('Title Routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', modelID: 'gpt-5-mini' })
|
||||
vi.stubGlobal('fetch', mocks.fetch)
|
||||
vi.stubGlobal('Bun', { sleep: mocks.sleep })
|
||||
mocks.sleep.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('updates the session title from an immediate JSON prompt response', async () => {
|
||||
const app = createTitleRoutes()
|
||||
|
||||
mocks.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ id: 'title-session-1' }))
|
||||
.mockResolvedValueOnce(textResponse(JSON.stringify({
|
||||
parts: [{ type: 'text', text: 'Refactoring background jobs' }],
|
||||
})))
|
||||
.mockResolvedValueOnce(textResponse('', 200))
|
||||
.mockResolvedValueOnce(textResponse('', 200))
|
||||
|
||||
const response = await app.request('http://localhost/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
directory: '/workspace/repos/sample-project',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text: 'Refactor recurring background jobs and improve observability.',
|
||||
sessionID: 'session-main-1',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as { title: string }
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.title).toBe('Refactoring background jobs')
|
||||
expect(mocks.fetch).toHaveBeenCalledWith(
|
||||
'http://127.0.0.1:5551/session/session-main-1?directory=%2Fworkspace%2Frepos%2Fsample-project',
|
||||
expect.objectContaining({ method: 'PATCH' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('polls session messages when the prompt endpoint returns an empty body', async () => {
|
||||
const app = createTitleRoutes()
|
||||
|
||||
mocks.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ id: 'title-session-2' }))
|
||||
.mockResolvedValueOnce(textResponse(''))
|
||||
.mockResolvedValueOnce(jsonResponse([
|
||||
{
|
||||
info: { role: 'assistant', time: { completed: Date.now() } },
|
||||
parts: [{ type: 'text', text: 'Analyzing recurring job setup' }],
|
||||
},
|
||||
]))
|
||||
.mockResolvedValueOnce(textResponse('', 200))
|
||||
.mockResolvedValueOnce(textResponse('', 200))
|
||||
|
||||
const response = await app.request('http://localhost/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
directory: '/workspace/repos/sample-project',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text: 'Why do recurring jobs stop after a restart?',
|
||||
sessionID: 'session-main-2',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as { title: string }
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.title).toBe('Analyzing recurring job setup')
|
||||
expect(mocks.fetch).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
'http://127.0.0.1:5551/session/title-session-2/message?directory=%2Fworkspace%2Frepos%2Fsample-project',
|
||||
)
|
||||
})
|
||||
|
||||
it('returns a 500 when the polled assistant message reports an error', async () => {
|
||||
const app = createTitleRoutes()
|
||||
|
||||
mocks.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ id: 'title-session-3' }))
|
||||
.mockResolvedValueOnce(textResponse(''))
|
||||
.mockResolvedValueOnce(jsonResponse([
|
||||
{
|
||||
info: {
|
||||
role: 'assistant',
|
||||
error: { data: { message: 'Model unavailable' } },
|
||||
},
|
||||
parts: [],
|
||||
},
|
||||
]))
|
||||
.mockResolvedValueOnce(textResponse('', 200))
|
||||
|
||||
const response = await app.request('http://localhost/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
directory: '/workspace/repos/sample-project',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text: 'Generate a title for this broken run.',
|
||||
sessionID: 'session-main-3',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as { error: string }
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body.error).toBe('Model unavailable')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user