Scheduler: edit, Run now, cron with a preview, and a schedule's runs (#19)
CI / Lint (eslint) (pull_request) Successful in 27s
CI / Test (jest) (pull_request) Successful in 26s
CI / Security (npm audit) (pull_request) Successful in 10s
CI / Scan (secrets, workflows, shell) (pull_request) Failing after 2m45s
CI / Integration (api) (pull_request) Successful in 3m37s
CI / UI (playwright) (pull_request) Successful in 2m51s
CI / Deploy (pull_request) Skipped
CI / Deploy worker (pull_request) Skipped
CI / Notify (pull_request) Skipped
CI / UI screenshots (before/after) (pull_request) Successful in 2m35s

- Edit: PUT /api/scheduled-commands/:id changes a schedule in place
  (keeping its history) and works out its next run again. The create
  dialog doubles as the edit dialog.
- Run now: POST /api/scheduled-commands/:id/run dispatches at once,
  records triggered_by, leaves next_run alone, and answers 409 while a
  previous run is still going. The dispatch body moved out of the
  scheduler loop into dispatchSchedule() so both share it.
- Cron is offered in the dialog, and a preview shows the next three runs
  and the server time zone they are worked out in
  (GET /api/scheduled-commands/preview). Errors stay in the dialog.
- Runs links to /executions?view=automated&search=scheduler:<name>;
  Executions now honours ?view= and ?search=.
- Create and edit share scheduleInput(), which also checks daily HH:MM.
- The dialog's worker list had no styles on this page (it borrows Quick
  Command's markup); they are now included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-23 19:17:48 -05:00
1 parent 777ab728c0
commit 966c2be5cc
10 files changed
+453 -97

No files matched your search

