Files
pulse/public/assets/pages/scheduler.js
T
jaredandClaude Opus 5.5 966c2be5cc
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
Scheduler: edit, Run now, cron with a preview, and a schedule's runs (#19)
- 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>
2026-11-23 19:17:48 -05:00

383 lines
16 KiB
JavaScript

/* =====================================================================
PULSE: Scheduler page (WP-F)
Owns DOM id prefix `sc-` and action namespace `sc:*`.
===================================================================== */
'use strict';
(function () {
const esc = Pulse.esc;
const fmt = Pulse.fmt;
let _schedules = [];
let _workers = [];
let _editingId = null; // set while the dialog edits an existing schedule (#19)
let _previewTimer = null;
/* -------------------------------------------------------------------
Helpers
------------------------------------------------------------------- */
function parseWorkerIds(raw) {
if (Array.isArray(raw)) return raw;
if (typeof raw === 'string') {
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : raw.split(',').filter(Boolean);
} catch (e) {
return raw.split(',').filter(Boolean);
}
}
return [];
}
function scheduleDescription(s) {
if (s.schedule_type === 'interval') return 'Every ' + esc(s.schedule_value) + ' minutes';
if (s.schedule_type === 'hourly') return 'Every ' + esc(s.schedule_value) + ' hour(s)';
if (s.schedule_type === 'daily') return 'Daily at ' + esc(s.schedule_value);
if (s.schedule_type === 'cron') return 'Cron: ' + esc(s.schedule_value);
return esc(s.schedule_value || '');
}
function workerNamesHtml(ids) {
if (!ids.length) return '<span class="lt-text-dim">-</span>';
return ids.map(id => {
const w = _workers.find(worker => worker.id === id);
const label = w ? w.name : String(id).slice(0, 8);
return '<span class="lt-badge">' + esc(label) + '</span>';
}).join(' ');
}
function nextRunCountdown(nextRun) {
const d = fmt.safeDate(nextRun);
if (!d) return '';
const secs = Math.round((d.getTime() - Date.now()) / 1000);
if (secs <= 0) return 'now';
if (secs < 60) return secs + 's';
if (secs < 3600) return Math.round(secs / 60) + 'm';
return Math.round(secs / 3600) + 'h';
}
/* -------------------------------------------------------------------
Table rendering
------------------------------------------------------------------- */
function rowHtml(s) {
const workerIds = parseWorkerIds(s.worker_ids);
const lastRun = s.last_run ? esc(fmt.dateTime(s.last_run)) : 'Never';
const nextRunDate = fmt.safeDate(s.next_run);
const countdown = nextRunCountdown(s.next_run);
const nextRun = nextRunDate
? esc(fmt.dateTime(s.next_run)) + (countdown ? ' <span class="sc-countdown" data-next-run="' + esc(s.next_run) + '">(in ' + esc(countdown) + ')</span>' : '')
: 'Not scheduled';
const statusBadge = s.enabled
? '<span class="lt-badge lt-badge-green">ENABLED</span>'
: '<span class="lt-badge lt-badge-red">DISABLED</span>';
const runsHref = '/executions?view=automated&search=' + encodeURIComponent('scheduler:' + (s.name || ''));
const adminActions = Pulse.isAdmin
? '<div class="lt-btn-group">' +
'<button type="button" class="lt-btn lt-btn-primary lt-btn-sm" data-action="sc:run" data-id="' + esc(s.id) + '" data-name="' + esc(s.name || '') + '">&#x25b6; Run now</button>' +
'<button type="button" class="lt-btn lt-btn-secondary lt-btn-sm" data-action="sc:edit" data-id="' + esc(s.id) + '">&#x270e; Edit</button>' +
'<button type="button" class="lt-btn lt-btn-secondary lt-btn-sm" data-action="sc:toggle" data-id="' + esc(s.id) + '" data-enabled="' + (s.enabled ? '1' : '0') + '">' +
(s.enabled ? '&#x23f8; Disable' : '&#x25b6; Enable') +
'</button>' +
'<button type="button" class="lt-btn lt-btn-danger lt-btn-sm" data-action="sc:delete" data-id="' + esc(s.id) + '" data-name="' + esc(s.name || '') + '">&#x1f5d1; Delete</button>' +
'<a class="lt-btn lt-btn-ghost lt-btn-sm" href="' + esc(runsHref) + '">Runs</a>' +
'</div>'
: '<a class="lt-btn lt-btn-ghost lt-btn-sm" href="' + esc(runsHref) + '">Runs</a>';
return (
'<tr class="' + (s.enabled ? '' : 'sc-row-disabled') + '">' +
'<td data-label="Name">' + esc(s.name || '') + '</td>' +
'<td data-label="Command"><code>' + esc(s.command || '') + '</code></td>' +
'<td data-label="Schedule">' + scheduleDescription(s) + '</td>' +
'<td data-label="Workers">' + workerNamesHtml(workerIds) + '</td>' +
'<td data-label="Last run">' + lastRun + '</td>' +
'<td data-label="Next run">' + nextRun + '</td>' +
'<td data-label="Status">' + statusBadge + '</td>' +
'<td data-label="Actions">' + adminActions + '</td>' +
'</tr>'
);
}
function render() {
const wrap = document.getElementById('sc-wrap');
if (!wrap) return;
if (_schedules.length === 0) {
wrap.innerHTML =
'<div class="lt-empty-state">' +
'<div class="lt-empty-state-title">No scheduled commands yet</div>' +
'<div class="lt-empty-state-body">A schedule runs a command on the workers you pick, repeatedly. ' +
'Try the command in <a href="/quick">Quick Command</a> first, then schedule it here.</div>' +
'<button type="button" class="lt-btn lt-btn-primary" data-action="sc:create-open">+ New Schedule</button>' +
'</div>';
return;
}
wrap.innerHTML =
'<table class="lt-table lt-table-responsive">' +
'<thead><tr><th>Name</th><th>Command</th><th>Schedule</th><th>Workers</th><th>Last run</th><th>Next run</th><th>Status</th><th>Actions</th></tr></thead>' +
'<tbody>' + _schedules.map(rowHtml).join('') + '</tbody>' +
'</table>';
}
function renderError() {
const wrap = document.getElementById('sc-wrap');
if (!wrap) return;
wrap.innerHTML =
'<div class="lt-alert lt-alert--error">' +
'<span class="lt-alert-icon">&#x2715;</span>' +
'<div class="lt-alert-body"><div class="lt-alert-title">Failed to load schedules</div></div>' +
'</div>';
}
function onTick() {
document.querySelectorAll('#sc-wrap .sc-countdown[data-next-run]').forEach(el => {
const countdown = nextRunCountdown(el.getAttribute('data-next-run'));
el.textContent = countdown ? '(in ' + countdown + ')' : '';
});
}
/* -------------------------------------------------------------------
Create modal
------------------------------------------------------------------- */
function renderCreateWorkerList() {
const wrap = document.getElementById('sc-worker-list');
if (!wrap) return;
if (_workers.length === 0) {
wrap.innerHTML = '<div class="lt-empty-state lt-empty-state--sm"><div class="lt-empty-state-title">No workers available</div>' +
'<div class="lt-empty-state-body">Connect one first: see <a href="/workers">Workers</a>.</div></div>';
return;
}
wrap.innerHTML = _workers.map(w =>
'<label class="qc-worker-row' + (w.status === 'online' ? ' qc-worker-row--online' : '') + '">' +
'<input type="checkbox" class="lt-checkbox" name="sc-worker-cb" value="' + esc(w.id) + '">' +
'<span class="' + fmt.status(w.status) + '">' + (w.status === 'online' ? '&#x25cf;' : '&#x25cb;') + '</span>' +
'<strong>' + esc(w.name) + '</strong>' +
'</label>'
).join('');
}
function updateValueInput() {
const type = document.getElementById('sc-type').value;
const container = document.getElementById('sc-value-container');
if (!container) return;
if (type === 'interval') {
container.innerHTML =
'<label class="lt-label" for="sc-value">Interval (minutes)</label>' +
'<input type="number" id="sc-value" class="lt-input" placeholder="e.g. 30" min="1">';
} else if (type === 'hourly') {
container.innerHTML =
'<label class="lt-label" for="sc-value">Every X Hours</label>' +
'<input type="number" id="sc-value" class="lt-input" placeholder="e.g. 2" min="1" max="24">';
} else if (type === 'daily') {
container.innerHTML =
'<label class="lt-label" for="sc-value">Time (HH:MM, server time)</label>' +
'<input type="time" id="sc-value" class="lt-input">';
} else if (type === 'cron') {
container.innerHTML =
'<label class="lt-label" for="sc-value">Cron expression</label>' +
'<input type="text" id="sc-value" class="lt-input" placeholder="*/15 * * * *" autocomplete="off" spellcheck="false">' +
'<div class="lt-form-hint">minute hour day-of-month month day-of-week, e.g. <code>0 2 * * 1-5</code> is 02:00 on weekdays</div>';
}
const valueEl = document.getElementById('sc-value');
if (valueEl) valueEl.addEventListener('input', previewSoon);
previewSoon();
}
/* The next three runs, worked out by the server in its own time zone (#19). */
function previewSoon() {
clearTimeout(_previewTimer);
_previewTimer = setTimeout(updatePreview, 300);
}
async function updatePreview() {
const el = document.getElementById('sc-preview');
const typeEl = document.getElementById('sc-type');
const valueEl = document.getElementById('sc-value');
if (!el || !typeEl) return;
const value = valueEl ? valueEl.value.trim() : '';
if (!value) { el.textContent = ''; return; }
try {
const data = await Pulse.api.get('/api/scheduled-commands/preview?type=' + encodeURIComponent(typeEl.value) +
'&value=' + encodeURIComponent(value));
const runs = (data && data.next) || [];
el.className = 'sc-preview';
el.innerHTML = '<div class="sc-preview-title">Next runs</div><ul>' +
runs.map(r => '<li>' + esc(fmt.dateTime(r)) + '</li>').join('') + '</ul>' +
'<div class="sc-preview-tz">Worked out in the server\'s time zone: ' + esc((data && data.timezone) || 'unknown') + '</div>';
} catch (e) {
el.className = 'sc-preview sc-preview--bad';
el.textContent = (e && e.message) || 'Invalid schedule';
}
}
function showFormError(message) {
const el = document.getElementById('sc-create-error');
if (!el) return;
el.textContent = message || '';
el.hidden = !message;
}
function setDialogMode(editing) {
const title = document.getElementById('sc-create-title');
const submit = document.getElementById('sc-submit');
if (title) title.textContent = editing ? 'Edit Scheduled Command' : 'Create Scheduled Command';
if (submit) submit.textContent = editing ? 'Save Changes' : 'Create Schedule';
}
function resetCreateForm() {
_editingId = null;
setDialogMode(false);
showFormError('');
const form = document.getElementById('sc-create-form');
if (form) form.reset();
const type = document.getElementById('sc-type');
if (type) type.value = 'interval';
updateValueInput();
renderCreateWorkerList();
}
// Edit in place (#19): the same dialog, filled in, saving with PUT.
function openEdit(id) {
const s = _schedules.find(x => x.id === id);
if (!s) return;
resetCreateForm();
_editingId = id;
setDialogMode(true);
document.getElementById('sc-name').value = s.name || '';
document.getElementById('sc-command').value = s.command || '';
document.getElementById('sc-type').value = s.schedule_type;
updateValueInput();
const valueEl = document.getElementById('sc-value');
if (valueEl) valueEl.value = s.schedule_value || '';
const ids = new Set(parseWorkerIds(s.worker_ids));
document.querySelectorAll('input[name="sc-worker-cb"]').forEach(cb => { cb.checked = ids.has(cb.value); });
previewSoon();
if (window.lt && lt.modal) lt.modal.open('sc-create-modal');
}
async function runNow(id, name) {
try {
const r = await Pulse.api.post('/api/scheduled-commands/' + encodeURIComponent(id) + '/run', {});
const msg = 'Ran "' + name + '" on ' + r.sent + ' worker' + (r.sent === 1 ? '' : 's') +
(r.offline ? ' (' + r.offline + ' offline)' : '');
if (r.offline) Pulse.toast.warning(msg); else Pulse.toast.success(msg);
await load();
} catch (e) {
Pulse.toast.error('Could not run "' + name + '": ' + (e.message || 'unknown error'));
}
}
async function submitCreate() {
const name = document.getElementById('sc-name').value.trim();
const command = document.getElementById('sc-command').value.trim();
const type = document.getElementById('sc-type').value;
const valueEl = document.getElementById('sc-value');
const value = valueEl ? valueEl.value : '';
const workerIds = Array.from(document.querySelectorAll('input[name="sc-worker-cb"]:checked')).map(cb => cb.value);
if (!name || !command || !value || workerIds.length === 0) {
showFormError('Fill in every field and pick at least one worker');
return;
}
const body = { name: name, command: command, worker_ids: workerIds, schedule_type: type, schedule_value: value };
const editing = _editingId;
try {
if (editing) await Pulse.api.put('/api/scheduled-commands/' + encodeURIComponent(editing), body);
else await Pulse.api.post('/api/scheduled-commands', body);
if (window.lt && lt.modal) lt.modal.close('sc-create-modal');
Pulse.toast.success(editing ? 'Schedule saved' : 'Schedule created');
resetCreateForm();
await load();
} catch (e) {
// The server says what is wrong (e.g. a bad cron expression): keep the dialog open.
showFormError((e && e.message) || 'Could not save the schedule');
}
}
async function toggleSchedule(id) {
try {
const data = await Pulse.api.put('/api/scheduled-commands/' + encodeURIComponent(id) + '/toggle');
Pulse.toast.success('Schedule ' + (data && data.enabled ? 'enabled' : 'disabled'));
await load();
} catch (e) {
Pulse.toast.error('Failed to toggle schedule: ' + (e.message || 'unknown error'));
}
}
async function deleteSchedule(id, name) {
const ok = await Pulse.confirm({
title: 'Delete schedule',
message: 'Delete scheduled command: ' + name + '?',
type: 'error',
confirmLabel: 'DELETE',
});
if (!ok) return;
try {
await Pulse.api.delete('/api/scheduled-commands/' + encodeURIComponent(id));
Pulse.toast.success('Schedule deleted');
await load();
} catch (e) {
Pulse.toast.error('Failed to delete schedule: ' + (e.message || 'unknown error'));
}
}
/* -------------------------------------------------------------------
Data loading
------------------------------------------------------------------- */
async function loadWorkers() {
try {
_workers = await Pulse.api.get('/api/workers') || [];
} catch (e) {
_workers = [];
console.error('[Pulse:scheduler] failed to load workers', e);
}
return _workers;
}
async function loadSchedules() {
try {
_schedules = await Pulse.api.get('/api/scheduled-commands') || [];
render();
} catch (e) {
_schedules = [];
console.error('[Pulse:scheduler] failed to load schedules', e);
renderError();
}
return _schedules;
}
async function load() {
await loadWorkers();
await loadSchedules();
}
async function refresh() {
await load();
}
function init() {
Pulse.actions.registerAll({
'sc:create-open': () => {
resetCreateForm();
if (window.lt && lt.modal) lt.modal.open('sc-create-modal');
},
'sc:create-submit': submitCreate,
'sc:type': updateValueInput,
'sc:toggle': (el) => toggleSchedule(el.getAttribute('data-id')),
'sc:edit': (el) => openEdit(el.getAttribute('data-id')),
'sc:run': (el) => runNow(el.getAttribute('data-id'), el.getAttribute('data-name')),
'sc:delete': (el) => deleteSchedule(el.getAttribute('data-id'), el.getAttribute('data-name')),
});
Pulse.events.on('tick', onTick);
return load();
}
function onEvent(type) {
if (type === 'worker_update') {
loadWorkers().then(render);
return true;
}
return false;
}
Pulse.registerPage({ name: 'scheduler', init, refresh, onEvent });
})();