mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
Refactor schedule service and add cron support
This commit is contained in:
1 parent
dbf48d4691
commit
47524876aa
24 files changed
+652
-139
No files matched your search
@@ -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')
|
||||
|
||||
@@ -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[]
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<string, string>): { output: string; timedOut: boolean } {
|
||||
function execWithTimeout(
|
||||
command: string | [executable: string, ...args: string[]],
|
||||
timeoutMs: number,
|
||||
env?: Record<string, string>
|
||||
): { 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()
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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<number, Cron>()
|
||||
private cronJobs = new Map<number, Stoppable>()
|
||||
|
||||
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<string, unknown> = { 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<typeof setTimeout> | 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,'))
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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<typeof vi.fn>
|
||||
const mockSpawnSync = spawnSync as ReturnType<typeof vi.fn>
|
||||
const mockGetVersion = opencodeServerManager.getVersion as ReturnType<typeof vi.fn>
|
||||
const mockFetchVersion = opencodeServerManager.fetchVersion as ReturnType<typeof vi.fn>
|
||||
const mockReloadConfig = opencodeServerManager.reloadConfig as ReturnType<typeof vi.fn>
|
||||
@@ -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<string, unknown>
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -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 }))
|
||||
})
|
||||
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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<SkillFileInfo[]> => {
|
||||
const params = repoId ? `?repoId=${repoId}` : ''
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills${params}`)
|
||||
},
|
||||
|
||||
getSkill: async (name: string, scope: SkillScope, repoId?: number): Promise<SkillFileInfo> => {
|
||||
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<SkillFileInfo> => {
|
||||
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<SkillFileInfo> => {
|
||||
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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<number | null>(null)
|
||||
const [skillSlugs, setSkillSlugs] = useState('')
|
||||
const [skillSlugs, setSkillSlugs] = useState<string[]>([])
|
||||
const [skillNotes, setSkillNotes] = useState('')
|
||||
const initialSkillSlugsRef = useRef<string[] | undefined>(undefined)
|
||||
const initialSkillNotesRef = useRef<string | undefined>(undefined)
|
||||
const [templateDialogOpen, setTemplateDialogOpen] = useState(false)
|
||||
const [editingTemplate, setEditingTemplate] = useState<PromptTemplate | undefined>(undefined)
|
||||
const [deletingTemplateId, setDeletingTemplateId] = useState<number | null>(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
|
||||
|
||||
<TabsContent value="skills" className="mt-0 min-h-0 flex-1 overflow-y-auto px-6 pt-4 pb-5">
|
||||
<div className="space-y-4">
|
||||
<section className="rounded-lg border border-border bg-card p-4">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-base font-medium flex items-center gap-2"><Sparkles className="h-4 w-4" /> Optional future integrations</h3>
|
||||
<p className="text-sm text-muted-foreground">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.</p>
|
||||
</div>
|
||||
</section>
|
||||
<div className="space-y-2">
|
||||
<Label>Select skills for this schedule</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Skills provide domain-specific instructions to the agent. Select which skills should be available when this schedule runs.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<details className="group rounded-lg border border-dashed border-border bg-card/50 p-4">
|
||||
<summary className="cursor-pointer list-none text-sm font-medium">Edit optional skill metadata</summary>
|
||||
<div className="mt-4 space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="schedule-skills">Skill tags</Label>
|
||||
<Input id="schedule-skills" value={skillSlugs} onChange={(event) => setSkillSlugs(event.target.value)} placeholder="nextjs, database-tuning" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="schedule-skill-notes">Notes</Label>
|
||||
<Textarea id="schedule-skill-notes" value={skillNotes} onChange={(event) => setSkillNotes(event.target.value)} placeholder="Optional notes for a future skill-aware scheduler." />
|
||||
</div>
|
||||
{skillsLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
</details>
|
||||
) : skills.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-border bg-card/50 p-6 text-center">
|
||||
<Sparkles className="h-6 w-6 mx-auto mb-2 text-muted-foreground" />
|
||||
<p className="text-sm text-muted-foreground">No skills discovered. Configure skill paths in Settings to make skills available here.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{skills.map((skill) => (
|
||||
<button
|
||||
key={skill.name}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSkillSlugs(prev =>
|
||||
prev.includes(skill.name)
|
||||
? prev.filter(s => s !== skill.name)
|
||||
: [...prev, skill.name]
|
||||
)
|
||||
}}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-sm font-medium transition-colors',
|
||||
skillSlugs.includes(skill.name)
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
{skillSlugs.includes(skill.name) && <Check className="h-3 w-3" />}
|
||||
{skill.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{skillSlugs.length > 0 && (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{skillSlugs.length} skill{skillSlugs.length !== 1 ? 's' : ''} selected
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="schedule-skill-notes">Notes</Label>
|
||||
<Textarea
|
||||
id="schedule-skill-notes"
|
||||
value={skillNotes}
|
||||
onChange={(event) => setSkillNotes(event.target.value)}
|
||||
placeholder="Optional notes about skill usage for this schedule."
|
||||
className="min-h-[80px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
@@ -13,6 +13,7 @@ import { CommandsEditor } from './CommandsEditor'
|
||||
import { AgentsEditor } from './AgentsEditor'
|
||||
import { AgentsMdEditor } from './AgentsMdEditor'
|
||||
import { McpManager } from './McpManager'
|
||||
import { SkillsEditor } from './SkillsEditor'
|
||||
import { VersionSelectDialog } from './VersionSelectDialog'
|
||||
import { MemoryPluginConfig } from './MemoryPluginConfig'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
@@ -62,6 +63,7 @@ export function OpenCodeConfigManager() {
|
||||
agentsMd: false,
|
||||
commands: false,
|
||||
agents: false,
|
||||
skills: false,
|
||||
mcp: false,
|
||||
})
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
|
||||
@@ -72,6 +74,7 @@ export function OpenCodeConfigManager() {
|
||||
const agentsMdRef = useRef<HTMLButtonElement>(null)
|
||||
const commandsRef = useRef<HTMLButtonElement>(null)
|
||||
const agentsRef = useRef<HTMLButtonElement>(null)
|
||||
const skillsRef = useRef<HTMLButtonElement>(null)
|
||||
const mcpRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
const scrollToSection = (ref: React.RefObject<HTMLButtonElement | null>) => {
|
||||
@@ -186,7 +189,8 @@ export function OpenCodeConfigManager() {
|
||||
|
||||
const agentsChanged = JSON.stringify(previousContent?.agent) !== JSON.stringify(newContent.agent)
|
||||
const pluginsChanged = JSON.stringify(previousContent?.plugin) !== JSON.stringify(newContent.plugin)
|
||||
if (restartServer || agentsChanged || pluginsChanged) {
|
||||
const skillsChanged = JSON.stringify(previousContent?.skills) !== JSON.stringify(newContent.skills)
|
||||
if (restartServer || agentsChanged || pluginsChanged || skillsChanged) {
|
||||
showToast.loading('Reloading server...', { id: 'update-restart' })
|
||||
try {
|
||||
await reloadConfigMutation.mutateAsync()
|
||||
@@ -687,6 +691,44 @@ export function OpenCodeConfigManager() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={skillsRef}
|
||||
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors min-w-0"
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.skills
|
||||
setExpandedSections(prev => ({ ...prev, skills: isExpanding }))
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(skillsRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Skills</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{(selectedConfig.content?.skills?.paths?.length ?? 0) + (selectedConfig.content?.skills?.urls?.length ?? 0)} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.skills ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.skills ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-4 max-h-[50vh] overflow-y-auto">
|
||||
<SkillsEditor
|
||||
skills={selectedConfig.content?.skills}
|
||||
onChange={(skills) => {
|
||||
const paths = skills?.paths?.filter(Boolean)
|
||||
const urls = skills?.urls?.filter(Boolean)
|
||||
const updatedContent = {
|
||||
...selectedConfig.content,
|
||||
skills: (paths?.length || urls?.length) ? { paths: paths?.length ? paths : undefined, urls: urls?.length ? urls : undefined } : undefined
|
||||
}
|
||||
updateConfigContent(selectedConfig.name, updatedContent)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={mcpRef}
|
||||
|
||||
@@ -8,6 +8,8 @@ export function invalidateConfigCaches(queryClient: QueryClient) {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['providers'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'providers'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
|
||||
}
|
||||
|
||||
export function invalidateSettingsCaches(queryClient: QueryClient, userId = 'default') {
|
||||
|
||||
@@ -8,3 +8,4 @@ export * from './notifications'
|
||||
export * from './ssh'
|
||||
export * from './memory'
|
||||
export * from './schedule'
|
||||
export * from './skills'
|
||||
@@ -60,7 +60,7 @@ const ScheduleJobBaseRequestSchema = z.object({
|
||||
agentSlug: z.string().min(1).max(100).optional(),
|
||||
prompt: z.string().min(1).max(20000),
|
||||
model: z.string().min(1).max(200).optional(),
|
||||
skillMetadata: ScheduleSkillMetadataSchema.optional(),
|
||||
skillMetadata: ScheduleSkillMetadataSchema.nullable().optional(),
|
||||
})
|
||||
|
||||
export const CreateScheduleJobRequestSchema = z.discriminatedUnion('scheduleMode', [
|
||||
|
||||
@@ -198,6 +198,10 @@ export const OpenCodeConfigSchema = z.object({
|
||||
disabled_providers: z.array(z.string()).optional(),
|
||||
share: z.enum(["manual", "auto", "disabled"]).optional(),
|
||||
plugin: z.array(z.string()).optional(),
|
||||
skills: z.object({
|
||||
paths: z.array(z.string()).optional(),
|
||||
urls: z.array(z.string()).optional(),
|
||||
}).optional(),
|
||||
}).strip();
|
||||
|
||||
export type OpenCodeConfigContent = z.infer<typeof OpenCodeConfigSchema>;
|
||||
|
||||
@@ -113,3 +113,19 @@ export type {
|
||||
CreatePromptTemplateRequest,
|
||||
UpdatePromptTemplateRequest,
|
||||
} from '../schemas/schedule'
|
||||
|
||||
export type {
|
||||
SkillScope,
|
||||
SkillFrontmatter,
|
||||
CreateSkillRequest,
|
||||
UpdateSkillRequest,
|
||||
SkillFileInfo,
|
||||
} from '../schemas/skills'
|
||||
export {
|
||||
SKILL_NAME_REGEX,
|
||||
SkillNameSchema,
|
||||
SkillScopeSchema,
|
||||
SkillFrontmatterSchema,
|
||||
CreateSkillRequestSchema,
|
||||
UpdateSkillRequestSchema,
|
||||
} from '../schemas/skills'
|
||||
Reference in new issue
Block a user