mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +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,49 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import migration007 from '../../src/db/migrations/007-schedules'
|
||||
import migration008 from '../../src/db/migrations/008-schedule-cron-support'
|
||||
|
||||
describe('schedule migrations', () => {
|
||||
it('creates schedule jobs with nullable interval minutes in v7', () => {
|
||||
const db = {
|
||||
run: vi.fn(),
|
||||
}
|
||||
|
||||
migration007.up(db as never)
|
||||
|
||||
expect(db.run).toHaveBeenCalledWith(expect.stringContaining('interval_minutes INTEGER,'))
|
||||
})
|
||||
|
||||
it('rebuilds schedule jobs for cron support in v8', () => {
|
||||
const db = {
|
||||
prepare: vi.fn().mockReturnValue({
|
||||
all: vi.fn().mockReturnValue([
|
||||
{ name: 'id', notnull: 0, dflt_value: null },
|
||||
{ name: 'repo_id', notnull: 1, dflt_value: null },
|
||||
{ name: 'name', notnull: 1, dflt_value: null },
|
||||
{ name: 'description', notnull: 0, dflt_value: null },
|
||||
{ name: 'enabled', notnull: 1, dflt_value: 'TRUE' },
|
||||
{ name: 'interval_minutes', notnull: 1, dflt_value: null },
|
||||
{ name: 'agent_slug', notnull: 0, dflt_value: null },
|
||||
{ name: 'prompt', notnull: 1, dflt_value: null },
|
||||
{ name: 'model', notnull: 0, dflt_value: null },
|
||||
{ name: 'skill_metadata', notnull: 0, dflt_value: null },
|
||||
{ name: 'created_at', notnull: 1, dflt_value: null },
|
||||
{ name: 'updated_at', notnull: 1, dflt_value: null },
|
||||
{ name: 'last_run_at', notnull: 0, dflt_value: null },
|
||||
{ name: 'next_run_at', notnull: 0, dflt_value: null },
|
||||
]),
|
||||
}),
|
||||
run: vi.fn(),
|
||||
}
|
||||
|
||||
migration008.up(db as never)
|
||||
|
||||
expect(db.prepare).toHaveBeenCalledWith('PRAGMA table_info(schedule_jobs)')
|
||||
expect(db.run).toHaveBeenCalledWith(expect.stringContaining('CREATE TABLE schedule_jobs_new'))
|
||||
expect(db.run).toHaveBeenCalledWith(expect.stringContaining('interval_minutes INTEGER,'))
|
||||
expect(db.run).toHaveBeenCalledWith(expect.stringContaining("schedule_mode TEXT NOT NULL DEFAULT 'interval'"))
|
||||
expect(db.run).toHaveBeenCalledWith(expect.stringContaining("'interval'"))
|
||||
expect(db.run).toHaveBeenCalledWith('DROP TABLE schedule_jobs')
|
||||
expect(db.run).toHaveBeenCalledWith('ALTER TABLE schedule_jobs_new RENAME TO schedule_jobs')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,460 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import * as schedulesDb from '../../src/db/schedules'
|
||||
|
||||
const mockDb = {
|
||||
prepare: vi.fn(),
|
||||
} as any
|
||||
|
||||
function makeJobRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 7,
|
||||
repo_id: 42,
|
||||
name: 'Weekly engineering summary',
|
||||
description: 'Summarize repo health and recent changes.',
|
||||
enabled: 1,
|
||||
schedule_mode: 'cron',
|
||||
interval_minutes: null,
|
||||
cron_expression: '0 9 * * 1',
|
||||
timezone: 'UTC',
|
||||
agent_slug: 'planner',
|
||||
prompt: 'Generate a weekly summary.',
|
||||
model: 'openai/gpt-5-mini',
|
||||
skill_metadata: JSON.stringify({ skillSlugs: ['planning'], notes: 'Optional notes' }),
|
||||
created_at: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
updated_at: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
last_run_at: Date.UTC(2026, 2, 9, 11, 0, 0),
|
||||
next_run_at: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeRunRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 5,
|
||||
job_id: 7,
|
||||
repo_id: 42,
|
||||
trigger_source: 'manual',
|
||||
status: 'running',
|
||||
started_at: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
finished_at: null,
|
||||
created_at: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
session_id: 'ses-1',
|
||||
session_title: 'Scheduled: Weekly engineering summary',
|
||||
log_text: 'Run started. Waiting for assistant response...',
|
||||
response_text: null,
|
||||
error_text: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('schedule database queries', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('lists schedule jobs and parses persisted metadata', () => {
|
||||
const stmt = {
|
||||
all: vi.fn().mockReturnValue([makeJobRow()]),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const jobs = schedulesDb.listScheduleJobsByRepo(mockDb, 42)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
|
||||
expect(jobs[0]).toMatchObject({
|
||||
id: 7,
|
||||
repoId: 42,
|
||||
scheduleMode: 'cron',
|
||||
skillMetadata: {
|
||||
skillSlugs: ['planning'],
|
||||
notes: 'Optional notes',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('creates a schedule job and reloads the inserted row', () => {
|
||||
const insertStmt = {
|
||||
run: vi.fn().mockReturnValue({ lastInsertRowid: 7 }),
|
||||
}
|
||||
const selectStmt = {
|
||||
get: vi.fn().mockReturnValue(makeJobRow()),
|
||||
}
|
||||
|
||||
mockDb.prepare.mockReturnValueOnce(insertStmt).mockReturnValueOnce(selectStmt)
|
||||
|
||||
const job = schedulesDb.createScheduleJob(mockDb, 42, {
|
||||
name: 'Weekly engineering summary',
|
||||
description: 'Summarize repo health and recent changes.',
|
||||
enabled: true,
|
||||
scheduleMode: 'cron',
|
||||
intervalMinutes: null,
|
||||
cronExpression: '0 9 * * 1',
|
||||
timezone: 'UTC',
|
||||
agentSlug: 'planner',
|
||||
prompt: 'Generate a weekly summary.',
|
||||
model: 'openai/gpt-5-mini',
|
||||
skillMetadata: { skillSlugs: ['planning'], notes: 'Optional notes' },
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
})
|
||||
|
||||
expect(insertStmt.run).toHaveBeenCalledWith(
|
||||
42,
|
||||
'Weekly engineering summary',
|
||||
'Summarize repo health and recent changes.',
|
||||
1,
|
||||
'cron',
|
||||
null,
|
||||
'0 9 * * 1',
|
||||
'UTC',
|
||||
'planner',
|
||||
'Generate a weekly summary.',
|
||||
'openai/gpt-5-mini',
|
||||
JSON.stringify({ skillSlugs: ['planning'], notes: 'Optional notes' }),
|
||||
expect.any(Number),
|
||||
expect.any(Number),
|
||||
null,
|
||||
Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
)
|
||||
expect(job.id).toBe(7)
|
||||
})
|
||||
|
||||
it('updates a schedule job when it exists', () => {
|
||||
const existingStmt = {
|
||||
get: vi.fn().mockReturnValue(makeJobRow({ name: 'Existing summary' })),
|
||||
}
|
||||
const updateStmt = {
|
||||
run: vi.fn(),
|
||||
}
|
||||
const reloadStmt = {
|
||||
get: vi.fn().mockReturnValue(makeJobRow({ name: 'Updated summary', enabled: 0, skill_metadata: null })),
|
||||
}
|
||||
|
||||
mockDb.prepare
|
||||
.mockReturnValueOnce(existingStmt)
|
||||
.mockReturnValueOnce(updateStmt)
|
||||
.mockReturnValueOnce(reloadStmt)
|
||||
|
||||
const job = schedulesDb.updateScheduleJob(mockDb, 42, 7, {
|
||||
name: 'Updated summary',
|
||||
description: null,
|
||||
enabled: false,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 90,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Run a new summary.',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
nextRunAt: null,
|
||||
})
|
||||
|
||||
expect(updateStmt.run).toHaveBeenCalledWith(
|
||||
'Updated summary',
|
||||
null,
|
||||
0,
|
||||
'interval',
|
||||
90,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
'Run a new summary.',
|
||||
null,
|
||||
null,
|
||||
expect.any(Number),
|
||||
null,
|
||||
42,
|
||||
7,
|
||||
)
|
||||
expect(job).toMatchObject({
|
||||
name: 'Updated summary',
|
||||
enabled: false,
|
||||
skillMetadata: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null when updating metadata for a missing run', () => {
|
||||
const selectStmt = {
|
||||
get: vi.fn().mockReturnValue(undefined),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(selectStmt)
|
||||
|
||||
const run = schedulesDb.updateScheduleRunMetadata(mockDb, 42, 7, 5, {
|
||||
sessionTitle: 'Updated title',
|
||||
})
|
||||
|
||||
expect(run).toBeNull()
|
||||
})
|
||||
|
||||
it('updates schedule run metadata while preserving omitted fields', () => {
|
||||
const existingRun = makeRunRow({ response_text: 'Existing response', error_text: 'Existing error' })
|
||||
const existingStmt = {
|
||||
get: vi.fn().mockReturnValue(existingRun),
|
||||
}
|
||||
const updateStmt = {
|
||||
run: vi.fn(),
|
||||
}
|
||||
const reloadStmt = {
|
||||
get: vi.fn().mockReturnValue(makeRunRow({ session_title: 'Updated title', response_text: 'Existing response', error_text: 'Existing error' })),
|
||||
}
|
||||
|
||||
mockDb.prepare
|
||||
.mockReturnValueOnce(existingStmt)
|
||||
.mockReturnValueOnce(updateStmt)
|
||||
.mockReturnValueOnce(reloadStmt)
|
||||
|
||||
const run = schedulesDb.updateScheduleRunMetadata(mockDb, 42, 7, 5, {
|
||||
sessionTitle: 'Updated title',
|
||||
})
|
||||
|
||||
expect(updateStmt.run).toHaveBeenCalledWith(
|
||||
'ses-1',
|
||||
'Updated title',
|
||||
'Run started. Waiting for assistant response...',
|
||||
'Existing response',
|
||||
'Existing error',
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
)
|
||||
expect(run?.sessionTitle).toBe('Updated title')
|
||||
})
|
||||
|
||||
it('creates and reloads a schedule run', () => {
|
||||
const insertStmt = {
|
||||
run: vi.fn().mockReturnValue({ lastInsertRowid: 5 }),
|
||||
}
|
||||
const selectStmt = {
|
||||
get: vi.fn().mockReturnValue(makeRunRow()),
|
||||
}
|
||||
|
||||
mockDb.prepare.mockReturnValueOnce(insertStmt).mockReturnValueOnce(selectStmt)
|
||||
|
||||
const run = schedulesDb.createScheduleRun(mockDb, {
|
||||
jobId: 7,
|
||||
repoId: 42,
|
||||
triggerSource: 'manual',
|
||||
status: 'running',
|
||||
startedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
})
|
||||
|
||||
expect(insertStmt.run).toHaveBeenCalledWith(7, 42, 'manual', 'running', expect.any(Number), expect.any(Number))
|
||||
expect(run.id).toBe(5)
|
||||
})
|
||||
|
||||
it('lists active runs and maps persisted fields', () => {
|
||||
const stmt = {
|
||||
all: vi.fn().mockReturnValue([
|
||||
makeRunRow({ id: 5 }),
|
||||
makeRunRow({ id: 6, status: 'failed', error_text: 'Model unavailable' }),
|
||||
]),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const runs = schedulesDb.listRunningScheduleRuns(mockDb, 10)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('WHERE status = \'running\''))
|
||||
expect(runs).toHaveLength(2)
|
||||
expect(runs[1]).toMatchObject({ id: 6, status: 'failed', errorText: 'Model unavailable' })
|
||||
})
|
||||
|
||||
it('lists run summaries without loading large log or response blobs', () => {
|
||||
const stmt = {
|
||||
all: vi.fn().mockReturnValue([
|
||||
makeRunRow({ log_text: null, response_text: null, error_text: 'Run failed' }),
|
||||
]),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const runs = schedulesDb.listScheduleRunsByJob(mockDb, 42, 7, 5)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('NULL AS log_text'))
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('NULL AS response_text'))
|
||||
expect(runs[0]).toMatchObject({
|
||||
id: 5,
|
||||
logText: null,
|
||||
responseText: null,
|
||||
errorText: 'Run failed',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns the running run for a job when present', () => {
|
||||
const stmt = {
|
||||
get: vi.fn().mockReturnValue(makeRunRow({ id: 8 })),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const run = schedulesDb.getRunningScheduleRunByJob(mockDb, 42, 7)
|
||||
|
||||
expect(run).toMatchObject({ id: 8, sessionId: 'ses-1' })
|
||||
})
|
||||
|
||||
it('lists due schedule jobs ordered by next run time', () => {
|
||||
const now = Date.now()
|
||||
const limit = 10
|
||||
const jobRow = makeJobRow()
|
||||
const stmt = {
|
||||
all: vi.fn().mockReturnValue([jobRow]),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const jobs = schedulesDb.listDueScheduleJobs(mockDb, now, limit)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('WHERE enabled = 1 AND next_run_at IS NOT NULL AND next_run_at <= ?'))
|
||||
expect(stmt.all).toHaveBeenCalledWith(now, limit)
|
||||
expect(jobs).toHaveLength(1)
|
||||
expect(jobs.at(0)?.id).toBe(7)
|
||||
})
|
||||
|
||||
it('lists enabled schedule jobs ordered by id', () => {
|
||||
const jobRow = makeJobRow()
|
||||
const stmt = {
|
||||
all: vi.fn().mockReturnValue([jobRow]),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const jobs = schedulesDb.listEnabledScheduleJobs(mockDb)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_jobs WHERE enabled = 1 ORDER BY id ASC')
|
||||
expect(stmt.all).toHaveBeenCalledWith()
|
||||
expect(jobs).toHaveLength(1)
|
||||
expect(jobs.at(0)?.enabled).toBe(true)
|
||||
})
|
||||
|
||||
it('gets a schedule job by id when found', () => {
|
||||
const jobRow = makeJobRow()
|
||||
const stmt = {
|
||||
get: vi.fn().mockReturnValue(jobRow),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const job = schedulesDb.getScheduleJobById(mockDb, 42, 7)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||
expect(stmt.get).toHaveBeenCalledWith(42, 7)
|
||||
expect(job).toMatchObject({ id: 7, repoId: 42, name: 'Weekly engineering summary' })
|
||||
})
|
||||
|
||||
it('returns null when schedule job is not found', () => {
|
||||
const stmt = {
|
||||
get: vi.fn().mockReturnValue(undefined),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const job = schedulesDb.getScheduleJobById(mockDb, 42, 7)
|
||||
|
||||
expect(job).toBeNull()
|
||||
})
|
||||
|
||||
it('deletes a schedule job successfully', () => {
|
||||
const stmt = {
|
||||
run: vi.fn().mockReturnValue({ changes: 1 }),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const result = schedulesDb.deleteScheduleJob(mockDb, 42, 7)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||
expect(stmt.run).toHaveBeenCalledWith(42, 7)
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false when deleting a non-existent schedule job', () => {
|
||||
const stmt = {
|
||||
run: vi.fn().mockReturnValue({ changes: 0 }),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const result = schedulesDb.deleteScheduleJob(mockDb, 42, 7)
|
||||
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('reserves the next run time for a schedule job', () => {
|
||||
const nextRunAt = Date.now() + 3600000
|
||||
const stmt = {
|
||||
run: vi.fn(),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
schedulesDb.reserveScheduleJobNextRun(mockDb, 42, 7, nextRunAt)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('UPDATE schedule_jobs SET next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
|
||||
expect(stmt.run).toHaveBeenCalledWith(nextRunAt, expect.any(Number), 42, 7)
|
||||
})
|
||||
|
||||
it('updates the run state of a schedule job', () => {
|
||||
const lastRunAt = Date.now()
|
||||
const nextRunAt = Date.now() + 3600000
|
||||
const stmt = {
|
||||
run: vi.fn(),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
schedulesDb.updateScheduleJobRunState(mockDb, 42, 7, { lastRunAt, nextRunAt })
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
|
||||
expect(stmt.run).toHaveBeenCalledWith(lastRunAt, nextRunAt, expect.any(Number), 42, 7)
|
||||
})
|
||||
|
||||
it('updates a schedule run and reloads the result', () => {
|
||||
const updateStmt = {
|
||||
run: vi.fn(),
|
||||
}
|
||||
const selectStmt = {
|
||||
get: vi.fn().mockReturnValue(makeRunRow({ status: 'completed', response_text: 'Completed' })),
|
||||
}
|
||||
|
||||
mockDb.prepare.mockReturnValueOnce(updateStmt).mockReturnValueOnce(selectStmt)
|
||||
|
||||
const run = schedulesDb.updateScheduleRun(mockDb, 42, 7, 5, {
|
||||
status: 'completed',
|
||||
finishedAt: Date.now(),
|
||||
sessionId: 'ses-1',
|
||||
sessionTitle: 'Updated title',
|
||||
logText: 'Log output',
|
||||
responseText: 'Completed',
|
||||
errorText: null,
|
||||
})
|
||||
|
||||
expect(updateStmt.run).toHaveBeenCalledWith(
|
||||
'completed',
|
||||
expect.any(Number),
|
||||
'ses-1',
|
||||
'Updated title',
|
||||
'Log output',
|
||||
'Completed',
|
||||
null,
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
)
|
||||
expect(run).toMatchObject({ status: 'completed', responseText: 'Completed' })
|
||||
})
|
||||
|
||||
it('gets a schedule run by id when found', () => {
|
||||
const runRow = makeRunRow()
|
||||
const stmt = {
|
||||
get: vi.fn().mockReturnValue(runRow),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const run = schedulesDb.getScheduleRunById(mockDb, 42, 7, 5)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
|
||||
expect(stmt.get).toHaveBeenCalledWith(42, 7, 5)
|
||||
expect(run).toMatchObject({ id: 5, jobId: 7, repoId: 42, status: 'running' })
|
||||
})
|
||||
|
||||
it('returns null when schedule run is not found', () => {
|
||||
const stmt = {
|
||||
get: vi.fn().mockReturnValue(undefined),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const run = schedulesDb.getScheduleRunById(mockDb, 42, 7, 5)
|
||||
|
||||
expect(run).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { proxyToOpenCodeWithDirectory } = vi.hoisted(() => ({
|
||||
proxyToOpenCodeWithDirectory: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/proxy', () => ({
|
||||
proxyToOpenCodeWithDirectory,
|
||||
}))
|
||||
|
||||
import { resolveOpenCodeModel } from '../../src/services/opencode-models'
|
||||
|
||||
function jsonResponse(body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('resolveOpenCodeModel', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('returns the preferred model when it is available', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({ model: 'openai/gpt-5' }))
|
||||
}
|
||||
|
||||
return Promise.resolve(jsonResponse({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5': {}, 'gpt-5-mini': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5-mini' },
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||
preferredModel: 'openai/gpt-5',
|
||||
})
|
||||
|
||||
expect(result).toEqual({
|
||||
providerID: 'openai',
|
||||
modelID: 'gpt-5',
|
||||
model: 'openai/gpt-5',
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to the provider default when the preferred model is unavailable', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({ model: 'openai/gpt-5.4' }))
|
||||
}
|
||||
|
||||
return Promise.resolve(jsonResponse({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5.3-codex-spark': {}, 'gpt-5-mini': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5.3-codex-spark' },
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||
preferredModel: 'openai/gpt-5.4',
|
||||
})
|
||||
|
||||
expect(result).toEqual({
|
||||
providerID: 'openai',
|
||||
modelID: 'gpt-5.3-codex-spark',
|
||||
model: 'openai/gpt-5.3-codex-spark',
|
||||
})
|
||||
})
|
||||
|
||||
it('prefers the configured small model when requested', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({
|
||||
model: 'openai/gpt-5',
|
||||
small_model: 'openai/gpt-5-mini',
|
||||
}))
|
||||
}
|
||||
|
||||
return Promise.resolve(jsonResponse({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5': {}, 'gpt-5-mini': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5' },
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||
preferSmallModel: true,
|
||||
})
|
||||
|
||||
expect(result).toEqual({
|
||||
providerID: 'openai',
|
||||
modelID: 'gpt-5-mini',
|
||||
model: 'openai/gpt-5-mini',
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to the first available model when defaults are missing', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({}))
|
||||
}
|
||||
|
||||
return Promise.resolve(jsonResponse({
|
||||
providers: [
|
||||
{ id: 'anthropic', models: { 'claude-sonnet-4': {}, 'claude-haiku-4': {} } },
|
||||
],
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await resolveOpenCodeModel('/workspace/repos/sample-project')
|
||||
|
||||
expect(result).toEqual({
|
||||
providerID: 'anthropic',
|
||||
modelID: 'claude-sonnet-4',
|
||||
model: 'anthropic/claude-sonnet-4',
|
||||
})
|
||||
})
|
||||
|
||||
it('throws when no configured models are available', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({ model: 'openai/gpt-5' }))
|
||||
}
|
||||
|
||||
return Promise.resolve(jsonResponse({ providers: [], default: {} }))
|
||||
})
|
||||
|
||||
await expect(resolveOpenCodeModel('/workspace/repos/sample-project')).rejects.toThrow(
|
||||
'No configured OpenCode models are available',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,183 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { ScheduleJob } from '@opencode-manager/shared/types'
|
||||
import {
|
||||
buildCreateSchedulePersistenceInput,
|
||||
buildUpdatedSchedulePersistenceInput,
|
||||
computeNextRunAtForJob,
|
||||
} from '../../src/services/schedule-config'
|
||||
|
||||
describe('schedule-config', () => {
|
||||
it('builds interval schedule persistence input with trimmed fields', () => {
|
||||
const currentDate = Date.UTC(2026, 2, 9, 12, 0, 0)
|
||||
|
||||
const result = buildCreateSchedulePersistenceInput({
|
||||
name: ' Daily health check ',
|
||||
description: ' Summarize repo health ',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
prompt: ' Review the repository and summarize risks. ',
|
||||
agentSlug: ' code ',
|
||||
model: ' openai/gpt-5 ',
|
||||
}, currentDate)
|
||||
|
||||
expect(result).toEqual({
|
||||
name: 'Daily health check',
|
||||
description: 'Summarize repo health',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: 'code',
|
||||
prompt: 'Review the repository and summarize risks.',
|
||||
model: 'openai/gpt-5',
|
||||
skillMetadata: undefined,
|
||||
nextRunAt: currentDate + 60 * 60_000,
|
||||
})
|
||||
})
|
||||
|
||||
it('defaults cron schedules to UTC and computes the next run', () => {
|
||||
const currentDate = Date.UTC(2026, 2, 9, 8, 15, 0)
|
||||
|
||||
const result = buildCreateSchedulePersistenceInput({
|
||||
name: 'Morning report',
|
||||
enabled: true,
|
||||
scheduleMode: 'cron',
|
||||
cronExpression: ' 0 9 * * * ',
|
||||
timezone: ' ',
|
||||
prompt: 'Generate the daily report.',
|
||||
}, currentDate)
|
||||
|
||||
expect(result.scheduleMode).toBe('cron')
|
||||
expect(result.cronExpression).toBe('0 9 * * *')
|
||||
expect(result.timezone).toBe('UTC')
|
||||
expect(result.nextRunAt).toBe(Date.UTC(2026, 2, 9, 9, 0, 0))
|
||||
})
|
||||
|
||||
it('preserves the existing next run when only prompt text changes', () => {
|
||||
const existing: ScheduleJob = {
|
||||
id: 7,
|
||||
repoId: 42,
|
||||
name: 'Weekly engineering summary',
|
||||
description: 'Summarize health',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Old prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
}
|
||||
|
||||
const result = buildUpdatedSchedulePersistenceInput(existing, {
|
||||
prompt: ' New prompt body ',
|
||||
}, Date.UTC(2026, 2, 9, 12, 30, 0))
|
||||
|
||||
expect(result.prompt).toBe('New prompt body')
|
||||
expect(result.nextRunAt).toBe(existing.nextRunAt)
|
||||
})
|
||||
|
||||
it('normalizes optional text fields when updating a schedule', () => {
|
||||
const existing: ScheduleJob = {
|
||||
id: 10,
|
||||
repoId: 42,
|
||||
name: 'Weekly engineering summary',
|
||||
description: 'Existing description',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: 'planner',
|
||||
prompt: 'Old prompt',
|
||||
model: 'openai/gpt-5-mini',
|
||||
skillMetadata: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
}
|
||||
|
||||
const result = buildUpdatedSchedulePersistenceInput(existing, {
|
||||
description: ' ',
|
||||
agentSlug: ' reviewer ',
|
||||
model: ' ',
|
||||
}, Date.UTC(2026, 2, 9, 12, 30, 0))
|
||||
|
||||
expect(result.description).toBeNull()
|
||||
expect(result.agentSlug).toBe('reviewer')
|
||||
expect(result.model).toBeNull()
|
||||
})
|
||||
|
||||
it('recomputes the next run when a disabled schedule is re-enabled', () => {
|
||||
const existing: ScheduleJob = {
|
||||
id: 8,
|
||||
repoId: 42,
|
||||
name: 'Paused summary',
|
||||
description: null,
|
||||
enabled: false,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 30,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Run a report',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
nextRunAt: null,
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
}
|
||||
|
||||
const currentDate = Date.UTC(2026, 2, 9, 14, 0, 0)
|
||||
const result = buildUpdatedSchedulePersistenceInput(existing, {
|
||||
enabled: true,
|
||||
}, currentDate)
|
||||
|
||||
expect(result.enabled).toBe(true)
|
||||
expect(result.nextRunAt).toBe(currentDate + 30 * 60_000)
|
||||
})
|
||||
|
||||
it('throws for invalid cron timezones', () => {
|
||||
expect(() => buildCreateSchedulePersistenceInput({
|
||||
name: 'Invalid timezone',
|
||||
enabled: true,
|
||||
scheduleMode: 'cron',
|
||||
cronExpression: '0 9 * * *',
|
||||
timezone: 'Mars/Phobos',
|
||||
prompt: 'Test prompt',
|
||||
}, Date.UTC(2026, 2, 9, 8, 0, 0))).toThrow('Invalid timezone: Mars/Phobos')
|
||||
})
|
||||
|
||||
it('returns null for disabled jobs when computing the next run', () => {
|
||||
const job: ScheduleJob = {
|
||||
id: 9,
|
||||
repoId: 42,
|
||||
name: 'Disabled summary',
|
||||
description: null,
|
||||
enabled: false,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 15,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
nextRunAt: null,
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
}
|
||||
|
||||
expect(computeNextRunAtForJob(job, Date.UTC(2026, 2, 9, 12, 0, 0))).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,884 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ScheduleJob, ScheduleRun } from '@opencode-manager/shared/types'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getRepoById: vi.fn(),
|
||||
createScheduleJob: vi.fn(),
|
||||
createScheduleRun: vi.fn(),
|
||||
deleteScheduleJob: vi.fn(),
|
||||
getScheduleJobById: vi.fn(),
|
||||
getRunningScheduleRunByJob: vi.fn(),
|
||||
getScheduleRunById: vi.fn(),
|
||||
listDueScheduleJobs: vi.fn(),
|
||||
listEnabledScheduleJobs: vi.fn(),
|
||||
listRunningScheduleRuns: vi.fn(),
|
||||
listScheduleJobsByRepo: vi.fn(),
|
||||
listScheduleRunsByJob: vi.fn(),
|
||||
updateScheduleJob: vi.fn(),
|
||||
updateScheduleJobRunState: vi.fn(),
|
||||
updateScheduleRun: vi.fn(),
|
||||
updateScheduleRunMetadata: vi.fn(),
|
||||
buildCreateSchedulePersistenceInput: vi.fn(),
|
||||
buildUpdatedSchedulePersistenceInput: vi.fn(),
|
||||
computeNextRunAtForJob: vi.fn(),
|
||||
|
||||
resolveOpenCodeModel: vi.fn(),
|
||||
proxyToOpenCodeWithDirectory: vi.fn(),
|
||||
addClient: vi.fn(),
|
||||
onEvent: vi.fn(),
|
||||
loggerError: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/db/queries', () => ({
|
||||
getRepoById: mocks.getRepoById,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/db/schedules', () => ({
|
||||
createScheduleJob: mocks.createScheduleJob,
|
||||
createScheduleRun: mocks.createScheduleRun,
|
||||
deleteScheduleJob: mocks.deleteScheduleJob,
|
||||
getScheduleJobById: mocks.getScheduleJobById,
|
||||
getRunningScheduleRunByJob: mocks.getRunningScheduleRunByJob,
|
||||
getScheduleRunById: mocks.getScheduleRunById,
|
||||
listDueScheduleJobs: mocks.listDueScheduleJobs,
|
||||
listEnabledScheduleJobs: mocks.listEnabledScheduleJobs,
|
||||
listRunningScheduleRuns: mocks.listRunningScheduleRuns,
|
||||
listScheduleJobsByRepo: mocks.listScheduleJobsByRepo,
|
||||
listScheduleRunsByJob: mocks.listScheduleRunsByJob,
|
||||
updateScheduleJob: mocks.updateScheduleJob,
|
||||
updateScheduleJobRunState: mocks.updateScheduleJobRunState,
|
||||
updateScheduleRun: mocks.updateScheduleRun,
|
||||
updateScheduleRunMetadata: mocks.updateScheduleRunMetadata,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/schedule-config', () => ({
|
||||
buildCreateSchedulePersistenceInput: mocks.buildCreateSchedulePersistenceInput,
|
||||
buildUpdatedSchedulePersistenceInput: mocks.buildUpdatedSchedulePersistenceInput,
|
||||
computeNextRunAtForJob: mocks.computeNextRunAtForJob,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-models', () => ({
|
||||
resolveOpenCodeModel: mocks.resolveOpenCodeModel,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/proxy', () => ({
|
||||
proxyToOpenCodeWithDirectory: mocks.proxyToOpenCodeWithDirectory,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/sse-aggregator', () => ({
|
||||
sseAggregator: {
|
||||
addClient: mocks.addClient,
|
||||
onEvent: mocks.onEvent,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
error: mocks.loggerError,
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockCronStop = vi.fn()
|
||||
const mockCronInstances: Array<{ callback: () => void; options: Record<string, unknown>; pattern: string; stop: typeof mockCronStop }> = []
|
||||
|
||||
vi.mock('croner', () => ({
|
||||
Cron: vi.fn().mockImplementation((pattern: string, options: Record<string, unknown>, callback: () => void) => {
|
||||
const instance = { pattern, options, callback, stop: mockCronStop }
|
||||
mockCronInstances.push(instance)
|
||||
return instance
|
||||
}),
|
||||
}))
|
||||
|
||||
import { ScheduleRunner, ScheduleService } from '../../src/services/schedules'
|
||||
|
||||
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 })
|
||||
}
|
||||
|
||||
const repo = {
|
||||
id: 42,
|
||||
fullPath: '/workspace/repos/sample-project',
|
||||
localPath: 'sample-project',
|
||||
repoUrl: 'https://github.com/example/sample-project',
|
||||
}
|
||||
|
||||
const job: ScheduleJob = {
|
||||
id: 7,
|
||||
repoId: 42,
|
||||
name: 'Weekly engineering summary',
|
||||
description: 'Summarize repo health and recent changes.',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Review the repository and summarize the current state.',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
}
|
||||
|
||||
const baseRun: ScheduleRun = {
|
||||
id: 5,
|
||||
jobId: 7,
|
||||
repoId: 42,
|
||||
triggerSource: 'manual',
|
||||
status: 'running',
|
||||
startedAt: Date.UTC(2026, 2, 9, 12, 5, 0),
|
||||
finishedAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 9, 12, 5, 0),
|
||||
sessionId: null,
|
||||
sessionTitle: null,
|
||||
logText: null,
|
||||
responseText: null,
|
||||
errorText: null,
|
||||
}
|
||||
|
||||
describe('ScheduleService', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
Reflect.get(ScheduleService, 'activeRuns').clear()
|
||||
|
||||
mocks.getRepoById.mockReturnValue(repo)
|
||||
mocks.getScheduleJobById.mockReturnValue(job)
|
||||
mocks.getRunningScheduleRunByJob.mockReturnValue(null)
|
||||
mocks.createScheduleRun.mockReturnValue(baseRun)
|
||||
mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', modelID: 'gpt-5-mini' })
|
||||
mocks.addClient.mockReturnValue(vi.fn())
|
||||
mocks.onEvent.mockReturnValue(vi.fn())
|
||||
mocks.getScheduleRunById.mockReturnValue({
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-1',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started. Waiting for assistant response...',
|
||||
})
|
||||
})
|
||||
|
||||
it('starts a run immediately and completes it after polling session messages', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-1',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started. Waiting for assistant response...',
|
||||
}
|
||||
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return Promise.resolve(jsonResponse({ id: 'ses-run-1' }))
|
||||
}
|
||||
|
||||
if (path === '/session/ses-run-1/message' && method === 'POST') {
|
||||
return Promise.resolve(textResponse(''))
|
||||
}
|
||||
|
||||
if (path === '/session/ses-run-1/message' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([
|
||||
{
|
||||
info: { role: 'assistant', time: { completed: Date.now() } },
|
||||
parts: [{ type: 'text', text: 'System health is stable.' }],
|
||||
},
|
||||
]))
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
const result = await service.runJob(42, 7, 'manual')
|
||||
|
||||
expect(result).toEqual(runWithSession)
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({
|
||||
status: 'completed',
|
||||
responseText: 'System health is stable.',
|
||||
sessionId: 'ses-run-1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
expect(mocks.updateScheduleJobRunState).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
expect.objectContaining({ nextRunAt: job.nextRunAt }),
|
||||
)
|
||||
})
|
||||
|
||||
it('completes a run immediately when the prompt endpoint returns JSON', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-2',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started. Waiting for assistant response...',
|
||||
}
|
||||
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return Promise.resolve(jsonResponse({ id: 'ses-run-2' }))
|
||||
}
|
||||
|
||||
if (path === '/session/ses-run-2/message' && method === 'POST') {
|
||||
return Promise.resolve(textResponse(JSON.stringify({
|
||||
parts: [{ type: 'text', text: 'Immediate status summary.' }],
|
||||
})))
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
await service.runJob(42, 7, 'manual')
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({
|
||||
status: 'completed',
|
||||
responseText: 'Immediate status summary.',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a new run when the job already has a running entry', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
|
||||
mocks.getRunningScheduleRunByJob.mockReturnValue({
|
||||
...baseRun,
|
||||
sessionId: 'ses-existing',
|
||||
sessionTitle: 'Scheduled: Existing run',
|
||||
})
|
||||
|
||||
await expect(service.runJob(42, 7, 'manual')).rejects.toMatchObject({
|
||||
message: 'Schedule is already running',
|
||||
status: 409,
|
||||
})
|
||||
})
|
||||
|
||||
it('surfaces setup failures when the model cannot be resolved', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
|
||||
mocks.resolveOpenCodeModel.mockRejectedValueOnce(new Error('No configured models are available.'))
|
||||
mocks.updateScheduleRun.mockReturnValue({
|
||||
...baseRun,
|
||||
status: 'failed',
|
||||
finishedAt: Date.UTC(2026, 2, 9, 12, 6, 0),
|
||||
errorText: 'No configured models are available.',
|
||||
})
|
||||
|
||||
await expect(service.runJob(42, 7, 'manual')).rejects.toMatchObject({
|
||||
message: 'No configured models are available.',
|
||||
status: 500,
|
||||
})
|
||||
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({
|
||||
status: 'failed',
|
||||
errorText: 'No configured models are available.',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('marks the run failed when prompt submission is rejected after session creation', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-6',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started. Waiting for assistant response...',
|
||||
}
|
||||
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return Promise.resolve(jsonResponse({ id: 'ses-run-6' }))
|
||||
}
|
||||
|
||||
if (path === '/session/ses-run-6/message' && method === 'POST') {
|
||||
return Promise.resolve(textResponse('Provider unavailable', 500))
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
const result = await service.runJob(42, 7, 'manual')
|
||||
|
||||
expect(result).toEqual(runWithSession)
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({
|
||||
status: 'failed',
|
||||
errorText: 'Provider unavailable',
|
||||
sessionId: 'ses-run-6',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('cancels an in-progress run by aborting the linked session', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const runningRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-3',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started. Waiting for assistant response...',
|
||||
}
|
||||
const cancelledRun: ScheduleRun = {
|
||||
...runningRun,
|
||||
status: 'cancelled',
|
||||
finishedAt: Date.UTC(2026, 2, 9, 12, 10, 0),
|
||||
errorText: 'Run cancelled by user.',
|
||||
}
|
||||
|
||||
mocks.getScheduleRunById.mockReturnValue(runningRun)
|
||||
mocks.updateScheduleRun.mockReturnValue(cancelledRun)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
if (path === '/session/ses-run-3/message' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([]))
|
||||
}
|
||||
|
||||
if (path === '/session/ses-run-3/abort' && method === 'POST') {
|
||||
return Promise.resolve(textResponse(''))
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
const result = await service.cancelRun(42, 7, 5)
|
||||
|
||||
expect(result).toEqual(cancelledRun)
|
||||
expect(mocks.proxyToOpenCodeWithDirectory).toHaveBeenCalledWith(
|
||||
'/session/ses-run-3/abort',
|
||||
'POST',
|
||||
repo.fullPath,
|
||||
)
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({ status: 'cancelled', errorText: 'Run cancelled by user.' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects cancellation for runs that already finished', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
|
||||
mocks.getScheduleRunById.mockReturnValue({
|
||||
...baseRun,
|
||||
status: 'completed',
|
||||
finishedAt: Date.UTC(2026, 2, 9, 12, 10, 0),
|
||||
responseText: 'Already done',
|
||||
})
|
||||
|
||||
await expect(service.cancelRun(42, 7, 5)).rejects.toMatchObject({
|
||||
message: 'Only running schedule runs can be cancelled',
|
||||
status: 409,
|
||||
})
|
||||
})
|
||||
|
||||
it('cancels a running entry without a linked session', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const runningRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: null,
|
||||
sessionTitle: null,
|
||||
}
|
||||
const cancelledRun: ScheduleRun = {
|
||||
...runningRun,
|
||||
status: 'cancelled',
|
||||
finishedAt: Date.UTC(2026, 2, 9, 12, 10, 0),
|
||||
errorText: 'Run cancelled by user.',
|
||||
}
|
||||
|
||||
mocks.getScheduleRunById.mockReturnValue(runningRun)
|
||||
mocks.updateScheduleRun.mockReturnValue(cancelledRun)
|
||||
|
||||
const result = await service.cancelRun(42, 7, 5)
|
||||
|
||||
expect(result).toEqual(cancelledRun)
|
||||
expect(mocks.proxyToOpenCodeWithDirectory).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces abort failures when cancellation cannot reach OpenCode', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const runningRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-7',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
}
|
||||
|
||||
mocks.getScheduleRunById.mockReturnValue(runningRun)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
if (path === '/session/ses-run-7/message' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([]))
|
||||
}
|
||||
|
||||
if (path === '/session/ses-run-7/abort' && method === 'POST') {
|
||||
return Promise.resolve(textResponse('Abort refused', 500))
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
await expect(service.cancelRun(42, 7, 5)).rejects.toMatchObject({
|
||||
message: 'Abort refused',
|
||||
status: 502,
|
||||
})
|
||||
})
|
||||
|
||||
it('marks orphaned idle runs as failed during recovery', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const orphanedRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
triggerSource: 'schedule',
|
||||
sessionId: 'ses-run-4',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
responseText: null,
|
||||
}
|
||||
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([orphanedRun])
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
if (path === '/session/ses-run-4/message' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([
|
||||
{
|
||||
info: { role: 'assistant' },
|
||||
parts: [{ type: 'text', text: 'Partial summary' }],
|
||||
},
|
||||
]))
|
||||
}
|
||||
|
||||
if (path === '/session/status' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse({
|
||||
'ses-run-4': { type: 'idle' },
|
||||
}))
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
await service.recoverRunningRuns()
|
||||
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({
|
||||
status: 'failed',
|
||||
responseText: 'Partial summary',
|
||||
errorText: expect.stringContaining('interrupted before completion'),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('finalizes interrupted runs without a linked session during recovery', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([
|
||||
{
|
||||
...baseRun,
|
||||
sessionId: null,
|
||||
sessionTitle: null,
|
||||
},
|
||||
])
|
||||
|
||||
await service.recoverRunningRuns()
|
||||
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({
|
||||
status: 'failed',
|
||||
errorText: expect.stringContaining('no linked session to recover'),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('completes recoverable runs when the assistant already finished', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const completedRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
triggerSource: 'schedule',
|
||||
sessionId: 'ses-run-8',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
}
|
||||
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([completedRun])
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
if (path === '/session/ses-run-8/message' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([
|
||||
{
|
||||
info: { role: 'assistant', time: { completed: Date.now() } },
|
||||
parts: [{ type: 'text', text: 'Recovered summary' }],
|
||||
},
|
||||
]))
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
await service.recoverRunningRuns()
|
||||
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({
|
||||
status: 'completed',
|
||||
responseText: 'Recovered summary',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('resumes recoverable runs when the session is still active', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const resumedRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
triggerSource: 'schedule',
|
||||
sessionId: 'ses-run-9',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
}
|
||||
let messageRequests = 0
|
||||
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([resumedRun])
|
||||
mocks.getScheduleRunById.mockReturnValue(resumedRun)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
if (path === '/session/ses-run-9/message' && method === 'GET') {
|
||||
messageRequests += 1
|
||||
|
||||
if (messageRequests === 1) {
|
||||
return Promise.resolve(jsonResponse([]))
|
||||
}
|
||||
|
||||
return Promise.resolve(jsonResponse([
|
||||
{
|
||||
info: { role: 'assistant', time: { completed: Date.now() } },
|
||||
parts: [{ type: 'text', text: 'Recovered after reconnect' }],
|
||||
},
|
||||
]))
|
||||
}
|
||||
|
||||
if (path === '/session/status' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse({
|
||||
'ses-run-9': { type: 'busy' },
|
||||
}))
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
await service.recoverRunningRuns()
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({
|
||||
status: 'completed',
|
||||
responseText: 'Recovered after reconnect',
|
||||
sessionId: 'ses-run-9',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('lists jobs and runs through the persistence layer', () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const listedRun = { ...baseRun, status: 'completed', finishedAt: Date.UTC(2026, 2, 9, 12, 10, 0) }
|
||||
|
||||
mocks.listScheduleJobsByRepo.mockReturnValue([job])
|
||||
mocks.listScheduleRunsByJob.mockReturnValue([listedRun])
|
||||
|
||||
expect(service.listJobs(42)).toEqual([job])
|
||||
expect(service.listRuns(42, 7, 10)).toEqual([listedRun])
|
||||
expect(mocks.listScheduleJobsByRepo).toHaveBeenCalledWith(expect.anything(), 42)
|
||||
expect(mocks.listScheduleRunsByJob).toHaveBeenCalledWith(expect.anything(), 42, 7, 10)
|
||||
})
|
||||
|
||||
it('creates and updates jobs using normalized persistence input', () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const createdJob = { ...job, id: 8, name: 'Daily release summary' }
|
||||
const updatedJob = { ...job, name: 'Updated release summary' }
|
||||
|
||||
mocks.buildCreateSchedulePersistenceInput.mockReturnValue({ name: 'Daily release summary' })
|
||||
mocks.createScheduleJob.mockReturnValue(createdJob)
|
||||
mocks.buildUpdatedSchedulePersistenceInput.mockReturnValue({ name: 'Updated release summary' })
|
||||
mocks.updateScheduleJob.mockReturnValue(updatedJob)
|
||||
|
||||
const createResult = service.createJob(42, {
|
||||
name: 'Daily release summary',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
prompt: 'Summarize release readiness.',
|
||||
})
|
||||
const updateResult = service.updateJob(42, 7, { name: 'Updated release summary' })
|
||||
|
||||
expect(createResult).toEqual(createdJob)
|
||||
expect(updateResult).toEqual(updatedJob)
|
||||
expect(mocks.buildCreateSchedulePersistenceInput).toHaveBeenCalled()
|
||||
expect(mocks.buildUpdatedSchedulePersistenceInput).toHaveBeenCalledWith(job, { name: 'Updated release summary' })
|
||||
})
|
||||
|
||||
it('throws when deleting or loading missing records', () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
|
||||
mocks.deleteScheduleJob.mockReturnValue(false)
|
||||
mocks.getScheduleRunById.mockReturnValue(null)
|
||||
|
||||
expect(() => service.deleteJob(42, 7)).toThrow('Schedule not found')
|
||||
expect(() => service.getRun(42, 7, 5)).toThrow('Run not found')
|
||||
})
|
||||
|
||||
it('cancels by finalizing the run when the assistant already completed', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const runningRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-5',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
}
|
||||
const completedRun: ScheduleRun = {
|
||||
...runningRun,
|
||||
status: 'completed',
|
||||
finishedAt: Date.UTC(2026, 2, 9, 12, 20, 0),
|
||||
responseText: 'Completed summary',
|
||||
}
|
||||
|
||||
mocks.getScheduleRunById.mockReturnValueOnce(runningRun).mockReturnValueOnce(completedRun)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
if (path === '/session/ses-run-5/message' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([
|
||||
{
|
||||
info: { role: 'assistant', time: { completed: Date.now() } },
|
||||
parts: [{ type: 'text', text: 'Completed summary' }],
|
||||
},
|
||||
]))
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
const result = await service.cancelRun(42, 7, 5)
|
||||
|
||||
expect(result).toEqual(completedRun)
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({ status: 'completed', responseText: 'Completed summary' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ScheduleRunner', () => {
|
||||
beforeEach(() => {
|
||||
mockCronInstances.length = 0
|
||||
mockCronStop.mockClear()
|
||||
})
|
||||
|
||||
it('recovers running runs and registers all enabled jobs on start', async () => {
|
||||
const mockJob: ScheduleJob = {
|
||||
id: 1,
|
||||
repoId: 10,
|
||||
name: 'Test Job',
|
||||
description: null,
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||
|
||||
const service = new ScheduleService({} as never)
|
||||
const runner = new ScheduleRunner(service)
|
||||
await runner.start()
|
||||
|
||||
expect(mocks.listRunningScheduleRuns).toHaveBeenCalled()
|
||||
expect(mocks.listEnabledScheduleJobs).toHaveBeenCalled()
|
||||
expect(mockCronInstances).toHaveLength(1)
|
||||
expect(mockCronInstances[0]?.pattern).toBe('*/60 * * * *')
|
||||
expect(mockCronInstances[0]?.options).toEqual(expect.objectContaining({ protect: true }))
|
||||
})
|
||||
|
||||
it('registers a cron job with timezone', async () => {
|
||||
const mockJob: ScheduleJob = {
|
||||
id: 2,
|
||||
repoId: 10,
|
||||
name: 'Test Cron',
|
||||
description: null,
|
||||
enabled: true,
|
||||
scheduleMode: 'cron',
|
||||
cronExpression: '0 9 * * *',
|
||||
timezone: 'America/New_York',
|
||||
intervalMinutes: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||
|
||||
const service = new ScheduleService({} as never)
|
||||
const runner = new ScheduleRunner(service)
|
||||
await runner.start()
|
||||
|
||||
expect(mockCronInstances).toHaveLength(1)
|
||||
expect(mockCronInstances[0]?.pattern).toBe('0 9 * * *')
|
||||
expect(mockCronInstances[0]?.options).toEqual(expect.objectContaining({ timezone: 'America/New_York', protect: true }))
|
||||
})
|
||||
|
||||
it('skips disabled jobs', async () => {
|
||||
const mockJob: ScheduleJob = {
|
||||
id: 3,
|
||||
repoId: 10,
|
||||
name: 'Disabled Job',
|
||||
description: null,
|
||||
enabled: false,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||
mocks.listEnabledScheduleJobs.mockReturnValue([])
|
||||
|
||||
const service = new ScheduleService({} as never)
|
||||
const runner = new ScheduleRunner(service)
|
||||
await runner.start()
|
||||
|
||||
runner.registerJob(mockJob)
|
||||
expect(mockCronInstances).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('stops all cron instances on stop', async () => {
|
||||
const mockJob: ScheduleJob = {
|
||||
id: 4,
|
||||
repoId: 10,
|
||||
name: 'Stop Test',
|
||||
description: null,
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 30,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||
|
||||
const service = new ScheduleService({} as never)
|
||||
const runner = new ScheduleRunner(service)
|
||||
await runner.start()
|
||||
|
||||
runner.stop()
|
||||
expect(mockCronStop).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('unregisters and re-registers a job on update via onJobChange', async () => {
|
||||
const mockJob: ScheduleJob = {
|
||||
id: 5,
|
||||
repoId: 10,
|
||||
name: 'Update Test',
|
||||
description: null,
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||
|
||||
const service = new ScheduleService({} as never)
|
||||
const runner = new ScheduleRunner(service)
|
||||
await runner.start()
|
||||
|
||||
expect(mockCronInstances).toHaveLength(1)
|
||||
|
||||
const updatedJob = { ...mockJob, intervalMinutes: 30 }
|
||||
runner.registerJob(updatedJob)
|
||||
|
||||
expect(mockCronStop).toHaveBeenCalled()
|
||||
expect(mockCronInstances).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user