+127 -82
View File
@@ -10,7 +10,7 @@ const fs = require('fs');
const helmet = require('helmet');
require('dotenv').config();
const { validateWebhookUrl, applyParams, evalCondition, conditionErrors, gotoErrors, calculateNextRun,
definitionErrors, resolveParams } = require('./lib/utils');
definitionErrors, resolveParams, nextRuns, scheduleInput } = require('./lib/utils');
const { PAGES } = require('./lib/nav');
const { renderPage, renderError } = require('./lib/render');
const { upsertUser, makeAuthenticatePage, ssoIdentity, trustedProxies, ALLOWED_GROUPS } = require('./lib/pageauth');
@@ -307,6 +307,76 @@ if (!DEV_READONLY) {
}
// Scheduled Commands Processor
/**
* Send a schedule's command to each of its workers, recording a failed run for any
* that is offline (#9). Used by the scheduler loop and by Run now (#19, triggeredBy).
*/
async function dispatchSchedule(schedule, triggeredBy) {
// Handle both string (raw SQL) and object (auto-parsed by MySQL2 JSON column)
let workerIds;
try {
workerIds = typeof schedule.worker_ids === 'string'
? JSON.parse(schedule.worker_ids)
: schedule.worker_ids;
} catch {
console.error(`[Scheduler] Invalid worker_ids JSON for "${schedule.name}": skipping`);
return { sent: 0, offline: 0 };
}
let sent = 0;
let offline = 0;
// Execute command on each worker
for (const workerId of workerIds) {
const workerWs = workers.get(workerId);
if (workerWs && workerWs.readyState === WebSocket.OPEN) {
const executionId = crypto.randomUUID();
// Create execution record
await pool.query(
'INSERT INTO executions (id, workflow_id, status, started_by, started_at, logs) VALUES (?, ?, ?, ?, NOW(), ?)',
[executionId, null, 'running', `scheduler:${schedule.name}`, JSON.stringify([{
step: 'scheduled_command',
action: 'command_sent',
worker_id: workerId,
command: schedule.command,
...(triggeredBy ? { triggered_by: triggeredBy } : {}),
timestamp: new Date().toISOString()
}])]
);
// Send command to worker
sendCommandToWorker(workerWs, {
type: 'execute_command',
execution_id: executionId,
command: schedule.command,
worker_id: workerId,
timeout: 5 * 60_000 // SCHEDULED_CMD_TIMEOUT
});
broadcast({ type: 'execution_started', execution_id: executionId, workflow_id: null });
sent++;
} else {
offline++;
// The worker isn't connected: record a failed run with the reason rather than
// skipping silently, so a missed schedule shows up in Executions (#9).
const executionId = crypto.randomUUID();
const timestamp = new Date().toISOString();
await pool.query(
'INSERT INTO executions (id, workflow_id, status, started_by, started_at, completed_at, logs) VALUES (?, ?, ?, ?, NOW(), NOW(), ?)',
[executionId, null, 'failed', `scheduler:${schedule.name}`, JSON.stringify([
{ step: 'scheduled_command', action: 'command_sent', worker_id: workerId, command: schedule.command, timestamp },
{ step: 'command_execution', action: 'command_result', worker_id: workerId, success: false,
error: 'Worker offline: the scheduled command was not sent', stdout: '', stderr: '', timestamp }
])]
);
console.warn(`[Scheduler] "${schedule.name}": worker ${workerId} is offline; recorded a failed run`);
broadcast({ type: 'execution_started', execution_id: executionId, workflow_id: null });
broadcast({ type: 'execution_status', execution_id: executionId, status: 'failed' });
}
}
return { sent, offline };
}
async function processScheduledCommands() {
try {
const [schedules] = await pool.query(
@@ -340,64 +410,7 @@ async function processScheduledCommands() {
}
console.log(`[Scheduler] Running scheduled command: ${schedule.name}`);
// Handle both string (raw SQL) and object (auto-parsed by MySQL2 JSON column)
let workerIds;
try {
workerIds = typeof schedule.worker_ids === 'string'
? JSON.parse(schedule.worker_ids)
: schedule.worker_ids;
} catch {
console.error(`[Scheduler] Invalid worker_ids JSON for "${schedule.name}": skipping`);
continue;
}
// Execute command on each worker
for (const workerId of workerIds) {
const workerWs = workers.get(workerId);
if (workerWs && workerWs.readyState === WebSocket.OPEN) {
const executionId = crypto.randomUUID();
// Create execution record
await pool.query(
'INSERT INTO executions (id, workflow_id, status, started_by, started_at, logs) VALUES (?, ?, ?, ?, NOW(), ?)',
[executionId, null, 'running', `scheduler:${schedule.name}`, JSON.stringify([{
step: 'scheduled_command',
action: 'command_sent',
worker_id: workerId,
command: schedule.command,
timestamp: new Date().toISOString()
}])]
);
// Send command to worker
sendCommandToWorker(workerWs, {
type: 'execute_command',
execution_id: executionId,
command: schedule.command,
worker_id: workerId,
timeout: 5 * 60_000 // SCHEDULED_CMD_TIMEOUT
});
broadcast({ type: 'execution_started', execution_id: executionId, workflow_id: null });
} else {
// The worker isn't connected: record a failed run with the reason rather than
// skipping silently, so a missed schedule shows up in Executions (#9).
const executionId = crypto.randomUUID();
const timestamp = new Date().toISOString();
await pool.query(
'INSERT INTO executions (id, workflow_id, status, started_by, started_at, completed_at, logs) VALUES (?, ?, ?, ?, NOW(), NOW(), ?)',
[executionId, null, 'failed', `scheduler:${schedule.name}`, JSON.stringify([
{ step: 'scheduled_command', action: 'command_sent', worker_id: workerId, command: schedule.command, timestamp },
{ step: 'command_execution', action: 'command_result', worker_id: workerId, success: false,
error: 'Worker offline: the scheduled command was not sent', stdout: '', stderr: '', timestamp }
])]
);
console.warn(`[Scheduler] "${schedule.name}": worker ${workerId} is offline; recorded a failed run`);
broadcast({ type: 'execution_started', execution_id: executionId, workflow_id: null });
broadcast({ type: 'execution_status', execution_id: executionId, status: 'failed' });
}
}
await dispatchSchedule(schedule);
// next_run and last_run already updated atomically above when we claimed the slot
}
@@ -1903,44 +1916,76 @@ app.get('/api/scheduled-commands', authenticateSSO, async (req, res) => {
}
});
app.get('/api/scheduled-commands/preview', authenticateSSO, (req, res) => {
// The next few runs for the editor, and the time zone they are worked out in.
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
try {
const runs = nextRuns(String(req.query.type || ''), String(req.query.value || ''), 3);
res.json({ next: runs.map(d => d.toISOString()), timezone });
} catch (e) {
res.status(400).json({ error: `Invalid schedule: ${e.message}`, timezone });
}
});
app.post('/api/scheduled-commands', authenticateSSO, requireJSON, async (req, res) => {
try {
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin access required' });
const { name, command, worker_ids, schedule_type, schedule_value } = req.body;
if (!name || !command || !worker_ids || !schedule_type || !schedule_value) {
return res.status(400).json({ error: 'Missing required fields' });
}
// Validate schedule_value for numeric types
if (schedule_type === 'interval' || schedule_type === 'hourly') {
const n = parseInt(schedule_value, 10);
if (!Number.isInteger(n) || n <= 0) {
return res.status(400).json({ error: `schedule_value for type "${schedule_type}" must be a positive integer` });
}
}
let nextRun;
try {
nextRun = calculateNextRun(schedule_type, schedule_value);
} catch (e) {
return res.status(400).json({ error: `Invalid schedule: ${e.message}` });
}
const checked = scheduleInput(req.body);
if (checked.error) return res.status(400).json({ error: checked.error });
const v = checked.value;
const id = crypto.randomUUID();
await pool.query(
`INSERT INTO scheduled_commands
(id, name, command, worker_ids, schedule_type, schedule_value, created_by, next_run)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
[id, name, command, JSON.stringify(worker_ids), schedule_type, schedule_value, req.user.username, nextRun]
[id, v.name, v.command, JSON.stringify(v.worker_ids), v.schedule_type, v.schedule_value, req.user.username, v.next_run]
);
res.json({ success: true, id });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
// Edit a schedule in place, keeping its history (#19). The next run is worked out afresh.
app.put('/api/scheduled-commands/:id', authenticateSSO, requireJSON, async (req, res) => {
try {
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin access required' });
const checked = scheduleInput(req.body);
if (checked.error) return res.status(400).json({ error: checked.error });
const v = checked.value;
const [result] = await pool.query(
`UPDATE scheduled_commands SET name = ?, command = ?, worker_ids = ?, schedule_type = ?, schedule_value = ?, next_run = ?
WHERE id = ?`,
[v.name, v.command, JSON.stringify(v.worker_ids), v.schedule_type, v.schedule_value, v.next_run, req.params.id]
);
if (result.affectedRows === 0) return res.status(404).json({ error: 'Schedule not found' });
res.json({ success: true, next_run: v.next_run });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
// Run a schedule now, without changing when it next runs on its own (#19).
app.post('/api/scheduled-commands/:id/run', authenticateSSO, async (req, res) => {
try {
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin access required' });
const [rows] = await pool.query('SELECT * FROM scheduled_commands WHERE id = ?', [req.params.id]);
if (rows.length === 0) return res.status(404).json({ error: 'Schedule not found' });
const schedule = rows[0];
const [running] = await pool.query(
"SELECT id FROM executions WHERE started_by = ? AND status = 'running' LIMIT 1",
[`scheduler:${schedule.name}`]
);
if (running.length) return res.status(409).json({ error: 'A run of this schedule is still in progress' });
const result = await dispatchSchedule(schedule, req.user.username);
await pool.query('UPDATE scheduled_commands SET last_run = NOW() WHERE id = ?', [schedule.id]);
console.log(`[Scheduler] "${schedule.name}" run now by ${req.user.username}: ${result.sent} sent, ${result.offline} offline`);
res.json({ success: true, ...result });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
app.put('/api/scheduled-commands/:id/toggle', authenticateSSO, async (req, res) => {
try {
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin access required' });