From 47524876aac0aafb618d8d2d0e5625a602354e98 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sun, 22 Mar 2026 11:14:30 -0400 Subject: [PATCH] Refactor schedule service and add cron support --- .../migrations/008-schedule-cron-support.ts | 51 +++++ backend/src/db/schedules.ts | 11 - backend/src/index.ts | 12 +- backend/src/routes/repos.ts | 5 +- backend/src/routes/schedules.ts | 4 +- backend/src/routes/settings.ts | 200 +++++++++++++++++- backend/src/services/schedule-config.ts | 2 +- backend/src/services/schedules.ts | 117 ++++++++-- backend/src/utils/version-utils.ts | 5 + backend/test/db/schedule-migrations.test.ts | 62 ++++-- backend/test/db/schedules.test.ts | 17 -- backend/test/routes/schedules.test.ts | 5 +- backend/test/routes/settings.test.ts | 50 +++-- backend/test/services/schedules.test.ts | 4 +- frontend/src/api/opencode.ts | 12 -- frontend/src/api/settings.ts | 43 +++- frontend/src/api/types/settings.ts | 6 +- .../schedules/ScheduleJobDialog.tsx | 116 +++++++--- .../settings/OpenCodeConfigManager.tsx | 44 +++- frontend/src/lib/queryInvalidation.ts | 2 + shared/src/schemas/index.ts | 1 + shared/src/schemas/schedule.ts | 2 +- shared/src/schemas/settings.ts | 4 + shared/src/types/index.ts | 16 ++ 24 files changed, 652 insertions(+), 139 deletions(-) diff --git a/backend/src/db/migrations/008-schedule-cron-support.ts b/backend/src/db/migrations/008-schedule-cron-support.ts index 948d3246..a0036989 100644 --- a/backend/src/db/migrations/008-schedule-cron-support.ts +++ b/backend/src/db/migrations/008-schedule-cron-support.ts @@ -11,6 +11,57 @@ const migration: Migration = { name: 'schedule-cron-support', up(db) { + const tableExists = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='schedule_jobs'").get() + + if (!tableExists) { + db.run(` + CREATE TABLE schedule_jobs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE, + name TEXT NOT NULL, + description TEXT, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + interval_minutes INTEGER, + schedule_mode TEXT NOT NULL DEFAULT 'interval', + cron_expression TEXT, + timezone TEXT, + agent_slug TEXT, + prompt TEXT NOT NULL, + model TEXT, + skill_metadata TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + last_run_at INTEGER, + next_run_at INTEGER + ) + `) + db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)') + db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)') + } + + const runsTableExists = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='schedule_runs'").get() + if (!runsTableExists) { + db.run(` + CREATE TABLE schedule_runs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + job_id INTEGER NOT NULL REFERENCES schedule_jobs(id) ON DELETE CASCADE, + repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE, + trigger_source TEXT NOT NULL, + status TEXT NOT NULL, + started_at INTEGER NOT NULL, + finished_at INTEGER, + created_at INTEGER NOT NULL, + session_id TEXT, + session_title TEXT, + log_text TEXT, + response_text TEXT, + error_text TEXT + ) + `) + db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_job ON schedule_runs(job_id, started_at DESC)') + db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_repo ON schedule_runs(repo_id, started_at DESC)') + } + const tableInfo = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[] const existingColumns = new Set(tableInfo.map((column) => column.name)) const intervalMinutesColumn = tableInfo.find((column) => column.name === 'interval_minutes') diff --git a/backend/src/db/schedules.ts b/backend/src/db/schedules.ts index b669f4a2..989c8fe0 100644 --- a/backend/src/db/schedules.ts +++ b/backend/src/db/schedules.ts @@ -115,17 +115,6 @@ export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJo return rows.map(rowToScheduleJob) } -export function listDueScheduleJobs(db: Database, now: number, limit: number = 20): ScheduleJob[] { - const stmt = db.prepare(` - SELECT * FROM schedule_jobs - WHERE enabled = 1 AND next_run_at IS NOT NULL AND next_run_at <= ? - ORDER BY next_run_at ASC - LIMIT ? - `) - const rows = stmt.all(now, limit) as ScheduleJobRow[] - return rows.map(rowToScheduleJob) -} - export function listEnabledScheduleJobs(db: Database): ScheduleJob[] { const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE enabled = 1 ORDER BY id ASC') const rows = stmt.all() as ScheduleJobRow[] diff --git a/backend/src/index.ts b/backend/src/index.ts index a7daebb9..0e2f1bf7 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -83,7 +83,6 @@ const requireAuth = createAuthMiddleware(auth) import { DEFAULT_AGENTS_MD } from './constants' let ipcServer: IPCServer | undefined -let scheduleRunnerInstance: ScheduleRunner | undefined const gitAuthService = new GitAuthService() const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', 'opencode.db-wal']) @@ -315,15 +314,14 @@ try { await opencodeServerManager.start() logger.info(`OpenCode server running on port ${opencodeServerManager.getPort()}`) - const scheduleService = new ScheduleService(db) - scheduleRunnerInstance = new ScheduleRunner(scheduleService) - await scheduleRunnerInstance.start() - await syncAdminFromEnv(auth, db) } catch (error) { logger.error('Failed to initialize workspace:', error) } +const scheduleService = new ScheduleService(db) +const scheduleRunnerInstance = new ScheduleRunner(scheduleService) + const notificationService = new NotificationService(db) if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) { @@ -345,6 +343,8 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) { }) } +void scheduleRunnerInstance.start() + app.route('/api/auth', createAuthRoutes(auth)) app.route('/api/auth-info', createAuthInfoRoutes(auth, db)) app.route('/api/health', createHealthRoutes(db)) @@ -354,7 +354,7 @@ app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(requireAuth)) const protectedApi = new Hono() protectedApi.use('/*', requireAuth) -protectedApi.route('/repos', createRepoRoutes(db, gitAuthService)) +protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService)) protectedApi.route('/settings', createSettingsRoutes(db)) protectedApi.route('/files', createFileRoutes()) protectedApi.route('/providers', createProvidersRoutes()) diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index a5baa1b1..c3fb087d 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -15,13 +15,14 @@ import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env' import { createRepoGitRoutes } from './repo-git' import { createScheduleRoutes } from './schedules' import type { GitAuthService } from '../services/git-auth' +import { ScheduleService } from '../services/schedules' import path from 'path' -export function createRepoRoutes(database: Database, gitAuthService: GitAuthService) { +export function createRepoRoutes(database: Database, gitAuthService: GitAuthService, scheduleService: ScheduleService) { const app = new Hono() app.route('/', createRepoGitRoutes(database, gitAuthService)) - app.route('/:id/schedules', createScheduleRoutes(database)) + app.route('/:id/schedules', createScheduleRoutes(scheduleService)) app.post('/', async (c) => { try { diff --git a/backend/src/routes/schedules.ts b/backend/src/routes/schedules.ts index d7adf4fb..a2bf402c 100644 --- a/backend/src/routes/schedules.ts +++ b/backend/src/routes/schedules.ts @@ -1,5 +1,4 @@ import { Hono, type Context } from 'hono' -import type { Database } from 'bun:sqlite' import { CreateScheduleJobRequestSchema, UpdateScheduleJobRequestSchema, @@ -33,9 +32,8 @@ function parseRunListLimit(value: string | undefined): number { return Math.min(parsed, 100) } -export function createScheduleRoutes(database: Database) { +export function createScheduleRoutes(scheduleService: ScheduleService) { const app = new Hono() - const scheduleService = new ScheduleService(database) app.get('/', (c) => { try { diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index 6c082574..fffc4b4d 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -13,12 +13,24 @@ import { OpenCodeConfigSchema, } from '../types/settings' import type { GitCredential } from '@opencode-manager/shared' +import { + CreateSkillRequestSchema, + UpdateSkillRequestSchema, + SkillScopeSchema, +} from '@opencode-manager/shared' import { logger } from '../utils/logger' import { opencodeServerManager } from '../services/opencode-single-server' import { DEFAULT_AGENTS_MD } from '../constants' import { validateSSHPrivateKey } from '../utils/ssh-validation' import { encryptSecret } from '../utils/crypto' -import { compareVersions } from '../utils/version-utils' +import { compareVersions, isValidVersion } from '../utils/version-utils' +import { + listManagedSkills, + getSkill, + createSkill, + updateSkill, + deleteSkill, +} from '../services/skills' function getOpenCodeInstallMethod(): string { const homePath = process.env.HOME || '' @@ -41,7 +53,27 @@ function getOpenCodeInstallMethod(): string { return 'curl' } -function execWithTimeout(command: string, timeoutMs: number, env?: Record): { output: string; timedOut: boolean } { +function execWithTimeout( + command: string | [executable: string, ...args: string[]], + timeoutMs: number, + env?: Record +): { output: string; timedOut: boolean } { + if (Array.isArray(command)) { + const result = spawnSync(command[0], command.slice(1), { + encoding: 'utf8', + timeout: timeoutMs, + killSignal: 'SIGKILL', + env: env ? { ...process.env, ...env } : undefined + }) + + if (result.signal === 'SIGKILL' || result.error?.message?.includes('TIMEOUT')) { + return { output: '', timedOut: true } + } + + const output = (result.stdout || '') + (result.stderr || '') + return { output, timedOut: false } + } + try { const output = execSync(command, { encoding: 'utf8', @@ -629,12 +661,20 @@ export function createSettingsRoutes(db: Database) { const body = await c.req.json() const { version } = z.object({ version: z.string().min(1) }).parse(body) + const versionWithoutPrefix = version.replace(/^v/, '') + if (!isValidVersion(versionWithoutPrefix)) { + throw new Error('Invalid version format. Must be in MAJOR.MINOR.PATCH format (e.g., 1.2.27)') + } + logger.info(`Installing OpenCode version: ${version}`) const versionArg = version.startsWith('v') ? version : `v${version}` const installMethod = getOpenCodeInstallMethod() logger.info(`Running opencode upgrade ${versionArg} --method ${installMethod} with 90s timeout...`) - const { output: upgradeOutput, timedOut } = execWithTimeout(`opencode upgrade ${versionArg} --method ${installMethod} 2>&1`, 90000) + const { output: upgradeOutput, timedOut } = execWithTimeout( + ['opencode', 'upgrade', versionArg, '--method', installMethod], + 90000 + ) logger.info(`Upgrade output: ${upgradeOutput}`) if (timedOut) { @@ -836,6 +876,160 @@ export function createSettingsRoutes(db: Database) { } }) + app.get('/skills', async (c) => { + try { + const repoIdParam = c.req.query('repoId') + const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined + if (repoId !== undefined && isNaN(repoId)) { + return c.json({ error: 'Invalid repoId' }, 400) + } + + const skills = await listManagedSkills(db, repoId) + return c.json(skills) + } catch (error) { + logger.error('Failed to list skills:', error) + return c.json({ error: 'Failed to list skills' }, 500) + } + }) + + app.get('/skills/:name', async (c) => { + try { + const name = c.req.param('name') + const scope = SkillScopeSchema.parse(c.req.query('scope')) + const repoIdParam = c.req.query('repoId') + const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined + if (repoId !== undefined && isNaN(repoId)) { + return c.json({ error: 'Invalid repoId' }, 400) + } + + if (scope === 'project' && !repoId) { + return c.json({ error: 'repoId is required for project scope' }, 400) + } + + const skill = await getSkill(db, name, scope, repoId) + return c.json(skill) + } catch (error) { + logger.error('Failed to get skill:', error) + if (error instanceof z.ZodError) { + return c.json({ error: 'Invalid scope parameter. Must be "global" or "project"' }, 400) + } + if (error instanceof Error && error.message.includes('not found')) { + return c.json({ error: error.message }, 404) + } + if (error instanceof Error && error.message.includes('Invalid skill name')) { + return c.json({ error: error.message }, 400) + } + return c.json({ error: 'Failed to get skill' }, 500) + } + }) + + app.post('/skills', async (c) => { + try { + const body = await c.req.json() + const validated = CreateSkillRequestSchema.parse(body) + + const skill = await createSkill(db, validated) + + try { + await opencodeServerManager.restart() + logger.info('Restarted OpenCode server after skill creation') + } catch (restartError) { + logger.warn('Failed to restart OpenCode server after skill creation:', restartError) + } + + return c.json(skill) + } catch (error) { + logger.error('Failed to create skill:', error) + if (error instanceof z.ZodError) { + return c.json({ error: 'Invalid skill data', details: error.issues }, 400) + } + if (error instanceof Error && error.message.includes('already exists')) { + return c.json({ error: error.message }, 409) + } + return c.json({ error: 'Failed to create skill' }, 500) + } + }) + + app.put('/skills/:name', async (c) => { + try { + const name = c.req.param('name') + const scope = SkillScopeSchema.parse(c.req.query('scope')) + const repoIdParam = c.req.query('repoId') + const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined + if (repoId !== undefined && isNaN(repoId)) { + return c.json({ error: 'Invalid repoId' }, 400) + } + const body = await c.req.json() + const validated = UpdateSkillRequestSchema.parse(body) + + if (scope === 'project' && !repoId) { + return c.json({ error: 'repoId is required for project scope' }, 400) + } + + const skill = await updateSkill(db, name, scope, validated, repoId) + + try { + await opencodeServerManager.restart() + logger.info('Restarted OpenCode server after skill update') + } catch (restartError) { + logger.warn('Failed to restart OpenCode server after skill update:', restartError) + } + + return c.json(skill) + } catch (error) { + logger.error('Failed to update skill:', error) + if (error instanceof z.ZodError) { + return c.json({ error: 'Invalid request data', details: error.issues }, 400) + } + if (error instanceof Error && error.message.includes('not found')) { + return c.json({ error: error.message }, 404) + } + if (error instanceof Error && error.message.includes('Invalid skill name')) { + return c.json({ error: error.message }, 400) + } + return c.json({ error: 'Failed to update skill' }, 500) + } + }) + + app.delete('/skills/:name', async (c) => { + try { + const name = c.req.param('name') + const scope = SkillScopeSchema.parse(c.req.query('scope')) + const repoIdParam = c.req.query('repoId') + const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined + if (repoId !== undefined && isNaN(repoId)) { + return c.json({ error: 'Invalid repoId' }, 400) + } + + if (scope === 'project' && !repoId) { + return c.json({ error: 'repoId is required for project scope' }, 400) + } + + await deleteSkill(db, name, scope, repoId) + + try { + await opencodeServerManager.restart() + logger.info('Restarted OpenCode server after skill deletion') + } catch (restartError) { + logger.warn('Failed to restart OpenCode server after skill deletion:', restartError) + } + + return c.json({ success: true }) + } catch (error) { + logger.error('Failed to delete skill:', error) + if (error instanceof z.ZodError) { + return c.json({ error: 'Invalid scope parameter. Must be "global" or "project"' }, 400) + } + if (error instanceof Error && error.message.includes('not found')) { + return c.json({ error: error.message }, 404) + } + if (error instanceof Error && error.message.includes('Invalid skill name')) { + return c.json({ error: error.message }, 400) + } + return c.json({ error: 'Failed to delete skill' }, 500) + } + }) + app.post('/test-ssh', async (c) => { try { const body = await c.req.json() diff --git a/backend/src/services/schedule-config.ts b/backend/src/services/schedule-config.ts index 76eca33b..74e58831 100644 --- a/backend/src/services/schedule-config.ts +++ b/backend/src/services/schedule-config.ts @@ -150,7 +150,7 @@ export function buildUpdatedSchedulePersistenceInput( agentSlug: input.agentSlug === undefined ? existing.agentSlug : (input.agentSlug?.trim() || null), prompt: input.prompt?.trim() || existing.prompt, model: input.model === undefined ? existing.model : (input.model?.trim() || null), - skillMetadata: input.skillMetadata === undefined ? existing.skillMetadata : input.skillMetadata, + skillMetadata: input.skillMetadata !== undefined ? input.skillMetadata : existing.skillMetadata, nextRunAt, } } diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index b7aa0312..5f1fefad 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -985,8 +985,38 @@ export class ScheduleService { } } +interface Stoppable { + stop(): void +} + +function buildIntervalCronExpression(intervalMinutes: number): string | null { + if (intervalMinutes < 5) { + return null + } + + if (intervalMinutes <= 59) { + return `*/${intervalMinutes} * * * *` + } + + if (intervalMinutes === 60) { + return `0 * * * *` + } + + const hours = intervalMinutes / 60 + if (Number.isInteger(hours) && 24 % hours === 0) { + return `0 */${hours} * * *` + } + + const days = intervalMinutes / 1440 + if (Number.isInteger(days)) { + return `0 0 */${days} * *` + } + + return null +} + export class ScheduleRunner { - private cronJobs = new Map() + private cronJobs = new Map() constructor(private readonly scheduleService: ScheduleService) {} @@ -1004,9 +1034,9 @@ export class ScheduleRunner { } stop(): void { - this.scheduleService.setJobChangeHandler(null as never) - for (const cron of this.cronJobs.values()) { - cron.stop() + this.scheduleService.setJobChangeHandler(null) + for (const stoppable of this.cronJobs.values()) { + stoppable.stop() } this.cronJobs.clear() } @@ -1040,30 +1070,81 @@ export class ScheduleRunner { } if (!job.nextRunAt) { + logger.warn(`Job ${job.id} (${job.name}) has no nextRunAt, skipping registration`) return } - const cronExpression = `*/${job.intervalMinutes} * * * *` + const cronExpression = buildIntervalCronExpression(job.intervalMinutes) const options: Record = { protect: true } if (job.timezone) { options.timezone = job.timezone } - const cron = new Cron(cronExpression, options, () => { - logger.info(`Cron triggered for job ${job.id}: ${job.name}`) - void this.executeJob(job.repoId, job.id) - }) - const now = Date.now() - const delay = job.nextRunAt - now - if (delay > 0) { - const timeout = setTimeout(() => { - logger.info(`Interval timer triggered for job ${job.id}: ${job.name}`) + if (cronExpression) { + const nextRunDate = new Date(job.nextRunAt) + const now = new Date() + + if (nextRunDate <= now) { void this.executeJob(job.repoId, job.id) - this.cronJobs.set(job.id, cron) - }, delay) - this.cronJobs.set(job.id, { stop: () => clearTimeout(timeout) } as unknown as Cron) - } else { + } + + const cronOptions = { + ...options, + ...(nextRunDate > now ? { startAt: nextRunDate.toISOString() } : {}), + } + const cron = new Cron(cronExpression, cronOptions, () => { + logger.info(`Cron triggered for job ${job.id}: ${job.name}`) + void this.executeJob(job.repoId, job.id) + }) this.cronJobs.set(job.id, cron) + } else { + const intervalMs = job.intervalMinutes * 60_000 + let timeout: ReturnType | null = null + let isStopped = false + let isRunning = false + + const scheduleNext = () => { + if (isStopped || isRunning) return + timeout = setTimeout(async () => { + if (isStopped || isRunning) return + isRunning = true + logger.info(`Interval timer triggered for job ${job.id}: ${job.name}`) + try { + await this.executeJob(job.repoId, job.id) + } finally { + isRunning = false + scheduleNext() + } + }, intervalMs) + } + + const initialDelay = Math.max(0, job.nextRunAt - Date.now()) + if (initialDelay > 0) { + timeout = setTimeout(() => { + if (isStopped || isRunning) return + isRunning = true + logger.info(`Interval timer triggered for job ${job.id}: ${job.name}`) + void this.executeJob(job.repoId, job.id).finally(() => { + isRunning = false + scheduleNext() + }) + }, initialDelay) + } else { + if (!isStopped) { + isRunning = true + void this.executeJob(job.repoId, job.id).finally(() => { + isRunning = false + scheduleNext() + }) + } + } + + this.cronJobs.set(job.id, { + stop: () => { + isStopped = true + if (timeout) clearTimeout(timeout) + } + }) } } diff --git a/backend/src/utils/version-utils.ts b/backend/src/utils/version-utils.ts index d34ed61b..67375a1a 100644 --- a/backend/src/utils/version-utils.ts +++ b/backend/src/utils/version-utils.ts @@ -10,3 +10,8 @@ export function compareVersions(v1: string, v2: string): number { } return 0 } + +export function isValidVersion(version: string): boolean { + const semverRegex = /^\d+\.\d+\.\d+$/ + return semverRegex.test(version) +} diff --git a/backend/test/db/schedule-migrations.test.ts b/backend/test/db/schedule-migrations.test.ts index f8869ced..0d4a467e 100644 --- a/backend/test/db/schedule-migrations.test.ts +++ b/backend/test/db/schedule-migrations.test.ts @@ -13,31 +13,59 @@ describe('schedule migrations', () => { expect(db.run).toHaveBeenCalledWith(expect.stringContaining('interval_minutes INTEGER,')) }) - it('rebuilds schedule jobs for cron support in v8', () => { + it('creates tables from scratch when schedule_jobs does not exist (phantom migration)', () => { 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 }, - ]), + get: vi.fn().mockReturnValue(undefined), }), run: vi.fn(), } migration008.up(db as never) + expect(db.prepare).toHaveBeenCalledWith(expect.stringContaining('sqlite_master')) + expect(db.run).toHaveBeenCalledWith(expect.stringContaining('CREATE TABLE schedule_jobs')) + expect(db.run).toHaveBeenCalledWith(expect.stringContaining('schedule_mode TEXT NOT NULL DEFAULT')) + expect(db.run).toHaveBeenCalledWith(expect.stringContaining('cron_expression TEXT')) + expect(db.run).toHaveBeenCalledWith(expect.stringContaining('timezone TEXT')) + expect(db.run).toHaveBeenCalledWith(expect.stringContaining('CREATE TABLE schedule_runs')) + expect(db.run).toHaveBeenCalledWith(expect.stringContaining('idx_schedule_jobs_repo')) + expect(db.run).toHaveBeenCalledWith(expect.stringContaining('idx_schedule_jobs_next_run')) + }) + + it('rebuilds schedule jobs for cron support in v8', () => { + const db = { + prepare: vi.fn().mockImplementation((query: string) => { + if (query.includes('sqlite_master')) { + return { + get: vi.fn().mockReturnValue({ name: 'schedule_jobs' }), + } + } + return { + 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(expect.stringContaining('sqlite_master')) 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,')) diff --git a/backend/test/db/schedules.test.ts b/backend/test/db/schedules.test.ts index 532c88af..03ae96ab 100644 --- a/backend/test/db/schedules.test.ts +++ b/backend/test/db/schedules.test.ts @@ -290,23 +290,6 @@ describe('schedule database queries', () => { 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 = { diff --git a/backend/test/routes/schedules.test.ts b/backend/test/routes/schedules.test.ts index 0201a420..455767a8 100644 --- a/backend/test/routes/schedules.test.ts +++ b/backend/test/routes/schedules.test.ts @@ -23,6 +23,9 @@ const mocks = vi.hoisted(() => { listRuns: vi.fn(), getRun: vi.fn(), cancelRun: vi.fn(), + listAllEnabledJobs: vi.fn(), + recoverRunningRuns: vi.fn(), + setJobChangeHandler: vi.fn(), }, } }) @@ -48,7 +51,7 @@ describe('Schedule Routes', () => { beforeEach(() => { vi.clearAllMocks() app = new Hono() - app.route('/repos/:id/schedules', createScheduleRoutes({} as never)) + app.route('/repos/:id/schedules', createScheduleRoutes(mocks.scheduleService as unknown as import('../../src/services/schedules').ScheduleService)) }) it('lists jobs for a repo', async () => { diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index 747d0648..4a0b70b2 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { execSync } from 'child_process' +import { execSync, spawnSync } from 'child_process' vi.mock('fs', () => ({ existsSync: vi.fn(() => false), @@ -93,6 +93,7 @@ import { createSettingsRoutes } from '../../src/routes/settings' import { opencodeServerManager } from '../../src/services/opencode-single-server' const mockExecSync = execSync as ReturnType +const mockSpawnSync = spawnSync as ReturnType const mockGetVersion = opencodeServerManager.getVersion as ReturnType const mockFetchVersion = opencodeServerManager.fetchVersion as ReturnType const mockReloadConfig = opencodeServerManager.reloadConfig as ReturnType @@ -302,7 +303,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should install specific version successfully', async () => { mockGetVersion.mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.5') - mockExecSync.mockReturnValueOnce('Installed v1.0.5\n') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.0.5\n', stderr: '', signal: null, error: undefined }) const req = new Request('http://localhost/opencode-install-version', { method: 'POST', @@ -320,7 +321,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should prepend v to version if missing', async () => { mockGetVersion.mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.5') - mockExecSync.mockReturnValueOnce('Installed v1.0.5\n') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.0.5\n', stderr: '', signal: null, error: undefined }) const req = new Request('http://localhost/opencode-install-version', { method: 'POST', @@ -329,8 +330,9 @@ describe('Settings Routes - OpenCode Upgrade', () => { }) await settingsApp.fetch(req) - expect(mockExecSync).toHaveBeenCalledWith( - 'opencode upgrade v1.0.5 --method curl 2>&1', + expect(mockSpawnSync).toHaveBeenCalledWith( + 'opencode', + ['upgrade', 'v1.0.5', '--method', 'curl'], expect.any(Object) ) }) @@ -338,7 +340,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should not double prepend v to version', async () => { mockGetVersion.mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.5') - mockExecSync.mockReturnValueOnce('Installed v1.0.5\n') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.0.5\n', stderr: '', signal: null, error: undefined }) const req = new Request('http://localhost/opencode-install-version', { method: 'POST', @@ -347,8 +349,9 @@ describe('Settings Routes - OpenCode Upgrade', () => { }) await settingsApp.fetch(req) - expect(mockExecSync).toHaveBeenCalledWith( - 'opencode upgrade v1.0.5 --method curl 2>&1', + expect(mockSpawnSync).toHaveBeenCalledWith( + 'opencode', + ['upgrade', 'v1.0.5', '--method', 'curl'], expect.any(Object) ) }) @@ -359,9 +362,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { mockGetVersion.mockReturnValueOnce('1.0.0') .mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.0') - mockExecSync.mockImplementationOnce(() => { - throw new Error('timeout') - }) + mockSpawnSync.mockReturnValueOnce({ stdout: '', stderr: '', signal: 'SIGKILL', error: undefined }) const req = new Request('http://localhost/opencode-install-version', { method: 'POST', @@ -371,8 +372,9 @@ describe('Settings Routes - OpenCode Upgrade', () => { const res = await settingsApp.fetch(req) const json = await res.json() as Record - expect(mockExecSync).toHaveBeenCalledWith( - 'opencode upgrade v1.0.5 --method curl 2>&1', + expect(mockSpawnSync).toHaveBeenCalledWith( + 'opencode', + ['upgrade', 'v1.0.5', '--method', 'curl'], expect.any(Object) ) expect(mockRestart).toHaveBeenCalled() @@ -403,6 +405,28 @@ describe('Settings Routes - OpenCode Upgrade', () => { expect(res.status).toBe(400) }) + + it('should reject invalid version format with command injection attempt', async () => { + const req = new Request('http://localhost/opencode-install-version', { + method: 'POST', + body: JSON.stringify({ version: '1.2.27; cat /etc/passwd; #' }), + headers: { 'Content-Type': 'application/json' } + }) + const res = await settingsApp.fetch(req) + + expect(res.status).toBe(400) + }) + + it('should reject version with invalid format', async () => { + const req = new Request('http://localhost/opencode-install-version', { + method: 'POST', + body: JSON.stringify({ version: 'invalid' }), + headers: { 'Content-Type': 'application/json' } + }) + const res = await settingsApp.fetch(req) + + expect(res.status).toBe(400) + }) }) }) diff --git a/backend/test/services/schedules.test.ts b/backend/test/services/schedules.test.ts index 5cca10c2..2c85f7e8 100644 --- a/backend/test/services/schedules.test.ts +++ b/backend/test/services/schedules.test.ts @@ -9,7 +9,6 @@ const mocks = vi.hoisted(() => ({ getScheduleJobById: vi.fn(), getRunningScheduleRunByJob: vi.fn(), getScheduleRunById: vi.fn(), - listDueScheduleJobs: vi.fn(), listEnabledScheduleJobs: vi.fn(), listRunningScheduleRuns: vi.fn(), listScheduleJobsByRepo: vi.fn(), @@ -40,7 +39,6 @@ vi.mock('../../src/db/schedules', () => ({ getScheduleJobById: mocks.getScheduleJobById, getRunningScheduleRunByJob: mocks.getRunningScheduleRunByJob, getScheduleRunById: mocks.getScheduleRunById, - listDueScheduleJobs: mocks.listDueScheduleJobs, listEnabledScheduleJobs: mocks.listEnabledScheduleJobs, listRunningScheduleRuns: mocks.listRunningScheduleRuns, listScheduleJobsByRepo: mocks.listScheduleJobsByRepo, @@ -748,7 +746,7 @@ describe('ScheduleRunner', () => { expect(mocks.listRunningScheduleRuns).toHaveBeenCalled() expect(mocks.listEnabledScheduleJobs).toHaveBeenCalled() expect(mockCronInstances).toHaveLength(1) - expect(mockCronInstances[0]?.pattern).toBe('*/60 * * * *') + expect(mockCronInstances[0]?.pattern).toBe('0 * * * *') expect(mockCronInstances[0]?.options).toEqual(expect.objectContaining({ protect: true })) }) diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index af7e78fc..eff42c73 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -1,7 +1,5 @@ import type { paths } from './opencode-types' import { fetchWrapper } from './fetchWrapper' -import { useQuery } from '@tanstack/react-query' -import { OPENCODE_API_ENDPOINT } from '@/config' type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json'] type SessionResponse = paths['/session/{sessionID}']['get']['responses']['200']['content']['application/json'] @@ -251,13 +249,3 @@ export const createOpenCodeClient = (baseURL: string, directory?: string) => { return new OpenCodeClient(baseURL, directory) } -export const useAgents = () => { - return useQuery({ - queryKey: ['opencode-agents'], - queryFn: async () => { - const client = createOpenCodeClient(OPENCODE_API_ENDPOINT) - return await client.listAgents() - }, - staleTime: 5 * 60 * 1000, - }) -} diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts index a29ed889..bcda5bd3 100644 --- a/frontend/src/api/settings.ts +++ b/frontend/src/api/settings.ts @@ -4,7 +4,11 @@ import type { OpenCodeConfig, OpenCodeConfigResponse, CreateOpenCodeConfigRequest, - UpdateOpenCodeConfigRequest + UpdateOpenCodeConfigRequest, + SkillFileInfo, + CreateSkillRequest, + UpdateSkillRequest, + SkillScope, } from './types/settings' import { API_BASE_URL } from '@/config' import { fetchWrapper, FetchError } from './fetchWrapper' @@ -214,6 +218,43 @@ export const settingsApi = { getMemoryPluginStatus: async (): Promise<{ memoryPluginEnabled: boolean }> => { return fetchWrapper(`${API_BASE_URL}/api/settings/memory-plugin-status`) }, + + listManagedSkills: async (repoId?: number): Promise => { + const params = repoId ? `?repoId=${repoId}` : '' + return fetchWrapper(`${API_BASE_URL}/api/settings/skills${params}`) + }, + + getSkill: async (name: string, scope: SkillScope, repoId?: number): Promise => { + const params = new URLSearchParams({ scope }) + if (repoId) params.set('repoId', String(repoId)) + return fetchWrapper(`${API_BASE_URL}/api/settings/skills/${name}?${params}`) + }, + + createSkill: async (data: CreateSkillRequest): Promise => { + return fetchWrapper(`${API_BASE_URL}/api/settings/skills`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + }) + }, + + updateSkill: async (name: string, scope: SkillScope, data: UpdateSkillRequest, repoId?: number): Promise => { + const params = new URLSearchParams({ scope }) + if (repoId) params.set('repoId', String(repoId)) + return fetchWrapper(`${API_BASE_URL}/api/settings/skills/${name}?${params}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + }) + }, + + deleteSkill: async (name: string, scope: SkillScope, repoId?: number): Promise<{ success: boolean }> => { + const params = new URLSearchParams({ scope }) + if (repoId) params.set('repoId', String(repoId)) + return fetchWrapper(`${API_BASE_URL}/api/settings/skills/${name}?${params}`, { + method: 'DELETE', + }) + }, } export interface VersionInfo { diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index bc393cf0..1e342325 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -7,10 +7,14 @@ import { type TTSConfig, type STTConfig, type OpenCodeConfigContent, + type SkillFileInfo, + type CreateSkillRequest, + type UpdateSkillRequest, + type SkillScope, } from '@opencode-manager/shared' import type { NotificationPreferences } from '@opencode-manager/shared/types' -export type { TTSConfig, STTConfig, OpenCodeConfigContent, NotificationPreferences } +export type { TTSConfig, STTConfig, OpenCodeConfigContent, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY } export interface CustomCommand { diff --git a/frontend/src/components/schedules/ScheduleJobDialog.tsx b/frontend/src/components/schedules/ScheduleJobDialog.tsx index a86d808f..8f6cdb2c 100644 --- a/frontend/src/components/schedules/ScheduleJobDialog.tsx +++ b/frontend/src/components/schedules/ScheduleJobDialog.tsx @@ -1,8 +1,9 @@ -import { useEffect, useMemo, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { useQuery } from '@tanstack/react-query' import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob } from '@opencode-manager/shared/types' import { getProvidersWithModels } from '@/api/providers' import { createOpenCodeClient } from '@/api/opencode' +import { settingsApi } from '@/api/settings' import { OPENCODE_API_ENDPOINT } from '@/config' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' @@ -25,6 +26,7 @@ import { weekdayOptions, } from '@/components/schedules/schedule-utils' import { Check, Info, Loader2, Pencil, Plus, Sparkles, Trash2 } from 'lucide-react' +import { cn } from '@/lib/utils' import { usePromptTemplates, useDeletePromptTemplate } from '@/hooks/usePromptTemplates' import { PromptTemplateDialog } from './PromptTemplateDialog' import { DeleteDialog } from '@/components/ui/delete-dialog' @@ -65,8 +67,10 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit const [model, setModel] = useState('') const [prompt, setPrompt] = useState('') const [selectedPromptTemplateId, setSelectedPromptTemplateId] = useState(null) - const [skillSlugs, setSkillSlugs] = useState('') + const [skillSlugs, setSkillSlugs] = useState([]) const [skillNotes, setSkillNotes] = useState('') + const initialSkillSlugsRef = useRef(undefined) + const initialSkillNotesRef = useRef(undefined) const [templateDialogOpen, setTemplateDialogOpen] = useState(false) const [editingTemplate, setEditingTemplate] = useState(undefined) const [deletingTemplateId, setDeletingTemplateId] = useState(null) @@ -91,6 +95,13 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit staleTime: 5 * 60 * 1000, }) + const { data: skills = [], isLoading: skillsLoading } = useQuery({ + queryKey: ['managed-skills'], + queryFn: () => settingsApi.listManagedSkills(), + enabled: open, + staleTime: 5 * 60 * 1000, + }) + const { data: openCodeConfig } = useQuery({ queryKey: ['opencode-config', 'schedule-dialog'], queryFn: async () => { @@ -164,8 +175,12 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit setPrompt(job?.prompt ?? '') const matchingTemplate = templates.find((template) => template.prompt === (job?.prompt ?? '')) setSelectedPromptTemplateId(matchingTemplate ? matchingTemplate.id : null) - setSkillSlugs(job?.skillMetadata?.skillSlugs.join(', ') ?? '') - setSkillNotes(job?.skillMetadata?.notes ?? '') + const initialSkillSlugs = job?.skillMetadata?.skillSlugs ?? [] + const initialSkillNotes = job?.skillMetadata?.notes ?? '' + setSkillSlugs(initialSkillSlugs) + setSkillNotes(initialSkillNotes) + initialSkillSlugsRef.current = initialSkillSlugs + initialSkillNotesRef.current = initialSkillNotes }, [job, open, templates]) const applyPromptTemplate = (template: PromptTemplate) => { @@ -186,6 +201,10 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit monthlyDay, cronExpression, }) + const skillSlugsChanged = JSON.stringify(skillSlugs) !== JSON.stringify(initialSkillSlugsRef.current ?? []) + const skillNotesChanged = skillNotes.trim() !== (initialSkillNotesRef.current ?? '') + const shouldIncludeSkillMetadata = skillSlugsChanged || skillNotesChanged + const baseFields = { name: name.trim(), description: description.trim() || undefined, @@ -193,12 +212,14 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit agentSlug: agentSlug.trim() || undefined, model: model.trim() || undefined, prompt: prompt.trim(), - skillMetadata: skillSlugs.trim() || skillNotes.trim() - ? { - skillSlugs: skillSlugs.split(',').map((value) => value.trim()).filter(Boolean), - notes: skillNotes.trim() || undefined, - } - : undefined, + ...(shouldIncludeSkillMetadata ? { + skillMetadata: skillSlugs.length > 0 || skillNotes.trim() + ? { + skillSlugs, + notes: skillNotes.trim() || undefined, + } + : null, + } : {}), } if (schedulePreset !== 'interval') { @@ -575,26 +596,65 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit
-
-
-

Optional future integrations

-

You can ignore this for now. These fields are stored for future skill-aware scheduling, but the current MVP does not use them during execution.

-
-
+
+ +

+ Skills provide domain-specific instructions to the agent. Select which skills should be available when this schedule runs. +

+
-
- Edit optional skill metadata -
-
- - setSkillSlugs(event.target.value)} placeholder="nextjs, database-tuning" /> -
-
- -