Files
pipelines/web/src/views/schedules.js
T

172 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { h } from '../dom.js';
import { SCHEDULE_DAYS, scheduleDraft, serializeSchedule, scheduleRuleLabel, scheduleDueLabel } from '../schedules.js';
import { newChatOperationId } from '../repository.js';
export function createSchedulesView(rt) {
const cache = new Map();
const pipelineId = pipeline => pipeline.Pipeline?.id ?? pipeline.id;
const message = error => {
const text = error?.message || String(error);
return /unknown (message|request|command)|unsupported.*schedule/i.test(text)
? `This server does not support saved schedules. Upgrade the server to use schedules. (${text})` : text;
};
const unsupported = () => new Error('This server does not support saved schedules. Upgrade the server to use schedules.');
const refresh = () => rt.renderContent();
function clearScheduleCache() { cache.clear(); }
function loadPipelineSchedules(id, { force = false } = {}) {
const prior = cache.get(id);
if (prior?.pending || (!force && prior)) return prior.pending ?? Promise.resolve(prior.items);
const entry = { items: prior?.items ?? [], loading: true, error: null };
cache.set(id, entry);
entry.pending = Promise.resolve().then(() => {
if (!rt.repo.listSchedules) throw unsupported();
return rt.repo.listSchedules(id);
}).then(items => {
if (!Array.isArray(items)) throw new Error('Server returned an invalid schedules response.');
entry.items = items;
return items;
}).catch(error => { entry.error = message(error); return null; }).finally(() => {
entry.loading = false; entry.pending = null;
if (cache.get(id) === entry) refresh();
});
return entry.pending;
}
async function changed(id) {
await loadPipelineSchedules(id, { force: true });
await rt.scheduleChanged?.(id);
refresh();
}
function button(text, onclick, props = {}) {
return h('button', { type: 'button', text, onclick, ...props });
}
function renderPipelineSchedules(pipeline) {
const id = pipelineId(pipeline);
if (!cache.has(id)) void loadPipelineSchedules(id);
const entry = cache.get(id);
const section = h('section', { class: 'schedule-section', 'aria-label': 'Schedules' },
h('div', { class: 'schedule-heading' }, h('h3', { text: `Schedules${entry && !entry.loading && !entry.error ? ` (${entry.items.length})` : ''}` }),
h('div', { class: 'schedule-actions' },
button('Refresh', () => { void loadPipelineSchedules(id, { force: true }); refresh(); }, { class: 'schedule-refresh' }),
button('Add schedule', event => openScheduleEditor({ pipeline, trigger: event.currentTarget }), { class: 'schedule-add' }))),
h('p', { class: 'schedule-muted', text: 'Independent prompts and timers for this pipeline. Schedules do not change its definition.' }));
if (entry.loading) section.append(h('p', { role: 'status', text: 'Loading schedules…' }));
if (entry.error) section.append(h('div', { class: 'schedule-error', role: 'alert' }, entry.error,
button('Retry', () => { void loadPipelineSchedules(id, { force: true }); refresh(); })));
if (!entry.loading && !entry.error && !entry.items.length) section.append(h('p', { class: 'schedule-muted', text: 'No schedules yet. Add one for each topic or recurring task.' }));
for (const schedule of entry.items) {
const errorNode = h('p', { class: 'schedule-error', role: 'alert', hidden: true });
const card = h('article', { class: 'schedule-card', 'data-schedule-id': schedule.id },
h('div', { class: 'schedule-heading' }, h('strong', { text: schedule.name }), h('span', { class: 'schedule-badge', text: schedule.enabled ? 'Enabled' : 'Paused' })),
h('div', { class: 'schedule-muted', text: `Pinned v${schedule.version} · ${scheduleRuleLabel(schedule.rule)}` }),
h('p', { class: 'schedule-prompt', text: schedule.input?.prompt ?? '' }),
h('div', { class: 'schedule-muted', text: `Next: ${schedule.enabled ? scheduleDueLabel(schedule.next_due, schedule.rule?.timezone) : 'Paused'}` }), errorNode);
const actions = h('div', { class: 'schedule-actions' });
const edit = button('Edit', event => openScheduleEditor({ pipeline, schedule, trigger: event.currentTarget }));
const toggle = button(schedule.enabled ? 'Pause' : 'Enable', async () => {
toggle.disabled = true;
try {
if (!rt.repo.saveSchedule) throw unsupported();
await rt.repo.saveSchedule({ ...schedule, enabled: !schedule.enabled });
await changed(id);
} catch (error) { errorNode.hidden = false; errorNode.textContent = message(error); }
finally { toggle.disabled = false; }
});
actions.append(edit, toggle, button('Delete', event => openDelete(schedule, event.currentTarget)));
card.append(actions); section.append(card);
}
return section;
}
function openDelete(schedule, trigger) {
let pending = false;
const close = () => { if (!pending) rt.modal.close('schedule-delete'); };
const errorNode = h('p', { class: 'schedule-error', role: 'alert' });
const confirm = button('Delete schedule', async () => {
if (pending) return;
pending = true; confirm.disabled = true;
try {
if (!rt.repo.deleteSchedule) throw unsupported();
await rt.repo.deleteSchedule(schedule.id, schedule.revision);
} catch (error) {
errorNode.textContent = message(error); pending = false; confirm.disabled = false; return;
}
// Keep mutation success separate from a subsequent list-refresh failure.
pending = false;
await changed(schedule.pipeline_id).catch(error => { errorNode.textContent = message(error); });
rt.modal.close('schedule-delete');
});
const panel = h('div', { class: 'schedule-overlay', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Delete schedule' },
h('div', { class: 'schedule-panel schedule-confirm' }, h('h2', { text: `Delete ${schedule.name}?` }),
h('p', { text: 'Future runs only. Run history and active runs will not be deleted.' }), errorNode,
h('div', { class: 'schedule-actions' }, button('Keep schedule', close), confirm)));
rt.modal.open('schedule-delete', panel, { trigger, onClose: close, renderManaged: false, history: false,
fallbackSelectors: ['.schedule-add', '.schedule-run', '#detailTitle', '#pane-main'] });
}
function openScheduleEditor({ pipeline, schedule = null, run = null, trigger = null }) {
const draft = scheduleDraft({ pipeline, schedule, run, workspace: rt.state.workspace });
const requestKey = schedule?.id ? undefined : `schedule:${newChatOperationId()}`;
let pending = false;
const close = () => { if (!pending) rt.modal.close('schedule-editor'); };
const fields = {};
const field = (key, label, { textarea = false, ...props } = {}) => {
const input = h(textarea ? 'textarea' : 'input', { class: 'schedule-input', name: key, type: textarea ? null : 'text', ...props });
input.value = draft[key]; fields[key] = input;
return h('label', { class: 'schedule-field' }, h('span', { text: label }), input);
};
const mode = h('select', { name: 'mode', 'aria-label': 'Timer mode' }, h('option', { value: 'interval', text: 'Interval' }), h('option', { value: 'clock', text: 'Clock times' }));
mode.value = draft.mode;
const interval = field('every', 'Interval (at least 1m)');
const clock = field('times', 'Clock times (24h, comma separated)');
const updateMode = () => { interval.hidden = mode.value !== 'interval'; clock.hidden = mode.value !== 'clock'; };
mode.addEventListener('change', updateMode); updateMode();
const days = h('fieldset', { class: 'schedule-days' }, h('legend', { text: 'Weekdays (none means every day)' }));
const dayInputs = SCHEDULE_DAYS.map(day => {
const input = h('input', { type: 'checkbox', value: day, checked: draft.days.includes(day) });
days.append(h('label', {}, input, day)); return input;
});
const enabled = h('input', { type: 'checkbox', name: 'enabled', checked: draft.enabled });
const notify = h('select', { name: 'notifyMode' }, ...['auto', 'on', 'off'].map(value => h('option', { value, text: value })));
notify.value = draft.notifyMode;
const errorNode = h('p', { class: 'schedule-error', role: 'alert', hidden: true });
const save = h('button', { type: 'submit', text: 'Save schedule' });
const form = h('form', { class: 'schedule-panel', novalidate: true },
h('h2', { text: schedule ? 'Edit schedule' : 'Add schedule' }),
h('p', { class: 'schedule-muted', text: 'Future runs only; does not publish or change the workflow. Saving does not start a run.' }),
field('name', 'Name', { required: true }), field('prompt', 'Prompt', { textarea: true, required: true, rows: 5 }),
h('div', { class: 'schedule-grid' }, field('version', 'Pinned version', { inputmode: 'numeric' }), field('workspace', 'Server workspace', { required: true })),
h('label', { class: 'schedule-field' }, 'Timer', mode), interval, clock, days,
field('timezone', 'Timezone (blank uses server timezone)'), h('label', { class: 'schedule-check' }, enabled, 'Enabled'),
h('p', { class: 'schedule-muted', text: 'Enabled schedules start future runs automatically, including model usage and the workflow’s permitted tools.' }),
h('details', { class: 'schedule-advanced' }, h('summary', { text: 'Advanced run options' }),
field('model', 'Model (provider/model)'), field('stageModels', 'Stage models (JSON object)', { textarea: true, rows: 3 }),
field('otherInput', 'Other input (JSON object; prompt above wins)', { textarea: true, rows: 4 }),
field('writePaths', 'Write paths (JSON array; optional additional restriction)', { textarea: true, rows: 3 }),
field('title', 'Run title (optional)'), h('label', { class: 'schedule-field' }, 'Notifications', notify), field('outputFormat', 'Output format (optional)')),
errorNode, h('div', { class: 'schedule-actions schedule-footer' }, button('Cancel', close), save));
form.addEventListener('submit', async event => {
event.preventDefault(); if (pending) return;
errorNode.hidden = true;
let record;
try {
for (const [key, input] of Object.entries(fields)) draft[key] = input.value;
Object.assign(draft, { mode: mode.value, days: dayInputs.filter(input => input.checked).map(input => input.value), enabled: enabled.checked, notifyMode: notify.value });
record = serializeSchedule(draft, { pipelineId: pipelineId(pipeline), schedule });
if (!rt.repo.saveSchedule) throw unsupported();
} catch (error) { errorNode.textContent = message(error); errorNode.hidden = false; return; }
const controls = [...form.querySelectorAll('input, textarea, select, button')];
pending = true; controls.forEach(control => { control.disabled = true; }); save.textContent = 'Saving…';
try { await rt.repo.saveSchedule(record, { requestKey }); }
catch (error) {
errorNode.textContent = `${message(error)} Your draft is preserved. If this schedule changed elsewhere, reopen it before retrying.`;
errorNode.hidden = false; pending = false; controls.forEach(control => { control.disabled = false; }); save.textContent = 'Save schedule'; return;
}
await changed(record.pipeline_id).catch(() => {});
pending = false; close();
});
const overlay = h('div', { class: 'schedule-overlay', role: 'dialog', 'aria-modal': 'true', 'aria-label': schedule ? 'Edit schedule' : 'Add schedule' }, form);
rt.modal.open('schedule-editor', overlay, { trigger, onClose: close, renderManaged: false, history: false,
fallbackSelectors: ['.schedule-add', '.schedule-run', '#detailTitle', '#pane-main'] });
return overlay;
}
return { renderPipelineSchedules, openScheduleEditor, loadPipelineSchedules, clearScheduleCache };
}