From 276b6c23233a0d09ae16b3b33c58d8f69d7e4188 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:00:43 -0500 Subject: [PATCH] feat: Schedules: one-shot runs and repo-defined schedule files (OM-31) - Once schedule data model, persistence and next-run - Run Once schedules: disable at timed start, one-shot timer - "Once" preset in the schedule dialog and Once display across - Apply remaining changes --- .../202611071200-schedule-run-at.ts | 22 +++ backend/src/db/migrations/index.ts | 2 + backend/src/db/schedules.ts | 16 +- backend/src/services/assistant-mode.ts | 2 +- backend/src/services/schedule-config.ts | 116 ++++++++++- backend/src/services/schedules.ts | 88 ++++++--- backend/test/db/schedule-run-at.test.ts | 124 ++++++++++++ backend/test/db/schedules.permission.test.ts | 1 + backend/test/db/schedules.test.ts | 4 + .../test/services/git/GitService.real.test.ts | 1 + backend/test/services/schedule-config.test.ts | 168 ++++++++++++++++ .../services/schedules.permission.test.ts | 1 + backend/test/services/schedules.test.ts | 183 +++++++++++++++++- .../schedules/ScheduleJobDialog.once.test.tsx | 168 ++++++++++++++++ .../schedules/ScheduleJobDialog.tsx | 16 ++ .../src/components/schedules/TimingTab.tsx | 19 +- .../__tests__/schedule-utils.test.ts | 143 +++++++++++++- .../components/schedules/schedule-utils.ts | 61 ++++++ frontend/src/pages/GlobalSchedules.tsx | 7 +- shared/src/schemas/schedule.ts | 14 +- 20 files changed, 1108 insertions(+), 48 deletions(-) create mode 100644 backend/src/db/migrations/202611071200-schedule-run-at.ts create mode 100644 backend/test/db/schedule-run-at.test.ts create mode 100644 frontend/src/components/schedules/ScheduleJobDialog.once.test.tsx diff --git a/backend/src/db/migrations/202611071200-schedule-run-at.ts b/backend/src/db/migrations/202611071200-schedule-run-at.ts new file mode 100644 index 00000000..1232195d --- /dev/null +++ b/backend/src/db/migrations/202611071200-schedule-run-at.ts @@ -0,0 +1,22 @@ +import type { Migration } from '../migration-runner' + +interface ColumnInfo { + name: string +} + +const migration: Migration = { + id: '202611071200-schedule-run-at', + + up(db) { + const columns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[] + if (!columns.some((column) => column.name === 'run_at')) { + db.run('ALTER TABLE schedule_jobs ADD COLUMN run_at TEXT') + } + }, + + down(db) { + db.run('ALTER TABLE schedule_jobs DROP COLUMN run_at') + }, +} + +export default migration diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts index 65fd0e26..0aa6844d 100644 --- a/backend/src/db/migrations/index.ts +++ b/backend/src/db/migrations/index.ts @@ -44,6 +44,7 @@ import migration202610231200 from './202610231200-push-subscription-session-id' import migration202610251900 from './202610251900-schedule-sandbox-config' import migration202610271800 from './202610271800-schedule-show-in-inbox' import migration202610291200 from './202610291200-drop-session-goals' +import migration202611071200 from './202611071200-schedule-run-at' export const allMigrations: Migration[] = [ migration001, @@ -91,4 +92,5 @@ export const allMigrations: Migration[] = [ migration202610251900, migration202610271800, migration202610291200, + migration202611071200, ] diff --git a/backend/src/db/schedules.ts b/backend/src/db/schedules.ts index 20b1da3f..c03d39d3 100644 --- a/backend/src/db/schedules.ts +++ b/backend/src/db/schedules.ts @@ -33,6 +33,7 @@ interface ScheduleJobRow { schedule_mode: ScheduleMode | null interval_minutes: number | null cron_expression: string | null + run_at: string | null timezone: string | null agent_slug: string | null prompt: string @@ -142,6 +143,7 @@ function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob { scheduleMode: row.schedule_mode ?? 'interval', intervalMinutes: row.interval_minutes, cronExpression: row.cron_expression, + runAt: row.run_at ?? null, timezone: row.timezone, agentSlug: row.agent_slug, prompt: row.prompt, @@ -245,7 +247,7 @@ export function createScheduleJob( const now = Date.now() const stmt = db.prepare(` INSERT INTO schedule_jobs ( - repo_id, server_id, directory, name, description, enabled, show_in_inbox, schedule_mode, interval_minutes, cron_expression, timezone, agent_slug, prompt, model, skill_metadata, + repo_id, server_id, directory, name, description, enabled, show_in_inbox, schedule_mode, interval_minutes, cron_expression, timezone, run_at, agent_slug, prompt, model, skill_metadata, permission_config, mcp_servers, branch, @@ -253,7 +255,7 @@ export function createScheduleJob( sandbox_config, created_at, updated_at, last_run_at, next_run_at ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `) const result = stmt.run( @@ -268,6 +270,7 @@ export function createScheduleJob( input.intervalMinutes, input.cronExpression, input.timezone, + input.runAt, input.agentSlug ?? null, input.prompt, input.model ?? null, @@ -300,7 +303,7 @@ export function updateScheduleJob(db: Database, repoId: number | null, jobId: nu const stmt = db.prepare(` UPDATE schedule_jobs - SET name = ?, description = ?, enabled = ?, show_in_inbox = ?, schedule_mode = ?, interval_minutes = ?, cron_expression = ?, timezone = ?, + SET name = ?, description = ?, enabled = ?, show_in_inbox = ?, schedule_mode = ?, interval_minutes = ?, cron_expression = ?, timezone = ?, run_at = ?, agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, mcp_servers = ?, branch = ?, workspace_mode = ?, sandbox_config = ?, directory = ?, updated_at = ?, next_run_at = ? WHERE repo_id IS ? AND id = ? `) @@ -314,6 +317,7 @@ export function updateScheduleJob(db: Database, repoId: number | null, jobId: nu input.intervalMinutes, input.cronExpression, input.timezone, + input.runAt, input.agentSlug, input.prompt, input.model, @@ -333,6 +337,12 @@ export function updateScheduleJob(db: Database, repoId: number | null, jobId: nu return getScheduleJobById(db, repoId, jobId) } +export function disableScheduleJob(db: Database, repoId: number | null, jobId: number): ScheduleJob | null { + db.prepare('UPDATE schedule_jobs SET enabled = 0, next_run_at = NULL, updated_at = ? WHERE repo_id IS ? AND id = ?') + .run(Date.now(), repoId, jobId) + return getScheduleJobById(db, repoId, jobId) +} + export function deleteScheduleJob(db: Database, repoId: number | null, jobId: number): boolean { db.prepare('DELETE FROM schedule_runs WHERE repo_id IS ? AND job_id = ?').run(repoId, jobId) const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id IS ? AND id = ?') diff --git a/backend/src/services/assistant-mode.ts b/backend/src/services/assistant-mode.ts index cbe01d13..5f1b5833 100644 --- a/backend/src/services/assistant-mode.ts +++ b/backend/src/services/assistant-mode.ts @@ -403,7 +403,7 @@ List all schedule jobs for a specific repo. ### POST /repos/:repoId/schedules Create a new schedule job. -Body matches \`CreateScheduleJobRequest\` schema (discriminated union with \`scheduleMode: 'interval' | 'cron'\`). +Body matches \`CreateScheduleJobRequest\` schema (discriminated union with \`scheduleMode: 'interval' | 'cron' | 'once'\`). \`once\` takes \`runAt\` (\`YYYY-MM-DDTHH:mm\` wall time) and \`timezone\`, must be in the future when enabled, and turns itself off when its timed run starts; \`Run now\` does not use it up. Optional \`workspaceMode\` sets where runs execute: \`worktree\` (default, a fresh worktree removed after each run), \`kept-worktree\` (a fresh worktree kept after each run), or \`shared-worktree\` (one worktree and branch reused by every run). Kept and shared worktrees are listed with \`GET /repos/:repoId/schedules/:jobId/worktrees\`. Removing schedule worktrees is done by the user in the Manager UI. diff --git a/backend/src/services/schedule-config.ts b/backend/src/services/schedule-config.ts index a41b3955..1d01c8fc 100644 --- a/backend/src/services/schedule-config.ts +++ b/backend/src/services/schedule-config.ts @@ -21,6 +21,7 @@ export interface ScheduleJobPersistenceInput { scheduleMode: ScheduleMode intervalMinutes: number | null cronExpression: string | null + runAt: string | null timezone: string | null agentSlug: string | null prompt: string @@ -44,6 +45,66 @@ function validateTimeZone(timezone: string): string { } } +export function resolveOnceRunAtMs(runAt: string, timezone: string): number { + const normalizedTimezone = validateTimeZone(timezone) + const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(runAt) + if (!match) { + throw new Error('Invalid date and time: ' + runAt) + } + + const year = Number(match[1]) + const month = Number(match[2]) + const day = Number(match[3]) + const hour = Number(match[4]) + const minute = Number(match[5]) + const guess = Date.UTC(year, month - 1, day, hour, minute) + const parsed = new Date(guess) + + if ( + parsed.getUTCFullYear() !== year || + parsed.getUTCMonth() !== month - 1 || + parsed.getUTCDate() !== day || + parsed.getUTCHours() !== hour || + parsed.getUTCMinutes() !== minute + ) { + throw new Error('Invalid date and time: ' + runAt) + } + + const offsetAt = (timestamp: number): number => { + const parts = new Intl.DateTimeFormat('en-US', { + timeZone: normalizedTimezone, + hourCycle: 'h23', + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + }).formatToParts(new Date(timestamp)) + const partValue = (type: Intl.DateTimeFormatPartTypes): number => + Number(parts.find((part) => part.type === type)?.value) + const wallClockMs = Date.UTC( + partValue('year'), + partValue('month') - 1, + partValue('day'), + partValue('hour'), + partValue('minute'), + partValue('second'), + ) + return wallClockMs - timestamp + } + + const offBefore = offsetAt(guess - 86_400_000) + const offAfter = offsetAt(guess + 86_400_000) + const matches = [guess - offBefore, guess - offAfter].filter( + (candidate) => candidate + offsetAt(candidate) === guess, + ) + if (matches.length === 0) { + return guess - offBefore + } + return Math.min(...matches) +} + function getCronNextRunAt(cronExpression: string, timezone: string, currentDate: number): number { const cron = new Cron(cronExpression, { timezone }) const next = cron.nextRun(new Date(currentDate)) @@ -62,6 +123,7 @@ function normalizeCronConfig(cronExpression: string, timezone: string | null | u scheduleMode: 'cron' as const, intervalMinutes: null, cronExpression: normalizedCronExpression, + runAt: null, timezone: normalizedTimezone, nextRunAt, } @@ -72,11 +134,25 @@ function normalizeIntervalConfig(intervalMinutes: number, currentDate: number) { scheduleMode: 'interval' as const, intervalMinutes, cronExpression: null, + runAt: null, timezone: null, nextRunAt: currentDate + intervalMinutes * 60_000, } } +function normalizeOnceConfig(runAt: string, timezone: string | null | undefined) { + const normalizedTimezone = validateTimeZone(timezone?.trim() || DEFAULT_CRON_TIMEZONE) + + return { + scheduleMode: 'once' as const, + intervalMinutes: null, + cronExpression: null, + runAt, + timezone: normalizedTimezone, + nextRunAt: resolveOnceRunAtMs(runAt, normalizedTimezone), + } +} + export function computeNextRunAtForJob(job: ScheduleJob, currentDate: number): number | null { if (!job.enabled) { return null @@ -90,6 +166,15 @@ export function computeNextRunAtForJob(job: ScheduleJob, currentDate: number): n return getCronNextRunAt(job.cronExpression, job.timezone || DEFAULT_CRON_TIMEZONE, currentDate) } + if (job.scheduleMode === 'once') { + if (!job.runAt) { + throw new Error('A date and time is required for one-time schedules') + } + + const runAt = resolveOnceRunAtMs(job.runAt, job.timezone || DEFAULT_CRON_TIMEZONE) + return runAt > currentDate ? runAt : null + } + if (!job.intervalMinutes) { throw new Error('Interval minutes are required for interval schedules') } @@ -115,7 +200,13 @@ export function buildCreateSchedulePersistenceInput(input: CreateScheduleJobRequ const scheduleConfig = input.scheduleMode === 'cron' ? normalizeCronConfig(input.cronExpression, input.timezone, currentDate) - : normalizeIntervalConfig(input.intervalMinutes, currentDate) + : input.scheduleMode === 'once' + ? normalizeOnceConfig(input.runAt, input.timezone) + : normalizeIntervalConfig(input.intervalMinutes, currentDate) + + if (input.scheduleMode === 'once' && base.enabled && scheduleConfig.nextRunAt <= currentDate) { + throw new Error('Choose a future date and time for a one-time schedule') + } return { ...base, @@ -140,23 +231,35 @@ export function buildUpdatedSchedulePersistenceInput( input.timezone ?? existing.timezone ?? DEFAULT_CRON_TIMEZONE, currentDate, ) - : normalizeIntervalConfig( - input.intervalMinutes ?? existing.intervalMinutes ?? 60, - currentDate, - ) + : scheduleMode === 'once' + ? normalizeOnceConfig( + input.runAt ?? existing.runAt ?? '', + input.timezone ?? existing.timezone ?? DEFAULT_CRON_TIMEZONE, + ) + : normalizeIntervalConfig( + input.intervalMinutes ?? existing.intervalMinutes ?? 60, + currentDate, + ) const scheduleChanged = input.scheduleMode !== undefined || input.intervalMinutes !== undefined || input.cronExpression !== undefined || + input.runAt !== undefined || input.timezone !== undefined + const recomputeNextRunAt = scheduleChanged || input.enabled !== undefined || existing.nextRunAt === null + const nextRunAt = enabled - ? scheduleChanged || input.enabled !== undefined || existing.nextRunAt === null + ? recomputeNextRunAt ? scheduleConfig.nextRunAt : existing.nextRunAt : null + if (scheduleConfig.scheduleMode === 'once' && enabled && recomputeNextRunAt && scheduleConfig.nextRunAt <= currentDate) { + throw new Error('Choose a future date and time for a one-time schedule') + } + return { name: input.name?.trim() || existing.name, description: input.description === undefined ? existing.description : (input.description?.trim() || null), @@ -165,6 +268,7 @@ export function buildUpdatedSchedulePersistenceInput( scheduleMode: scheduleConfig.scheduleMode, intervalMinutes: scheduleConfig.intervalMinutes, cronExpression: scheduleConfig.cronExpression, + runAt: scheduleConfig.runAt, timezone: scheduleConfig.timezone, agentSlug: input.agentSlug === undefined ? existing.agentSlug : (input.agentSlug?.trim() || null), prompt: input.prompt?.trim() || existing.prompt, diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index 15be090a..ad2698ac 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -26,6 +26,7 @@ import { deleteScheduleJob, deleteScheduleRunById, deleteScheduleRunsByIds, + disableScheduleJob, getScheduleJobById, getRunningScheduleRunByJob, getScheduleRunById, @@ -122,6 +123,16 @@ function buildSessionTitle(job: ScheduleJob): string { type SkillAttachment = { id: string } +function formatScheduleLabel(job: ScheduleJob): string { + if (job.scheduleMode === 'cron') { + return `${job.cronExpression ?? ''} (${job.timezone ?? 'UTC'})` + } + if (job.scheduleMode === 'once') { + return `${job.runAt ?? ''} (${job.timezone ?? 'UTC'})` + } + return `every ${job.intervalMinutes ?? 0} minutes` +} + function buildRunLog(input: { job: ScheduleJob triggerSource: ScheduleRunTriggerSource @@ -131,9 +142,7 @@ function buildRunLog(input: { errorText?: string | null finishedAt: number }): string { - const scheduleLabel = input.job.scheduleMode === 'cron' - ? `${input.job.cronExpression ?? ''} (${input.job.timezone ?? 'UTC'})` - : `every ${input.job.intervalMinutes ?? 0} minutes` + const scheduleLabel = formatScheduleLabel(input.job) const lines = [ `Job: ${input.job.name}`, @@ -168,9 +177,7 @@ function buildRunStartedLog(input: { sessionId: string sessionTitle: string }): string { - const scheduleLabel = input.job.scheduleMode === 'cron' - ? `${input.job.cronExpression ?? ''} (${input.job.timezone ?? 'UTC'})` - : `every ${input.job.intervalMinutes ?? 0} minutes` + const scheduleLabel = formatScheduleLabel(input.job) return [ `Job: ${input.job.name}`, @@ -951,6 +958,13 @@ export class ScheduleService { createdAt: startedAt, }) + if (triggerSource === 'schedule' && job.scheduleMode === 'once') { + const disabledJob = disableScheduleJob(this.db, repoId, jobId) + if (disabledJob) { + this.onJobChange?.(disabledJob, jobId) + } + } + const abort = new AbortController() ScheduleService.activeRuns.set(jobId, { runId: run.id, abort }) let repo: Repo | null = null @@ -1087,10 +1101,7 @@ export class ScheduleService { }) try { - updateScheduleJobRunState(this.db, repoId, jobId, { - lastRunAt: finishedAt, - nextRunAt: triggerSource === 'manual' ? job.nextRunAt : computeNextRunAtForJob(job, finishedAt), - }) + this.recordRunFinished(repoId, job, triggerSource, finishedAt) } catch (updateError) { logger.error(`Failed to update job state for job ${jobId}:`, updateError) } @@ -1340,10 +1351,7 @@ export class ScheduleService { }), }) - updateScheduleJobRunState(this.db, input.repoId, input.job.id, { - lastRunAt: finishedAt, - nextRunAt: input.triggerSource === 'manual' ? input.job.nextRunAt : computeNextRunAtForJob(input.job, finishedAt), - }) + this.recordRunFinished(input.repoId, input.job, input.triggerSource, finishedAt) } finally { await ScheduleService.awaitCancelDecision(input.job.id, input.runId) input.sessionMonitor.dispose() @@ -1436,10 +1444,7 @@ export class ScheduleService { }) } - updateScheduleJobRunState(this.db, input.repoId, input.job.id, { - lastRunAt: finishedAt, - nextRunAt: input.triggerSource === 'manual' ? input.job.nextRunAt : computeNextRunAtForJob(input.job, finishedAt), - }) + this.recordRunFinished(input.repoId, input.job, input.triggerSource, finishedAt) } catch (error) { if ((await ScheduleService.awaitCancelDecision(input.job.id, input.runId)) !== 'resume') { return @@ -1470,10 +1475,7 @@ export class ScheduleService { }), }) - updateScheduleJobRunState(this.db, input.repoId, input.job.id, { - lastRunAt: finishedAt, - nextRunAt: input.triggerSource === 'manual' ? input.job.nextRunAt : computeNextRunAtForJob(input.job, finishedAt), - }) + this.recordRunFinished(input.repoId, input.job, input.triggerSource, finishedAt) } finally { await ScheduleService.awaitCancelDecision(input.job.id, input.runId) input.sessionMonitor.dispose() @@ -1574,15 +1576,29 @@ export class ScheduleService { }), }) - updateScheduleJobRunState(this.db, run.repoId, run.jobId, { - lastRunAt: finishedAt, - nextRunAt: run.triggerSource === 'manual' ? job.nextRunAt : computeNextRunAtForJob(job, finishedAt), - }) + this.recordRunFinished(run.repoId, job, run.triggerSource, finishedAt) await this.teardownRunResources(run.repoId, run.jobId, run.id, job, repo, run.sessionId) ScheduleService.releaseActiveRun(job.id, run.id) } + /** + * Records that a run finished, deriving the next run time from the job as it exists now rather than + * the snapshot captured when the run started, so edits made mid-run are not clobbered. + */ + private recordRunFinished( + repoId: number | null, + fallbackJob: ScheduleJob, + triggerSource: ScheduleRunTriggerSource, + finishedAt: number, + ): void { + const current = getScheduleJobById(this.db, repoId, fallbackJob.id) ?? fallbackJob + updateScheduleJobRunState(this.db, repoId, fallbackJob.id, { + lastRunAt: finishedAt, + nextRunAt: triggerSource === 'manual' ? current.nextRunAt : computeNextRunAtForJob(current, finishedAt), + }) + } + private async interruptCancelledSession(client: OpenCodeClient, sessionId: string): Promise { try { await client.api.session.interrupt({ sessionID: sessionId }) @@ -1967,6 +1983,26 @@ export class ScheduleRunner { return } + if (job.scheduleMode === 'once') { + if (!job.nextRunAt) { + logger.warn(`Job ${job.id} (${job.name}) has no nextRunAt, skipping registration`) + return + } + + if (job.nextRunAt <= Date.now()) { + void this.executeJob(job) + return + } + + const cron = new Cron(new Date(job.nextRunAt), { protect: true }, () => { + logger.info(`Once job triggered for job ${job.id}: ${job.name}`) + void this.executeJob(job) + }) + this.cronJobs.set(job.id, cron) + logger.info(`Once job created for ${job.id}: next run at ${cron.nextRun()?.toISOString()}`) + return + } + if (!job.intervalMinutes) { return } diff --git a/backend/test/db/schedule-run-at.test.ts b/backend/test/db/schedule-run-at.test.ts new file mode 100644 index 00000000..9aaad288 --- /dev/null +++ b/backend/test/db/schedule-run-at.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it } from 'vitest' +import { Database } from 'bun:sqlite' +import { CreateScheduleJobRequestSchema, type ScheduleJob } from '@opencode-manager/shared/schemas' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import { createRepo } from '../../src/db/queries' +import { + createScheduleJob, + disableScheduleJob, + getScheduleJobById, + updateScheduleJob, +} from '../../src/db/schedules' +import { + buildCreateSchedulePersistenceInput, + buildUpdatedSchedulePersistenceInput, +} from '../../src/services/schedule-config' + +function createTestDb(): Database { + const db = new Database(':memory:') + migrate(db, allMigrations) + return db +} + +function createTestRepo(db: Database): number { + const repo = createRepo(db, { + localPath: '/abs/repo', + sourcePath: '/abs/repo', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + }) + return repo.id +} + +function createOnceJob(db: Database, repoId: number, currentDate: number): ScheduleJob { + const request = CreateScheduleJobRequestSchema.parse({ + name: 'One-time report', + scheduleMode: 'once', + runAt: '2026-11-20T09:00', + timezone: 'Europe/Berlin', + prompt: 'Generate the report.', + }) + return createScheduleJob(db, repoId, buildCreateSchedulePersistenceInput(request, currentDate)) +} + +describe('schedule run at', () => { + const currentDate = Date.UTC(2026, 10, 1, 12, 0, 0) + + it('accepts a valid once request and rejects a malformed date', () => { + const request = { + name: 'One-time request', + scheduleMode: 'once' as const, + timezone: 'Europe/Berlin', + prompt: 'Generate the report.', + } + + const parsed = CreateScheduleJobRequestSchema.parse({ ...request, runAt: '2026-11-20T09:00' }) + expect(parsed).toMatchObject({ scheduleMode: 'once', runAt: '2026-11-20T09:00' }) + expect(() => CreateScheduleJobRequestSchema.parse({ ...request, runAt: '2026-11-20 09:00' })).toThrow('Use YYYY-MM-DDTHH:mm') + }) + + it('round-trips a once schedule date, timezone and next run', () => { + const db = createTestDb() + const repoId = createTestRepo(db) + + const created = createOnceJob(db, repoId, currentDate) + const loaded = getScheduleJobById(db, created.repoId, created.id) + + expect(created.scheduleMode).toBe('once') + expect(created.runAt).toBe('2026-11-20T09:00') + expect(created.timezone).toBe('Europe/Berlin') + expect(created.nextRunAt).toBe(Date.UTC(2026, 10, 20, 8, 0, 0)) + expect(loaded?.runAt).toBe('2026-11-20T09:00') + expect(loaded?.timezone).toBe('Europe/Berlin') + expect(loaded?.nextRunAt).toBe(Date.UTC(2026, 10, 20, 8, 0, 0)) + + const updated = updateScheduleJob( + db, + created.repoId, + created.id, + buildUpdatedSchedulePersistenceInput(created, { runAt: '2026-12-01T10:00' }, currentDate), + ) + + expect(updated?.runAt).toBe('2026-12-01T10:00') + expect(getScheduleJobById(db, created.repoId, created.id)?.runAt).toBe('2026-12-01T10:00') + + db.close() + }) + + it('disables a schedule and clears its next run', () => { + const db = createTestDb() + const repoId = createTestRepo(db) + const created = createOnceJob(db, repoId, currentDate) + + const disabled = disableScheduleJob(db, created.repoId, created.id) + const loaded = getScheduleJobById(db, created.repoId, created.id) + + expect(disabled?.enabled).toBe(false) + expect(disabled?.nextRunAt).toBeNull() + expect(loaded?.enabled).toBe(false) + expect(loaded?.nextRunAt).toBeNull() + + db.close() + }) + + it('reads a null run at for interval schedules', () => { + const db = createTestDb() + const repoId = createTestRepo(db) + const request = CreateScheduleJobRequestSchema.parse({ + name: 'Interval report', + scheduleMode: 'interval', + intervalMinutes: 60, + prompt: 'Generate the report.', + }) + + const created = createScheduleJob(db, repoId, buildCreateSchedulePersistenceInput(request, currentDate)) + + expect(created.runAt).toBeNull() + expect(getScheduleJobById(db, created.repoId, created.id)?.runAt).toBeNull() + + db.close() + }) +}) diff --git a/backend/test/db/schedules.permission.test.ts b/backend/test/db/schedules.permission.test.ts index aa8f9bc7..e632b012 100644 --- a/backend/test/db/schedules.permission.test.ts +++ b/backend/test/db/schedules.permission.test.ts @@ -29,6 +29,7 @@ describe('schedule permission config persistence', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Run a permission test', model: null, diff --git a/backend/test/db/schedules.test.ts b/backend/test/db/schedules.test.ts index 092f6409..932a5912 100644 --- a/backend/test/db/schedules.test.ts +++ b/backend/test/db/schedules.test.ts @@ -110,6 +110,7 @@ describe('schedule database queries', () => { intervalMinutes: null, cronExpression: '0 9 * * 1', timezone: 'UTC', + runAt: null, agentSlug: 'planner', prompt: 'Generate a weekly summary.', model: 'openai/gpt-5-mini', @@ -134,6 +135,7 @@ describe('schedule database queries', () => { null, '0 9 * * 1', 'UTC', + null, 'planner', 'Generate a weekly summary.', 'openai/gpt-5-mini', @@ -176,6 +178,7 @@ describe('schedule database queries', () => { intervalMinutes: 90, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Run a new summary.', model: null, @@ -198,6 +201,7 @@ describe('schedule database queries', () => { null, null, null, + null, 'Run a new summary.', null, null, diff --git a/backend/test/services/git/GitService.real.test.ts b/backend/test/services/git/GitService.real.test.ts index 56fb6a52..2cbf5025 100644 --- a/backend/test/services/git/GitService.real.test.ts +++ b/backend/test/services/git/GitService.real.test.ts @@ -40,6 +40,7 @@ function scheduleJobInput(name: string, branch: string): ScheduleJobPersistenceI intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'do work', model: null, diff --git a/backend/test/services/schedule-config.test.ts b/backend/test/services/schedule-config.test.ts index 4f7abecf..1491c913 100644 --- a/backend/test/services/schedule-config.test.ts +++ b/backend/test/services/schedule-config.test.ts @@ -4,6 +4,7 @@ import { buildCreateSchedulePersistenceInput, buildUpdatedSchedulePersistenceInput, computeNextRunAtForJob, + resolveOnceRunAtMs, } from '../../src/services/schedule-config' describe('schedule-config', () => { @@ -31,6 +32,7 @@ describe('schedule-config', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: 'code', prompt: 'Review the repository and summarize risks.', model: 'openai/gpt-5', @@ -75,6 +77,7 @@ describe('schedule-config', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Old prompt', model: null, @@ -110,6 +113,7 @@ describe('schedule-config', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: 'planner', prompt: 'Old prompt', model: 'openai/gpt-5-mini', @@ -148,6 +152,7 @@ describe('schedule-config', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Prompt', model: null, @@ -182,6 +187,7 @@ describe('schedule-config', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Prompt', model: null, @@ -216,6 +222,7 @@ describe('schedule-config', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Prompt', model: null, @@ -250,6 +257,7 @@ describe('schedule-config', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Prompt', model: null, @@ -284,6 +292,7 @@ describe('schedule-config', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Prompt', model: null, @@ -318,6 +327,7 @@ describe('schedule-config', () => { intervalMinutes: 30, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Run a report', model: null, @@ -366,6 +376,7 @@ describe('schedule-config', () => { intervalMinutes: 15, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Prompt', model: null, @@ -384,6 +395,162 @@ describe('schedule-config', () => { expect(computeNextRunAtForJob(job, Date.UTC(2026, 2, 9, 12, 0, 0))).toBeNull() }) + describe('one-time schedules', () => { + const onceJob = (overrides: Partial = {}): ScheduleJob => ({ + id: 20, + repoId: 42, + name: 'One-time report', + description: null, + enabled: true, + showInInbox: true, + scheduleMode: 'once', + intervalMinutes: null, + cronExpression: null, + timezone: 'Europe/Berlin', + runAt: '2026-11-20T09:00', + agentSlug: null, + prompt: 'Prompt', + model: null, + skillMetadata: null, + permissionConfig: null, + mcpServers: [], + branch: null, + workspaceMode: 'worktree', + sandbox: null, + nextRunAt: Date.UTC(2026, 10, 20, 8, 0, 0), + lastRunAt: null, + createdAt: Date.UTC(2026, 10, 1, 12, 0, 0), + updatedAt: Date.UTC(2026, 10, 1, 12, 0, 0), + ...overrides, + }) + + it('builds a once persistence input from a wall-clock date and time', () => { + const result = buildCreateSchedulePersistenceInput({ + name: 'One-time report', + enabled: true, + showInInbox: true, + scheduleMode: 'once', + runAt: '2026-11-20T09:00', + timezone: 'Europe/Berlin', + prompt: 'Generate the report.', + }, Date.UTC(2026, 10, 1, 12, 0, 0)) + + expect(result.scheduleMode).toBe('once') + expect(result.runAt).toBe('2026-11-20T09:00') + expect(result.timezone).toBe('Europe/Berlin') + expect(result.intervalMinutes).toBeNull() + expect(result.cronExpression).toBeNull() + expect(result.nextRunAt).toBe(Date.UTC(2026, 10, 20, 8, 0, 0)) + }) + + it('resolves a once time through daylight saving time', () => { + const result = buildCreateSchedulePersistenceInput({ + name: 'Summer report', + enabled: true, + showInInbox: true, + scheduleMode: 'once', + runAt: '2026-07-01T09:00', + timezone: 'Europe/Berlin', + prompt: 'Generate the summer report.', + }, Date.UTC(2026, 5, 1, 12, 0, 0)) + + expect(result.nextRunAt).toBe(Date.UTC(2026, 6, 1, 7, 0, 0)) + }) + + it('rejects an enabled once schedule in the past', () => { + expect(() => buildCreateSchedulePersistenceInput({ + name: 'Past report', + enabled: true, + showInInbox: true, + scheduleMode: 'once', + runAt: '2026-11-20T09:00', + timezone: 'Europe/Berlin', + prompt: 'Generate the report.', + }, Date.UTC(2026, 10, 21, 12, 0, 0))).toThrow('Choose a future date and time for a one-time schedule') + }) + + it('rejects a date that does not exist', () => { + expect(() => buildCreateSchedulePersistenceInput({ + name: 'Impossible report', + enabled: true, + showInInbox: true, + scheduleMode: 'once', + runAt: '2026-02-30T09:00', + timezone: 'Europe/Berlin', + prompt: 'Generate the report.', + }, Date.UTC(2026, 0, 1, 12, 0, 0))).toThrow('Invalid date and time: 2026-02-30T09:00') + }) + + it('renames a used-up disabled once schedule without recomputing a next run', () => { + const existing = onceJob({ + enabled: false, + runAt: '2026-01-05T09:00', + nextRunAt: null, + }) + + const result = buildUpdatedSchedulePersistenceInput(existing, { + name: 'Renamed report', + }, Date.UTC(2026, 5, 1, 12, 0, 0)) + + expect(result.name).toBe('Renamed report') + expect(result.runAt).toBe('2026-01-05T09:00') + expect(result.nextRunAt).toBeNull() + }) + + it('rejects re-enabling a once schedule whose time has passed', () => { + const existing = onceJob({ + enabled: false, + runAt: '2026-01-05T09:00', + nextRunAt: null, + }) + + expect(() => buildUpdatedSchedulePersistenceInput(existing, { + enabled: true, + }, Date.UTC(2026, 5, 1, 12, 0, 0))).toThrow('Choose a future date and time for a one-time schedule') + }) + + it('clears the once date when switching to cron', () => { + const result = buildUpdatedSchedulePersistenceInput(onceJob(), { + scheduleMode: 'cron', + cronExpression: '0 9 * * *', + }, Date.UTC(2026, 10, 1, 12, 0, 0)) + + expect(result.scheduleMode).toBe('cron') + expect(result.cronExpression).toBe('0 9 * * *') + expect(result.runAt).toBeNull() + }) + + it('computes the next run for an enabled once job from its date', () => { + const job = onceJob() + + expect(computeNextRunAtForJob(job, Date.UTC(2026, 10, 1, 12, 0, 0))).toBe(Date.UTC(2026, 10, 20, 8, 0, 0)) + expect(computeNextRunAtForJob(job, Date.UTC(2026, 10, 21, 12, 0, 0))).toBeNull() + }) + + it('requires a stored date and time when computing a once next run', () => { + expect(() => computeNextRunAtForJob(onceJob({ runAt: null }), Date.UTC(2026, 10, 1, 12, 0, 0))) + .toThrow('A date and time is required for one-time schedules') + }) + }) + + describe('once time resolution across DST transitions', () => { + it('moves a skipped New York wall clock forward by the spring-forward gap', () => { + expect(resolveOnceRunAtMs('2026-03-08T02:30', 'America/New_York')).toBe(Date.UTC(2026, 2, 8, 7, 30)) + }) + + it('moves a skipped Berlin wall clock forward by the spring-forward gap', () => { + expect(resolveOnceRunAtMs('2026-03-29T02:30', 'Europe/Berlin')).toBe(Date.UTC(2026, 2, 29, 1, 30)) + }) + + it('resolves an ambiguous New York wall clock to its first occurrence', () => { + expect(resolveOnceRunAtMs('2026-11-01T01:30', 'America/New_York')).toBe(Date.UTC(2026, 10, 1, 5, 30)) + }) + + it('resolves an ambiguous Berlin wall clock to its first occurrence', () => { + expect(resolveOnceRunAtMs('2026-10-25T02:30', 'Europe/Berlin')).toBe(Date.UTC(2026, 9, 25, 0, 30)) + }) + }) + describe('sandbox config', () => { const sandbox = { enabled: true, resources: { cpus: 4, memoryMib: 12288 } } @@ -398,6 +565,7 @@ describe('schedule-config', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Prompt', model: null, diff --git a/backend/test/services/schedules.permission.test.ts b/backend/test/services/schedules.permission.test.ts index 2938ef3a..fa2021ea 100644 --- a/backend/test/services/schedules.permission.test.ts +++ b/backend/test/services/schedules.permission.test.ts @@ -119,6 +119,7 @@ const baseJob: ScheduleJob = { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Review the repository and summarize the current state.', model: null, diff --git a/backend/test/services/schedules.test.ts b/backend/test/services/schedules.test.ts index 24c83b7a..9c8599ba 100644 --- a/backend/test/services/schedules.test.ts +++ b/backend/test/services/schedules.test.ts @@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({ createScheduleRun: vi.fn(), deleteScheduleJob: vi.fn(), deleteScheduleRunById: vi.fn(), + disableScheduleJob: vi.fn(), deleteScheduleRunsByIds: vi.fn(), listScheduleRunArtifactsByJob: vi.fn(), cleanupOrphanedSchedules: vi.fn(), @@ -57,6 +58,7 @@ vi.mock('../../src/db/schedules', () => ({ createScheduleRun: mocks.createScheduleRun, deleteScheduleJob: mocks.deleteScheduleJob, deleteScheduleRunById: mocks.deleteScheduleRunById, + disableScheduleJob: mocks.disableScheduleJob, deleteScheduleRunsByIds: mocks.deleteScheduleRunsByIds, listScheduleRunArtifactsByJob: mocks.listScheduleRunArtifactsByJob, cleanupOrphanedSchedules: mocks.cleanupOrphanedSchedules, @@ -107,11 +109,11 @@ vi.mock('../../src/utils/logger', () => ({ })) const mockCronStop = vi.fn() -const mockCronInstances: Array<{ callback: () => void; options: Record; pattern: string; stop: typeof mockCronStop }> = [] +const mockCronInstances: Array<{ callback: () => void; nextRun: () => null; options: Record; pattern: string | Date; stop: typeof mockCronStop }> = [] vi.mock('croner', () => ({ - Cron: vi.fn().mockImplementation((pattern: string, options: Record, callback: () => void) => { - const instance = { pattern, options, callback, stop: mockCronStop } + Cron: vi.fn().mockImplementation((pattern: string | Date, options: Record, callback: () => void) => { + const instance = { pattern, options, callback, nextRun: vi.fn(() => null), stop: mockCronStop } mockCronInstances.push(instance) return instance }), @@ -194,6 +196,7 @@ const job: ScheduleJob = { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Review the repository and summarize the current state.', model: null, @@ -1635,6 +1638,118 @@ describe('ScheduleService', () => { expect(mocks.updateScheduleJob).toHaveBeenCalled() }) }) + + describe('once schedules', () => { + function onceScheduleJob(overrides: Partial = {}): ScheduleJob { + return { ...job, scheduleMode: 'once', intervalMinutes: null, runAt: '2026-03-09T13:00', ...overrides } + } + + it('disables a once job before starting its timed run', async () => { + const scheduledJob = onceScheduleJob() + const disabledJob = { ...scheduledJob, enabled: false, nextRunAt: null } + mocks.getScheduleJobById.mockReturnValue(scheduledJob) + mocks.disableScheduleJob.mockReturnValue(disabledJob) + mocks.updateScheduleRunMetadata.mockReturnValue({ + ...baseRun, + sessionId: 'ses-run-1', + sessionTitle: 'Scheduled: Weekly engineering summary', + }) + const onChange = vi.fn() + const stub = createStubScheduleApi({ + sessionID: 'ses-run-1', + messages: [assistantMessage('Once done.', { completed: true })], + }) + const service = makeService(stub.api) + service.setJobChangeHandler(onChange) + + await service.runJob(42, 7, 'schedule') + + expect(mocks.disableScheduleJob).toHaveBeenCalledWith(expect.anything(), 42, 7) + expect(onChange).toHaveBeenCalledWith(disabledJob, 7) + expect(mocks.disableScheduleJob.mock.invocationCallOrder[0]).toBeLessThan( + vi.mocked(stub.api.session.create).mock.invocationCallOrder[0]!, + ) + expect(mocks.updateScheduleRunMetadata).toHaveBeenCalledWith( + expect.anything(), + 42, + 7, + 5, + expect.objectContaining({ logText: expect.stringContaining('2026-03-09T13:00') }), + ) + }) + + it('derives the next run time from the reloaded job when a once job changes mid-run', async () => { + const startedSnapshot = onceScheduleJob({ nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0) }) + const reenabledJob = onceScheduleJob({ + enabled: true, + runAt: '2026-03-10T13:00', + nextRunAt: Date.UTC(2026, 2, 10, 13, 0, 0), + }) + mocks.getScheduleJobById.mockReturnValueOnce(startedSnapshot).mockReturnValue(reenabledJob) + mocks.disableScheduleJob.mockReturnValue({ ...startedSnapshot, enabled: false, nextRunAt: null }) + mocks.updateScheduleRunMetadata.mockReturnValue({ + ...baseRun, + sessionId: 'ses-run-1', + sessionTitle: 'Scheduled: Weekly engineering summary', + }) + mocks.computeNextRunAtForJob.mockReturnValue(Date.UTC(2026, 2, 10, 13, 0, 0)) + const stub = createStubScheduleApi({ + sessionID: 'ses-run-1', + messages: [assistantMessage('Once done.', { completed: true })], + }) + const service = makeService(stub.api) + + await service.runJob(42, 7, 'schedule') + + await vi.waitFor(() => { + expect(mocks.updateScheduleJobRunState).toHaveBeenCalledWith( + expect.anything(), + 42, + 7, + expect.objectContaining({ nextRunAt: Date.UTC(2026, 2, 10, 13, 0, 0) }), + ) + }) + + expect(mocks.computeNextRunAtForJob).toHaveBeenCalledWith(reenabledJob, expect.any(Number)) + expect(mocks.computeNextRunAtForJob).not.toHaveBeenCalledWith(startedSnapshot, expect.anything()) + }) + + it('keeps a once job enabled for a manual run', async () => { + mocks.getScheduleJobById.mockReturnValue(onceScheduleJob()) + mocks.updateScheduleRunMetadata.mockReturnValue({ ...baseRun, sessionId: 'ses-run-1' }) + const stub = createStubScheduleApi({ + sessionID: 'ses-run-1', + messages: [assistantMessage('Manual done.', { completed: true })], + }) + const service = makeService(stub.api) + + await service.runJob(42, 7, 'manual') + + expect(mocks.disableScheduleJob).not.toHaveBeenCalled() + await vi.waitFor(() => { + expect(mocks.updateScheduleJobRunState).toHaveBeenCalledWith( + expect.anything(), + 42, + 7, + expect.objectContaining({ nextRunAt: job.nextRunAt }), + ) + }) + }) + + it('does not disable a cron job on a timed run', async () => { + mocks.getScheduleJobById.mockReturnValue({ ...job, scheduleMode: 'cron', intervalMinutes: null, cronExpression: '0 9 * * *' }) + mocks.updateScheduleRunMetadata.mockReturnValue({ ...baseRun, sessionId: 'ses-run-1' }) + const stub = createStubScheduleApi({ + sessionID: 'ses-run-1', + messages: [assistantMessage('Cron done.', { completed: true })], + }) + const service = makeService(stub.api) + + await service.runJob(42, 7, 'schedule') + + expect(mocks.disableScheduleJob).not.toHaveBeenCalled() + }) + }) }) describe('ScheduleService startup cancellation', () => { @@ -2567,6 +2682,7 @@ describe('ScheduleRunner', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Test', model: null, @@ -2608,6 +2724,7 @@ describe('ScheduleRunner', () => { cronExpression: '0 9 * * *', timezone: 'America/New_York', intervalMinutes: null, + runAt: null, agentSlug: null, prompt: 'Test', model: null, @@ -2647,6 +2764,7 @@ describe('ScheduleRunner', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Test', model: null, @@ -2685,6 +2803,7 @@ describe('ScheduleRunner', () => { intervalMinutes: 30, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Test', model: null, @@ -2723,6 +2842,7 @@ describe('ScheduleRunner', () => { intervalMinutes: 60, cronExpression: null, timezone: null, + runAt: null, agentSlug: null, prompt: 'Test', model: null, @@ -2753,6 +2873,63 @@ describe('ScheduleRunner', () => { expect(mockCronStop).toHaveBeenCalled() expect(mockCronInstances).toHaveLength(2) }) + + it('registers a future once job as a single one-time cron', () => { + const futureRunAt = Date.now() + 3_600_000 + const onceJob: ScheduleJob = { + ...job, + scheduleMode: 'once', + intervalMinutes: null, + runAt: '2026-03-09T13:00', + nextRunAt: futureRunAt, + } + const service = makeService(createStubScheduleApi().api) + const runner = new ScheduleRunner(service) + + runner.registerJob(onceJob) + + expect(mockCronInstances).toHaveLength(1) + expect(mockCronInstances[0]?.pattern).toBeInstanceOf(Date) + expect((mockCronInstances[0]?.pattern as Date).getTime()).toBe(futureRunAt) + expect(mockCronInstances[0]?.options).toEqual({ protect: true }) + }) + + it('runs a past once job immediately without registering a cron', async () => { + const onceJob: ScheduleJob = { + ...job, + scheduleMode: 'once', + intervalMinutes: null, + runAt: '2026-03-09T13:00', + nextRunAt: Date.now() - 60_000, + } + const service = makeService(createStubScheduleApi().api) + const runSpy = vi.spyOn(service, 'runJobForJob').mockResolvedValue(baseRun) + const runner = new ScheduleRunner(service) + + runner.registerJob(onceJob) + + await vi.waitFor(() => expect(runSpy).toHaveBeenCalledWith(onceJob, 'schedule')) + expect(mockCronInstances).toHaveLength(0) + }) + + it('skips a disabled once job', () => { + const onceJob: ScheduleJob = { + ...job, + enabled: false, + scheduleMode: 'once', + intervalMinutes: null, + runAt: '2026-03-09T13:00', + nextRunAt: Date.now() + 3_600_000, + } + const service = makeService(createStubScheduleApi().api) + const runSpy = vi.spyOn(service, 'runJobForJob').mockResolvedValue(baseRun) + const runner = new ScheduleRunner(service) + + runner.registerJob(onceJob) + + expect(mockCronInstances).toHaveLength(0) + expect(runSpy).not.toHaveBeenCalled() + }) }) describe('ScheduleService run history cleanup', () => { diff --git a/frontend/src/components/schedules/ScheduleJobDialog.once.test.tsx b/frontend/src/components/schedules/ScheduleJobDialog.once.test.tsx new file mode 100644 index 00000000..7425033a --- /dev/null +++ b/frontend/src/components/schedules/ScheduleJobDialog.once.test.tsx @@ -0,0 +1,168 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import type { ScheduleJob } from '@opencode-manager/shared/types' +import { ScheduleJobDialog } from './ScheduleJobDialog' +import { useSettings } from '@/hooks/useSettings' +import { useServerHealth } from '@/hooks/useServerHealth' +import { createUseSettingsMock } from '@/test/test-utils' + +Element.prototype.scrollIntoView = vi.fn() + +vi.mock('@/hooks/useSettings') +vi.mock('@/hooks/useServerHealth') + +vi.mock('@/hooks/usePromptTemplates', () => ({ + usePromptTemplates: () => ({ data: [], isLoading: false }), + useCreatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }), + useUpdatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }), + useDeletePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }), +})) + +vi.mock('@/hooks/useScheduleTarget', () => ({ + useScheduleTarget: () => ({ scheduleTarget: undefined, isLoading: false, isError: false }), +})) + +vi.mock('@/hooks/useScheduleModels', () => ({ + useScheduleModels: () => ({ availableModels: null, isLoading: false }), +})) + +vi.mock('@/hooks/useOpenCode', () => ({ + useAgents: () => ({ data: [], isSuccess: true }), +})) + +vi.mock('@/api/settings', () => ({ + settingsApi: { + listManagedSkills: () => Promise.resolve([]), + }, +})) + +vi.mock('@/api/mcp', () => ({ + mcpApi: { + getStatus: () => Promise.resolve({}), + }, +})) + +vi.mock('@/api/repos', () => ({ + listRepos: () => Promise.resolve([]), + listBranches: () => Promise.resolve({ branches: [], status: { ahead: 0, behind: 0 } }), +})) + +function mockSandboxPreferences() { + vi.mocked(useSettings).mockReturnValue( + createUseSettingsMock({ preferences: { sandbox: { enabled: true } } }), + ) +} + +function mockSandboxHealth() { + vi.mocked(useServerHealth).mockReturnValue({ + data: { sandbox: { available: true, enabled: true, enforced: false } }, + isLoading: false, + error: null, + refetch: vi.fn(), + } as unknown as ReturnType) +} + +function createWrapper() { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }) + return ({ children }: { children: React.ReactNode }) => ( + {children} + ) +} + +function getJob(overrides?: Partial): ScheduleJob { + return { + id: 1, + repoId: 1, + name: 'Nightly health check', + description: null, + enabled: true, + showInInbox: true, + scheduleMode: 'interval', + intervalMinutes: 60, + cronExpression: null, + runAt: null, + timezone: null, + agentSlug: null, + prompt: 'Check the repo.', + model: null, + skillMetadata: null, + permissionConfig: null, + mcpServers: [], + branch: null, + workspaceMode: 'worktree', + sandbox: null, + createdAt: 0, + updatedAt: 0, + lastRunAt: null, + nextRunAt: null, + ...overrides, + } +} + +describe('ScheduleJobDialog — once', () => { + beforeEach(() => { + vi.clearAllMocks() + mockSandboxPreferences() + mockSandboxHealth() + }) + + it('saves a Once schedule', async () => { + const onSubmit = vi.fn() + const user = userEvent.setup() + + render( + , + { wrapper: createWrapper() }, + ) + + await user.type(screen.getByLabelText('Name'), 'Nightly health check') + await user.click(screen.getByRole('tab', { name: 'Prompt' })) + await user.type(screen.getByRole('textbox', { name: 'Prompt' }), 'Check the repo.') + await user.click(screen.getByRole('tab', { name: 'Timing' })) + await user.click(screen.getByRole('button', { name: 'Once' })) + + fireEvent.change(screen.getByLabelText('Date and time'), { target: { value: '2026-11-08T09:00' } }) + fireEvent.change(screen.getByLabelText('Timezone'), { target: { value: 'Europe/Berlin' } }) + + await user.click(screen.getByRole('button', { name: 'Create schedule' })) + + await waitFor(() => { + expect(onSubmit).toHaveBeenCalledTimes(1) + }) + + expect(onSubmit).toHaveBeenCalledWith( + expect.objectContaining({ + scheduleMode: 'once', + runAt: '2026-11-08T09:00', + timezone: 'Europe/Berlin', + }), + ) + }) + + it("shows an existing Once schedule's values", async () => { + const user = userEvent.setup() + + render( + , + { wrapper: createWrapper() }, + ) + + await user.click(screen.getByRole('tab', { name: 'Timing' })) + + expect(await screen.findByLabelText('Date and time')).toHaveValue('2026-11-08T09:00') + expect(screen.getByLabelText('Timezone')).toHaveValue('Europe/Berlin') + }) +}) diff --git a/frontend/src/components/schedules/ScheduleJobDialog.tsx b/frontend/src/components/schedules/ScheduleJobDialog.tsx index f7702165..72b97b06 100644 --- a/frontend/src/components/schedules/ScheduleJobDialog.tsx +++ b/frontend/src/components/schedules/ScheduleJobDialog.tsx @@ -17,6 +17,7 @@ import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs' import { buildCronExpressionFromPreset, detectSchedulePreset, + getDefaultOnceRunAt, getLocalTimeZone, type SchedulePreset, } from '@/components/schedules/schedule-utils' @@ -64,6 +65,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, const [weeklyDays, setWeeklyDays] = useState(['1']) const [monthlyDay, setMonthlyDay] = useState('1') const [cronExpression, setCronExpression] = useState('0 9 * * 1-5') + const [runAt, setRunAt] = useState(getDefaultOnceRunAt()) const [timezone, setTimezone] = useState(getLocalTimeZone()) const [agentSlug, setAgentSlug] = useState('') const [model, setModel] = useState('') @@ -183,6 +185,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, setWeeklyDays(scheduleDefaults.weeklyDays) setMonthlyDay(scheduleDefaults.monthlyDay) setCronExpression(scheduleDefaults.cronExpression) + setRunAt(scheduleDefaults.runAt) setTimezone(scheduleDefaults.timezone) setAgentSlug(job?.agentSlug ?? '') setModel(job?.model ?? '') @@ -275,6 +278,16 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, } : {}), } + if (schedulePreset === 'once') { + onSubmit({ + ...baseFields, + scheduleMode: 'once', + runAt, + timezone: timezone.trim() || 'UTC', + }) + return + } + if (schedulePreset !== 'interval') { onSubmit({ ...baseFields, @@ -295,6 +308,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, const isScheduleConfigInvalid = (schedulePreset === 'advanced' && (!cronExpression.trim() || !timezone.trim())) || ((schedulePreset === 'daily' || schedulePreset === 'weekdays' || schedulePreset === 'weekly' || schedulePreset === 'monthly') && !timezone.trim()) || + (schedulePreset === 'once' && (!runAt || !timezone.trim())) || (schedulePreset === 'weekly' && weeklyDays.length === 0) const missingRequirements = [ @@ -393,6 +407,8 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, onMonthlyDayChange={setMonthlyDay} cronExpression={cronExpression} onCronExpressionChange={setCronExpression} + runAt={runAt} + onRunAtChange={setRunAt} timezone={timezone} onTimezoneChange={setTimezone} /> diff --git a/frontend/src/components/schedules/TimingTab.tsx b/frontend/src/components/schedules/TimingTab.tsx index 741b0f09..74e13c73 100644 --- a/frontend/src/components/schedules/TimingTab.tsx +++ b/frontend/src/components/schedules/TimingTab.tsx @@ -27,6 +27,8 @@ type TimingTabProps = { onMonthlyDayChange: (value: string) => void cronExpression: string onCronExpressionChange: (value: string) => void + runAt: string + onRunAtChange: (value: string) => void timezone: string onTimezoneChange: (value: string) => void } @@ -46,6 +48,8 @@ export function TimingTab({ onMonthlyDayChange, cronExpression, onCronExpressionChange, + runAt, + onRunAtChange, timezone, onTimezoneChange, }: TimingTabProps) { @@ -122,6 +126,17 @@ export function TimingTab({ onTimezoneChange(event.target.value)} placeholder={getLocalTimeZone()} /> + ) : schedulePreset === 'once' ? ( +
+
+ + onRunAtChange(event.target.value)} /> +
+
+ + onTimezoneChange(event.target.value)} placeholder={getLocalTimeZone()} /> +
+
) : schedulePreset === 'weekly' ? (
@@ -216,8 +231,8 @@ export function TimingTab({

Schedule Preview

-

{formatDraftScheduleSummary({ preset: schedulePreset, intervalMinutes, timeOfDay, hourlyMinute, weeklyDays, monthlyDay, cronExpression, timezone })}

- {schedulePreset !== 'interval' && ( +

{formatDraftScheduleSummary({ preset: schedulePreset, intervalMinutes, timeOfDay, hourlyMinute, weeklyDays, monthlyDay, cronExpression, runAt, timezone })}

+ {schedulePreset !== 'interval' && schedulePreset !== 'once' && (

{buildCronExpressionFromPreset({ preset: schedulePreset, intervalMinutes, timeOfDay, hourlyMinute, weeklyDays, monthlyDay, cronExpression })}

diff --git a/frontend/src/components/schedules/__tests__/schedule-utils.test.ts b/frontend/src/components/schedules/__tests__/schedule-utils.test.ts index 6a5baf83..8de77228 100644 --- a/frontend/src/components/schedules/__tests__/schedule-utils.test.ts +++ b/frontend/src/components/schedules/__tests__/schedule-utils.test.ts @@ -1,6 +1,47 @@ import { describe, expect, it } from 'vitest' -import { formatRunDuration, formatScheduleInbox, matchesScheduleJobSearch } from '@/components/schedules/schedule-utils' -import type { ScheduleJob } from '@opencode-manager/shared/types' +import { + detectSchedulePreset, + formatDraftScheduleSummary, + formatOnceRunAt, + formatRunDuration, + formatScheduleInbox, + formatScheduleShortLabel, + formatScheduleSummary, + getDefaultOnceRunAt, + matchesScheduleJobSearch, + toUpdateScheduleRequest, +} from '@/components/schedules/schedule-utils' +import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types' + +function createJob(overrides?: Partial): ScheduleJob { + return { + id: 1, + repoId: 1, + name: 'Nightly health check', + description: null, + enabled: true, + showInInbox: true, + scheduleMode: 'interval', + intervalMinutes: 60, + cronExpression: null, + runAt: null, + timezone: null, + agentSlug: null, + prompt: 'Check the repo.', + model: null, + skillMetadata: null, + permissionConfig: null, + mcpServers: [], + branch: null, + workspaceMode: 'worktree', + sandbox: null, + createdAt: 0, + updatedAt: 0, + lastRunAt: null, + nextRunAt: null, + ...overrides, + } +} describe('formatRunDuration', () => { it('formats seconds, minutes, and hours', () => { @@ -35,3 +76,101 @@ describe('matchesScheduleJobSearch', () => { expect(matchesScheduleJobSearch(job, ' ')).toBe(true) }) }) + +describe('getDefaultOnceRunAt', () => { + it('returns tomorrow at 09:00 from local date parts', () => { + expect(getDefaultOnceRunAt(new Date(2026, 0, 15, 23, 30))).toBe('2026-01-16T09:00') + }) +}) + +describe('detectSchedulePreset', () => { + it('returns once with the job run time and timezone', () => { + const result = detectSchedulePreset(createJob({ scheduleMode: 'once', runAt: '2026-11-08T09:00', timezone: 'Europe/Berlin' })) + + expect(result.preset).toBe('once') + expect(result.runAt).toBe('2026-11-08T09:00') + expect(result.timezone).toBe('Europe/Berlin') + }) + + it('returns a default once run time for a non-once job', () => { + const result = detectSchedulePreset(createJob({ scheduleMode: 'interval' })) + + expect(result.preset).not.toBe('once') + expect(result.runAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/) + }) +}) + +describe('once schedule labels', () => { + const job = createJob({ scheduleMode: 'once', runAt: '2026-11-08T09:00', timezone: 'Europe/Berlin' }) + + it('summarizes a once job with its timezone', () => { + expect(formatScheduleSummary(job)).toBe(`Once · ${formatOnceRunAt('2026-11-08T09:00')} - Europe/Berlin`) + }) + + it('labels a once job without its timezone', () => { + expect(formatScheduleShortLabel(job)).toBe(`Once · ${formatOnceRunAt('2026-11-08T09:00')}`) + }) + + it('previews a once draft as turning off after the run', () => { + expect(formatDraftScheduleSummary({ + preset: 'once', + intervalMinutes: '', + timeOfDay: '', + hourlyMinute: '', + weeklyDays: [], + monthlyDay: '', + cronExpression: '', + runAt: '2026-11-08T09:00', + timezone: 'Europe/Berlin', + })).toBe(`Runs once on ${formatOnceRunAt('2026-11-08T09:00')} - Europe/Berlin, then turns off.`) + }) +}) + +describe('toUpdateScheduleRequest', () => { + it('keeps the once run time and clears interval and cron', () => { + const request = { + name: 'Once job', + prompt: 'Check the repo.', + scheduleMode: 'once', + runAt: '2026-11-08T09:00', + timezone: 'Europe/Berlin', + } as CreateScheduleJobRequest + + const result = toUpdateScheduleRequest(request) + + expect(result.intervalMinutes).toBeNull() + expect(result.cronExpression).toBeNull() + expect(result.runAt).toBe('2026-11-08T09:00') + expect(result.timezone).toBe('Europe/Berlin') + }) + + it('clears the once run time and interval for a cron request', () => { + const request = { + name: 'Cron job', + prompt: 'Check the repo.', + scheduleMode: 'cron', + cronExpression: '0 9 * * *', + timezone: 'UTC', + } as CreateScheduleJobRequest + + const result = toUpdateScheduleRequest(request) + + expect(result.intervalMinutes).toBeNull() + expect(result.runAt).toBeNull() + }) + + it('clears cron, timezone, and the once run time for an interval request', () => { + const request = { + name: 'Interval job', + prompt: 'Check the repo.', + scheduleMode: 'interval', + intervalMinutes: 60, + } as CreateScheduleJobRequest + + const result = toUpdateScheduleRequest(request) + + expect(result.cronExpression).toBeNull() + expect(result.timezone).toBeNull() + expect(result.runAt).toBeNull() + }) +}) diff --git a/frontend/src/components/schedules/schedule-utils.ts b/frontend/src/components/schedules/schedule-utils.ts index aa92d251..cb016220 100644 --- a/frontend/src/components/schedules/schedule-utils.ts +++ b/frontend/src/components/schedules/schedule-utils.ts @@ -27,6 +27,7 @@ export const schedulePresetOptions = [ { label: 'Weekdays', value: 'weekdays' }, { label: 'Weekly', value: 'weekly' }, { label: 'Monthly', value: 'monthly' }, + { label: 'Once', value: 'once' }, { label: 'Advanced', value: 'advanced' }, ] as const @@ -92,6 +93,29 @@ export function getLocalTimeZone(): string { } } +export function getDefaultOnceRunAt(now: Date = new Date()): string { + const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1) + + return `${tomorrow.getFullYear()}-${String(tomorrow.getMonth() + 1).padStart(2, '0')}-${String(tomorrow.getDate()).padStart(2, '0')}T09:00` +} + +const ONCE_RUN_AT_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/ + +export function formatOnceRunAt(runAt: string): string { + const match = runAt.match(ONCE_RUN_AT_PATTERN) + if (!match) { + return runAt + } + + const [, year, month, day, hour, minute] = match + + return new Intl.DateTimeFormat(undefined, { + dateStyle: 'medium', + timeStyle: 'short', + timeZone: 'UTC', + }).format(Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute))) +} + function isNumericToken(value: string): boolean { return /^\d+$/.test(value) } @@ -164,6 +188,7 @@ export function detectSchedulePreset(job?: ScheduleJob): { weeklyDays: string[] monthlyDay: string cronExpression: string + runAt: string timezone: string } { const defaultTimezone = job?.timezone ?? getLocalTimeZone() @@ -175,9 +200,19 @@ export function detectSchedulePreset(job?: ScheduleJob): { weeklyDays: ['1'], monthlyDay: '1', cronExpression: job?.cronExpression ?? '0 9 * * 1-5', + runAt: getDefaultOnceRunAt(), timezone: defaultTimezone, } + if (job?.scheduleMode === 'once') { + return { + ...defaults, + preset: 'once', + runAt: job.runAt ?? defaults.runAt, + timezone: job.timezone ?? getLocalTimeZone(), + } + } + if (!job || job.scheduleMode === 'interval') { return defaults } @@ -299,6 +334,10 @@ export function formatCronHumanText(cronExpression: string | null): string | nul } export function formatScheduleSummary(job: ScheduleJob): string { + if (job.scheduleMode === 'once') { + return `Once · ${formatOnceRunAt(job.runAt ?? '')}${job.timezone ? ` - ${job.timezone}` : ''}` + } + if (job.scheduleMode === 'cron') { return `${formatCronHumanText(job.cronExpression) ?? (job.cronExpression ?? 'Custom cron')}${job.timezone ? ` - ${job.timezone}` : ''}` } @@ -307,6 +346,10 @@ export function formatScheduleSummary(job: ScheduleJob): string { } export function formatScheduleShortLabel(job: ScheduleJob): string { + if (job.scheduleMode === 'once') { + return `Once · ${formatOnceRunAt(job.runAt ?? '')}` + } + if (job.scheduleMode === 'cron') { return formatCronHumanText(job.cronExpression) ?? 'Custom cron' } @@ -322,8 +365,13 @@ export function formatDraftScheduleSummary(input: { weeklyDays: string[] monthlyDay: string cronExpression: string + runAt: string timezone: string }): string { + if (input.preset === 'once') { + return input.runAt.trim() ? `Runs once on ${formatOnceRunAt(input.runAt)} - ${input.timezone.trim() || 'UTC'}, then turns off.` : 'Choose a date and time' + } + if (input.preset === 'interval') { const parsedInterval = Number.parseInt(input.intervalMinutes, 10) return formatIntervalLabel(Number.isNaN(parsedInterval) ? null : parsedInterval) @@ -345,6 +393,18 @@ export function toUpdateScheduleRequest(data: CreateScheduleJobRequest): UpdateS agentSlug: data.agentSlug ?? null, model: data.model ?? null, intervalMinutes: null, + runAt: null, + } + } + + if (data.scheduleMode === 'once') { + return { + ...data, + description: data.description ?? null, + agentSlug: data.agentSlug ?? null, + model: data.model ?? null, + intervalMinutes: null, + cronExpression: null, } } @@ -354,6 +414,7 @@ export function toUpdateScheduleRequest(data: CreateScheduleJobRequest): UpdateS agentSlug: data.agentSlug ?? null, model: data.model ?? null, cronExpression: null, + runAt: null, timezone: null, } } diff --git a/frontend/src/pages/GlobalSchedules.tsx b/frontend/src/pages/GlobalSchedules.tsx index 02f26a4e..7a368acf 100644 --- a/frontend/src/pages/GlobalSchedules.tsx +++ b/frontend/src/pages/GlobalSchedules.tsx @@ -32,7 +32,7 @@ import { Combobox } from '@/components/ui/combobox' import { getRepoPath, getServerProjectPath } from '@/lib/navigation' type StatusFilter = 'all' | 'enabled' | 'disabled' -type ScheduleModeFilter = 'all' | 'cron' | 'interval' +type ScheduleModeFilter = 'all' | 'cron' | 'interval' | 'once' type SortOption = 'nextRun' | 'name' | 'repo' function jobBucket(job: ScheduleJobWithRepo): string { @@ -201,9 +201,7 @@ export function GlobalSchedules() { } if (scheduleModeFilter !== 'all') { - filtered = filtered.filter((job) => - scheduleModeFilter === 'cron' ? job.scheduleMode === 'cron' : job.scheduleMode === 'interval' - ) + filtered = filtered.filter((job) => job.scheduleMode === scheduleModeFilter) } if (repoFilter !== 'all') { @@ -249,6 +247,7 @@ export function GlobalSchedules() { { value: 'all', label: 'All Modes' }, { value: 'cron', label: 'Cron' }, { value: 'interval', label: 'Interval' }, + { value: 'once', label: 'Once' }, ], []) const sortOptions = useMemo(() => [ diff --git a/shared/src/schemas/schedule.ts b/shared/src/schemas/schedule.ts index 1a1d8c91..94fe935a 100644 --- a/shared/src/schemas/schedule.ts +++ b/shared/src/schemas/schedule.ts @@ -7,9 +7,14 @@ export type ScheduleRunTriggerSource = z.infer -export const ScheduleModeSchema = z.enum(['interval', 'cron']) +export const ScheduleModeSchema = z.enum(['interval', 'cron', 'once']) export type ScheduleMode = z.infer +/** + * A wall-clock date and time read in the schedule's `timezone`. + */ +export const ScheduleRunAtSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/, 'Use YYYY-MM-DDTHH:mm') + /** * Where a scheduled run executes. `worktree` gives every run a fresh worktree that is * removed when the run ends, `kept-worktree` keeps each run's worktree afterwards, and @@ -199,6 +204,7 @@ export const ScheduleJobSchema = z.object({ scheduleMode: ScheduleModeSchema, intervalMinutes: z.number().int().min(5).max(10080).nullable(), cronExpression: z.string().nullable(), + runAt: z.string().nullable(), timezone: z.string().nullable(), agentSlug: z.string().nullable(), prompt: z.string(), @@ -270,6 +276,11 @@ export const CreateScheduleJobRequestSchema = z.discriminatedUnion('scheduleMode cronExpression: z.string().min(1).max(200), timezone: z.string().min(1).max(120), }), + ScheduleJobBaseRequestSchema.extend({ + scheduleMode: z.literal('once'), + runAt: ScheduleRunAtSchema, + timezone: z.string().min(1).max(120), + }), ]) export type CreateScheduleJobRequest = z.infer @@ -286,6 +297,7 @@ export const UpdateScheduleJobRequestSchema = z.object({ scheduleMode: ScheduleModeSchema.optional(), intervalMinutes: z.number().int().min(5).max(10080).nullable().optional(), cronExpression: z.string().min(1).max(200).nullable().optional(), + runAt: ScheduleRunAtSchema.nullable().optional(), timezone: z.string().min(1).max(120).nullable().optional(), agentSlug: z.string().min(1).max(100).nullable().optional(), prompt: z.string().min(1).max(20000).optional(),