feat(client): add code-split Workflows, Broadcast, Snippets, Alerts views, pinned widgets, and service cron tasks

This commit is contained in:
tyuXX 2026-11-27 06:19:37 +00:00
parent 7272ad58bd
commit 41e79c3df3
9 changed files with 1925 additions and 72 deletions

View file

@ -0,0 +1,430 @@
import { apiFetch } from '../api.js';
import { confirmDialog } from '../dialogs.js';
import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js';
interface AlertChannelItem {
id: string;
name: string;
type: 'discord' | 'telegram' | 'ntfy' | 'generic';
url?: string;
secretRef: string;
chatId?: string;
topic?: string;
enabled: boolean;
}
interface AlertRuleItem {
id: string;
name: string;
kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system';
severity: 'warn' | 'critical';
target: { serverId?: string; tags?: string[]; all?: boolean };
forConsecutivePolls: number;
cooldownSec: number;
channelIds: string[];
remediationWorkflowId?: string;
enabled: boolean;
metric?: string;
operator?: string;
threshold?: number;
mountPoint?: string;
thresholdPct?: number;
offlineSec?: number;
probeId?: string;
systemId?: string;
item?: string;
}
interface MaintenanceWindowItem {
id: string;
name: string;
cron: string;
timezone: string;
durationMinutes: number;
target: { serverId?: string; tags?: string[]; all?: boolean };
enabled: boolean;
}
interface AlertsPayload {
alertsConfig: {
version: 1;
channels: AlertChannelItem[];
rules: AlertRuleItem[];
maintenanceWindows: MaintenanceWindowItem[];
};
activeCount: number;
activeEvents: Array<{
id: string;
ruleId: string;
serverId: string | null;
state: string;
severity: string;
message: string;
webhookStatus: string | null;
triggeredAt: number;
}>;
recentEvents: Array<{
id: string;
ruleId: string;
serverId: string | null;
state: string;
severity: string;
message: string;
webhookStatus: string | null;
triggeredAt: number;
resolvedAt: number | null;
}>;
silences: Array<{
id: string;
scopeType: string;
targetId: string;
reason: string | null;
expiresAt: number;
}>;
activeMaintenanceWindowIds: string[];
}
export async function renderAlertsView(
root: HTMLElement,
state: ClientState,
): Promise<void> {
root.replaceChildren();
const [data, credsRes] = await Promise.all([
apiFetch<AlertsPayload>('/api/alerts'),
apiFetch<{ credentials: Array<{ id: string; type: string }> }>('/api/vault/credentials').catch(() => ({
credentials: [],
})),
]);
state.activeAlertCount = data.activeCount;
const cfg = data.alertsConfig;
const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh');
refreshBtn.addEventListener('click', () => {
void renderAlertsView(root, state);
});
root.append(
el(
'section',
{ class: 'panel row-between' },
el('div', {}, el('h1', {}, `Alerting & Webhooks (${data.activeCount} firing)`), el('p', { class: 'muted' }, `${cfg.rules.length} rules, ${cfg.channels.length} channels, ${cfg.maintenanceWindows.length} maintenance windows, ${data.silences.length} active silences.`)),
refreshBtn,
),
);
// 1. Firing Incidents + Quick Snooze
const firingPanel = el('section', { class: 'panel panel-region' });
firingPanel.append(el('h2', {}, `Active Firing Alerts (${data.activeEvents.length})`));
if (data.activeEvents.length === 0) {
firingPanel.append(el('p', { class: 'ok-text' }, 'All monitored rules are currently healthy.'));
} else {
for (const evt of data.activeEvents) {
const snoozeButtons = (
[
['Snooze 30m', 'rule', evt.ruleId, 30],
['Mute Server 2h', evt.serverId ? 'server' : 'rule', evt.serverId ?? evt.ruleId, 120],
['Mute 12h', evt.serverId ? 'server' : 'rule', evt.serverId ?? evt.ruleId, 720],
] as const
).map(([label, scopeType, targetId, durationMinutes]) => {
const b = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, label);
b.addEventListener('click', async () => {
await apiFetch('/api/alerts/silences', {
method: 'POST',
body: { scopeType, targetId, durationMinutes, reason: `Quick snooze from ${evt.id}` },
});
await renderAlertsView(root, state);
});
return b;
});
firingPanel.append(
el(
'div',
{ class: 'alert-box' },
el('div', { class: 'row-between' }, el('strong', { class: evt.severity === 'critical' ? 'err-text' : 'warn-text' }, `[${evt.severity.toUpperCase()}] ${evt.ruleId}${evt.serverId ? ` @ ${evt.serverId}` : ''}`), el('div', { class: 'row' }, ...snoozeButtons)),
el('div', { class: 'mono' }, evt.message),
el('div', { class: 'mono muted' }, `Fired: ${fmtTime(evt.triggeredAt)} | Webhook: ${evt.webhookStatus ?? 'none'}`),
),
);
}
}
root.append(firingPanel);
// 2. Silences & Maintenance Windows
const silPanel = el('section', { class: 'panel panel-region' });
silPanel.append(el('h2', {}, 'Active Silences / Snoozes'));
const silScope = el(
'select',
{ class: 'input-sm' },
el('option', { value: 'server' }, 'server'),
el('option', { value: 'rule' }, 'rule'),
el('option', { value: 'tag' }, 'tag'),
el('option', { value: 'all' }, 'all'),
);
const silTarget = el('input', { class: 'input-sm', placeholder: 'Target ID (or * for all)' });
const silDur = el('input', { class: 'input-sm', type: 'number', min: 1, max: 43200, value: '120' });
const silReason = el('input', { class: 'input-sm', placeholder: 'Reason (optional)' });
const silForm = el(
'form',
{ class: 'row', style: 'margin-bottom:8px' },
silScope,
silTarget,
silDur,
silReason,
el('button', { type: 'submit', class: 'btn btn-sm btn-primary mutating-action' }, 'Add Silence'),
);
silForm.addEventListener('submit', async (ev) => {
ev.preventDefault();
await apiFetch('/api/alerts/silences', {
method: 'POST',
body: {
scopeType: silScope.value,
targetId: silScope.value === 'all' ? '*' : silTarget.value.trim(),
durationMinutes: Number(silDur.value || 60),
reason: silReason.value.trim() || undefined,
},
});
await renderAlertsView(root, state);
});
silPanel.append(silForm);
for (const s of data.silences) {
const unmuteBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Remove');
unmuteBtn.addEventListener('click', async () => {
await apiFetch(`/api/alerts/silences/${encodeURIComponent(s.id)}`, { method: 'DELETE' });
await renderAlertsView(root, state);
});
silPanel.append(
el('div', { class: 'row-between panel' }, el('span', { class: 'mono' }, `[${s.scopeType}:${s.targetId}] expires ${fmtTime(s.expiresAt)}${s.reason ? ` — ${s.reason}` : ''}`), unmuteBtn),
);
}
// Maintenance windows inside same card
silPanel.append(el('h2', { style: 'margin-top:12px' }, `Scheduled Maintenance Windows (${cfg.maintenanceWindows.length})`));
const saveConfig = async (nextCfg: AlertsPayload['alertsConfig']) => {
await apiFetch('/api/alerts/config', { method: 'PUT', body: nextCfg });
await renderAlertsView(root, state);
};
for (const w of cfg.maintenanceWindows) {
const active = data.activeMaintenanceWindowIds.includes(w.id);
const rmWin = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
rmWin.addEventListener('click', () => {
void saveConfig({
...cfg,
maintenanceWindows: cfg.maintenanceWindows.filter((x) => x.id !== w.id),
});
});
silPanel.append(
el('div', { class: 'row-between panel' }, el('span', { class: 'mono' }, `${w.name} (${w.id}) | cron "${w.cron}" ${w.timezone} (${w.durationMinutes}m) ${active ? '[ACTIVE NOW]' : ''}`), rmWin),
);
}
const mwId = el('input', { class: 'input-sm', placeholder: 'nightly-maint', required: true });
const mwName = el('input', { class: 'input-sm', placeholder: 'Nightly Updates', required: true });
const mwCron = el('input', { class: 'input-sm', value: '0 3 * * *', required: true });
const mwDur = el('input', { class: 'input-sm', type: 'number', min: 1, max: 1440, value: '60', required: true });
const mwForm = el('form', { class: 'row', style: 'margin-top:6px' }, mwId, mwName, mwCron, mwDur, el('button', { type: 'submit', class: 'btn btn-sm mutating-action' }, '+ Window'));
mwForm.addEventListener('submit', (ev) => {
ev.preventDefault();
void saveConfig({
...cfg,
maintenanceWindows: [
...cfg.maintenanceWindows,
{
id: mwId.value.trim(),
name: mwName.value.trim(),
cron: mwCron.value.trim(),
timezone: 'UTC',
durationMinutes: Number(mwDur.value || 60),
target: { all: true },
enabled: true,
},
],
});
});
silPanel.append(mwForm);
root.append(silPanel);
// 3. Notification Channels & Test Alert
const chanPanel = el('section', { class: 'panel panel-region' });
chanPanel.append(el('h2', {}, `Webhook Channels (${cfg.channels.length})`));
const chanStatusMsg = el('p', { class: 'form-msg' });
const cTbl = el('table');
cTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'ID'), el('th', {}, 'Type'), el('th', {}, 'Endpoint / Ref'), el('th', {}, 'Actions'))));
const cBody = el('tbody');
for (const ch of cfg.channels) {
const testBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Send Test Alert');
testBtn.addEventListener('click', async () => {
chanStatusMsg.textContent = `Sending test alert to "${ch.id}"...`;
try {
const res = await apiFetch<{ ok: boolean; statusCode?: number; error?: string }>(
`/api/alerts/channels/${encodeURIComponent(ch.id)}/test`,
{ method: 'POST' },
);
chanStatusMsg.className = res.ok ? 'form-msg ok-text' : 'form-msg err-text';
chanStatusMsg.textContent = res.ok
? `Test alert delivered to "${ch.id}" (HTTP ${String(res.statusCode ?? 200)}).`
: `Test alert failed for "${ch.id}": ${res.error ?? `HTTP ${String(res.statusCode)}`}`;
} catch (err) {
chanStatusMsg.className = 'form-msg err-text';
chanStatusMsg.textContent = extractErrorMessage(err);
}
});
const delCh = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
delCh.addEventListener('click', async () => {
const ok = await confirmDialog('dialog-confirm', `Delete alert channel "${ch.id}"?`);
if (!ok) return;
await saveConfig({ ...cfg, channels: cfg.channels.filter((x) => x.id !== ch.id) });
});
cBody.append(
el('tr', {}, el('td', { class: 'mono' }, `${ch.id} (${ch.name})`), el('td', {}, el('span', { class: 'badge' }, ch.type)), el('td', { class: 'mono' }, `${ch.url ?? ch.topic ?? ch.chatId ?? '—'} [vault:${ch.secretRef}]`), el('td', {}, el('div', { class: 'row' }, testBtn, delCh))),
);
}
cTbl.append(cBody);
const chId = el('input', { placeholder: 'ops-webhook', required: true });
const chName = el('input', { placeholder: 'Ops Webhook', required: true });
const chType = el('select', {}, el('option', { value: 'generic' }, 'generic'), el('option', { value: 'discord' }, 'discord'), el('option', { value: 'telegram' }, 'telegram'), el('option', { value: 'ntfy' }, 'ntfy'));
const chUrl = el('input', { placeholder: 'Webhook / base URL (optional for ntfy.sh or Telegram)' });
const chExtra = el('input', { placeholder: 'Telegram chatId OR ntfy topic (optional)' });
const chRef = el('select', {});
for (const cr of credsRes.credentials) {
chRef.append(el('option', { value: cr.id }, `${cr.id} (${cr.type})`));
}
if (credsRes.credentials.length === 0) {
chRef.append(el('option', { value: 'webhook-main' }, 'webhook-main (add in Vault)'));
}
const chForm = el(
'form',
{ class: 'stack', style: 'margin-top:8px' },
el('div', { class: 'grid-3' }, chId, chName, chType),
el('div', { class: 'grid-3' }, chUrl, chExtra, chRef),
el('div', {}, el('button', { type: 'submit', class: 'btn btn-sm mutating-action' }, '+ Add Webhook Channel')),
);
chForm.addEventListener('submit', async (ev) => {
ev.preventDefault();
chanStatusMsg.textContent = '';
try {
await saveConfig({
...cfg,
channels: [
...cfg.channels,
{
id: chId.value.trim(),
name: chName.value.trim(),
type: chType.value as AlertChannelItem['type'],
url: chUrl.value.trim() || undefined,
secretRef: chRef.value.trim(),
chatId: chType.value === 'telegram' ? chExtra.value.trim() || undefined : undefined,
topic: chType.value === 'ntfy' ? chExtra.value.trim() || undefined : undefined,
enabled: true,
},
],
});
} catch (err) {
chanStatusMsg.className = 'form-msg err-text';
chanStatusMsg.textContent = extractErrorMessage(err);
}
});
chanPanel.append(el('div', { class: 'table-wrap' }, cTbl), chanStatusMsg, chForm);
root.append(chanPanel);
// 4. Alert Rules
const rulesPanel = el('section', { class: 'panel panel-region' });
rulesPanel.append(el('h2', {}, `Alert Rules (${cfg.rules.length})`));
const rMsg = el('p', { class: 'form-msg err-text' });
for (const r of cfg.rules) {
const condText =
r.kind === 'metric'
? `${r.metric} ${r.operator} ${r.threshold}`
: r.kind === 'disk'
? `disk ${r.mountPoint ?? '*'} >= ${r.thresholdPct}%`
: r.kind === 'offline'
? `offline >= ${r.offlineSec}s`
: r.kind === 'probe'
? `probe ${r.probeId ?? '*'}`
: `system ${r.systemId}/${r.item ?? '*'}`;
const toggleBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, r.enabled ? 'Disable' : 'Enable');
toggleBtn.addEventListener('click', () => {
void saveConfig({
...cfg,
rules: cfg.rules.map((x) => (x.id === r.id ? { ...x, enabled: !x.enabled } : x)),
});
});
const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
delBtn.addEventListener('click', () => {
void saveConfig({ ...cfg, rules: cfg.rules.filter((x) => x.id !== r.id) });
});
rulesPanel.append(
el('div', { class: 'row-between panel' }, el('div', {}, el('strong', {}, `${r.name} (${r.id})`), el('div', { class: 'mono muted' }, `${condText} | for=${r.forConsecutivePolls} | cooldown=${r.cooldownSec}s | channels=[${r.channelIds.join(',')}]${r.remediationWorkflowId ? ` | fix=${r.remediationWorkflowId}` : ''}`)), el('div', { class: 'row' }, toggleBtn, delBtn)),
);
}
const ruleId = el('input', { placeholder: 'high-cpu', required: true });
const ruleName = el('input', { placeholder: 'High CPU Usage', required: true });
const ruleKind = el('select', {}, el('option', { value: 'metric' }, 'metric'), el('option', { value: 'disk' }, 'disk'), el('option', { value: 'offline' }, 'offline'), el('option', { value: 'probe' }, 'probe'), el('option', { value: 'system' }, 'system'));
const ruleSev = el('select', {}, el('option', { value: 'warn' }, 'warn'), el('option', { value: 'critical' }, 'critical'));
const ruleParam1 = el('input', { placeholder: 'metric/mount/probe/system (e.g. cpuPct)' });
const ruleThresh = el('input', { type: 'number', value: '85', placeholder: 'Threshold / Offline sec' });
const rulePolls = el('input', { type: 'number', min: 1, value: '3', placeholder: 'forConsecutivePolls' });
const ruleChans = el('input', { placeholder: 'channelIds comma-sep (optional)' });
const ruleRemWf = el('input', { placeholder: 'remediationWorkflowId (optional)' });
const ruleForm = el(
'form',
{ class: 'stack', style: 'margin-top:8px' },
el('div', { class: 'grid-3' }, ruleId, ruleName, ruleKind),
el('div', { class: 'grid-3' }, ruleSev, ruleParam1, ruleThresh),
el('div', { class: 'grid-3' }, rulePolls, ruleChans, ruleRemWf),
rMsg,
el('div', {}, el('button', { type: 'submit', class: 'btn btn-sm btn-primary mutating-action' }, '+ Add Alert Rule')),
);
ruleForm.addEventListener('submit', async (ev) => {
ev.preventDefault();
rMsg.textContent = '';
const base = {
id: ruleId.value.trim(),
name: ruleName.value.trim(),
severity: ruleSev.value as 'warn' | 'critical',
target: { all: true },
forConsecutivePolls: Number(rulePolls.value || 3),
cooldownSec: 300,
channelIds: ruleChans.value.split(',').map((c) => c.trim()).filter(Boolean),
remediationWorkflowId: ruleRemWf.value.trim() || undefined,
enabled: true,
};
let nextRule: AlertRuleItem;
if (ruleKind.value === 'disk') {
nextRule = { ...base, kind: 'disk', mountPoint: ruleParam1.value.trim() || undefined, thresholdPct: Number(ruleThresh.value || 90) };
} else if (ruleKind.value === 'offline') {
nextRule = { ...base, kind: 'offline', offlineSec: Number(ruleThresh.value || 60) };
} else if (ruleKind.value === 'probe') {
nextRule = { ...base, kind: 'probe', probeId: ruleParam1.value.trim() || undefined };
} else if (ruleKind.value === 'system') {
nextRule = { ...base, kind: 'system', systemId: ruleParam1.value.trim() || 'docker-compose' };
} else {
nextRule = { ...base, kind: 'metric', metric: (ruleParam1.value.trim() || 'cpuPct') as 'cpuPct', operator: 'gt', threshold: Number(ruleThresh.value || 85) };
}
try {
await saveConfig({ ...cfg, rules: [...cfg.rules, nextRule] });
} catch (err) {
rMsg.textContent = extractErrorMessage(err);
}
});
rulesPanel.append(ruleForm);
root.append(rulesPanel);
// 5. Recent History
const histPanel = el('section', { class: 'panel panel-region' });
histPanel.append(el('h2', {}, `Recent Alert Events (${data.recentEvents.length})`));
const hTbl = el('table');
hTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'Rule'), el('th', {}, 'Server'), el('th', {}, 'State'), el('th', {}, 'Message'), el('th', {}, 'Time'))));
const hBody = el('tbody');
for (const e of data.recentEvents) {
hBody.append(
el('tr', {}, el('td', { class: 'mono' }, e.ruleId), el('td', { class: 'mono' }, e.serverId ?? '—'), el('td', {}, el('span', { class: e.state === 'firing' ? 'badge badge-err' : 'badge badge-ok' }, `[${e.state.toUpperCase()}]`)), el('td', { class: 'mono' }, e.message), el('td', { class: 'mono' }, fmtTime(e.triggeredAt))),
);
}
hTbl.append(hBody);
histPanel.append(el('div', { class: 'table-wrap' }, hTbl));
root.append(histPanel);
}

View file

@ -229,7 +229,20 @@ export async function renderDashboardView(
state: ClientState,
): Promise<void> {
root.replaceChildren();
const res = await apiFetch<{ servers: ServerEntry[] }>('/api/servers');
const [res, pinnedRes] = await Promise.all([
apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
apiFetch<{
workflows: Array<{
workflow: {
id: string;
name: string;
inputs: Array<{ required?: boolean; default?: unknown }>;
};
latestRun: { runId: string; status: string; finishedAt: number | null } | null;
latestStepLogs: Array<{ stepId: string; stdout: string; stderr: string }>;
}>;
}>('/api/workflows?pinnedOnly=1').catch(() => ({ workflows: [] })),
]);
const servers = res.servers;
const actionStatus = el('p', { class: 'form-msg' });
@ -352,6 +365,92 @@ export async function renderDashboardView(
);
}
if (pinnedRes.workflows.length > 0) {
const pinnedGrid = el('div', { class: 'grid-2' });
for (const entry of pinnedRes.workflows) {
const wf = entry.workflow;
const runStatus = entry.latestRun?.status ?? 'idle';
const badgeClass =
runStatus === 'success'
? 'badge badge-ok'
: runStatus === 'failed' || runStatus === 'timed-out'
? 'badge badge-err'
: runStatus === 'running' || runStatus === 'queued'
? 'badge badge-warn'
: 'badge';
const rawOut = entry.latestStepLogs
.map((l) => l.stdout || l.stderr)
.filter((s) => s.length > 0)
.join('\n')
.trim();
const previewText = rawOut
? rawOut.length > 220
? `${rawOut.slice(0, 220)}…`
: rawOut
: 'No output captured yet.';
const statusNote = el('span', { class: 'muted mono' }, '');
const needsPrompt = wf.inputs.some(
(inp) => inp.required !== false && inp.default === undefined,
);
const runBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm btn-primary' },
needsPrompt ? 'Inputs…' : 'Run',
);
runBtn.addEventListener('click', async () => {
if (needsPrompt) {
window.location.hash = '#workflows';
return;
}
runBtn.disabled = true;
statusNote.textContent = 'Starting…';
try {
const started = await apiFetch<{ runId: string; status: string }>(
`/api/workflows/${encodeURIComponent(wf.id)}/run`,
{ method: 'POST', body: {} },
);
statusNote.textContent = `Run ${started.runId}: ${started.status}`;
} catch (err) {
statusNote.textContent = err instanceof Error ? err.message : String(err);
} finally {
runBtn.disabled = false;
}
});
pinnedGrid.append(
el(
'article',
{ class: 'panel' },
el(
'div',
{ class: 'row-between' },
el('strong', {}, wf.name),
el('span', { class: badgeClass }, runStatus.toUpperCase()),
),
el('pre', { class: 'terminal-preview muted' }, previewText),
el(
'div',
{ class: 'row-between' },
el('div', { class: 'row' }, runBtn, el('a', { href: '#workflows', class: 'btn btn-sm' }, 'Open')),
statusNote,
),
),
);
}
root.append(
el(
'section',
{ class: 'panel' },
el(
'div',
{ class: 'row-between' },
el('h2', {}, `Pinned Workflows (${pinnedRes.workflows.length})`),
el('a', { href: '#workflows', class: 'btn btn-sm' }, 'All Workflows'),
),
pinnedGrid,
),
);
}
if (servers.length === 0) {
root.append(
el(

View file

@ -1,49 +0,0 @@
import { el, type ConfigOverview, type RouteId } from '../state.js';
export function renderSectionShell(
root: HTMLElement,
route: 'workflows' | 'alerts',
overview: ConfigOverview,
): void {
root.replaceChildren();
if (route === 'workflows') {
const panel = el('section', { class: 'panel' });
panel.append(
el('h1', {}, 'DAG Workflows & Command Snippets'),
el('p', { class: 'muted' }, 'Full-DAG execution, croner triggers, and Ad-Hoc Fleet Broadcast activate in Phase 4.'),
);
if (overview.workflows.length === 0) {
panel.append(el('p', { class: 'muted' }, 'No workflows configured yet. Create one in Config -> workflows/<id>.json.'));
} else {
for (const wf of overview.workflows) {
const steps = Array.isArray(wf.steps) ? wf.steps : [];
panel.append(
el(
'div',
{ class: 'panel' },
el('strong', {}, `${String(wf.name ?? wf.id)} (${String(wf.id)})`),
el('div', { class: 'mono muted' }, `Steps: ${steps.length} | Overlap: ${String(wf.overlapPolicy ?? 'skip')}`),
),
);
}
}
const snips = overview.snippets.snippets ?? [];
panel.append(el('h2', {}, `Saved Snippets (${snips.length})`));
for (const sn of snips) {
panel.append(el('div', { class: 'mono' }, `• ${String(sn.id)}: ${String(sn.command)}`));
}
root.append(panel);
return;
}
const panel = el('section', { class: 'panel' });
const rules = overview.alerts.rules ?? [];
const channels = overview.alerts.channels ?? [];
const windows = overview.alerts.maintenanceWindows ?? [];
panel.append(
el('h1', {}, 'Alerting, Channels & Maintenance Windows'),
el('p', { class: 'muted' }, `Configured in alerts.json: ${rules.length} rules, ${channels.length} channels, ${windows.length} maintenance windows. AlertEngine evaluates live samples starting Phase 4.`),
);
root.append(panel);
}

View file

@ -513,26 +513,188 @@ export async function renderSystemsView(
}
// Per-Service Tasks & Cron workflows matching scope
const scopedWfs = (state.overview?.workflows ?? []).filter((wf) => {
const scope = wf.scope as { serverId?: string; systemId?: string; item?: string } | undefined;
if (!scope) return false;
if (scope.systemId && scope.systemId !== systemId) return false;
if (scope.serverId && scope.serverId !== targetServerId) return false;
if (scope.item && scope.item !== item.name) return false;
return Boolean(scope.systemId);
});
const tasksPanel = el('section', { class: 'panel' });
tasksPanel.append(
el('div', { class: 'row-between' }, el('h2', {}, `Tasks & Cron (${scopedWfs.length})`), el('a', { href: '#config', class: 'btn btn-sm' }, 'Configure Workflows')),
const tasksListHost = el('div', { class: 'stack' });
const taskOutputPre = el('pre', { class: 'terminal-preview muted', hidden: true }, '');
const scheduleFormWrap = el('form', { class: 'stack panel', hidden: true });
const taskActionInput = el('input', {
type: 'text',
value: 'restart',
placeholder: 'restart / reload / status',
required: true,
});
const taskNameInput = el('input', {
type: 'text',
value: `${item.name} scheduled task`,
required: true,
});
const taskCronInput = el('input', {
type: 'text',
placeholder: '0 4 * * * (blank = manual)',
});
const taskTzInput = el('input', { type: 'text', value: 'UTC' });
const taskFormErr = el('p', { class: 'err-text', hidden: true }, '');
const toggleScheduleBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm btn-primary' },
'+ Schedule Service Task',
);
if (scopedWfs.length === 0) {
tasksPanel.append(el('p', { class: 'muted' }, 'No scoped workflows yet. Phase 4 adds interactive scheduling and execution here.'));
} else {
for (const wf of scopedWfs) {
tasksPanel.append(el('div', { class: 'mono' }, `• ${String(wf.name ?? wf.id)} (${String(wf.id)})`));
toggleScheduleBtn.addEventListener('click', () => {
scheduleFormWrap.hidden = !scheduleFormWrap.hidden;
});
const refreshScopedTasks = async (): Promise<void> => {
const wfRes = await apiFetch<{
workflows: Array<{
workflow: {
id: string;
name: string;
trigger: { type: string; expression?: string };
scope?: { serverId?: string; systemId?: string; item?: string };
};
nextRunAt: number | null;
latestRun: { runId: string; status: string } | null;
}>;
}>('/api/workflows').catch(() => ({ workflows: [] }));
const scopedWfs = wfRes.workflows.filter((entry) => {
const sc = entry.workflow.scope;
if (!sc || sc.systemId !== systemId) return false;
if (sc.serverId && sc.serverId !== targetServerId) return false;
if (sc.item && sc.item !== item.name) return false;
return true;
});
tasksListHost.replaceChildren();
if (scopedWfs.length === 0) {
tasksListHost.append(
el('p', { class: 'muted' }, 'No scoped tasks or cron workflows for this service yet.'),
);
return;
}
}
for (const entry of scopedWfs) {
const wf = entry.workflow;
const trigText =
wf.trigger.type === 'cron'
? `cron: ${wf.trigger.expression ?? ''}${entry.nextRunAt ? ` (next ${new Date(entry.nextRunAt).toISOString().slice(0, 19).replace('T', ' ')})` : ''}`
: wf.trigger.type;
const statusBadge = el(
'span',
{
class:
entry.latestRun?.status === 'success'
? 'badge badge-ok'
: entry.latestRun?.status === 'failed'
? 'badge badge-err'
: 'badge',
},
entry.latestRun?.status ?? 'idle',
);
const runTaskBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary' }, 'Run Task');
runTaskBtn.addEventListener('click', async () => {
runTaskBtn.disabled = true;
taskOutputPre.hidden = false;
taskOutputPre.textContent = `Running ${wf.name}…`;
try {
const started = await apiFetch<{ runId: string; status: string }>(
`/api/workflows/${encodeURIComponent(wf.id)}/run`,
{ method: 'POST', body: {} },
);
taskOutputPre.textContent = `Run ${started.runId}: ${started.status}`;
for (let i = 0; i < 15; i++) {
await new Promise((r) => setTimeout(r, 400));
const detail = await apiFetch<{
run: { status: string };
stepLogs: Array<{ stepId: string; exitCode: number | null; stdout: string; stderr: string }>;
}>(`/api/workflows/runs/${encodeURIComponent(started.runId)}`);
const logs = detail.stepLogs
.map((l) => `[${l.stepId}] exit=${l.exitCode ?? '-'}\n${l.stdout}${l.stderr ? `\nSTDERR:\n${l.stderr}` : ''}`)
.join('\n');
taskOutputPre.textContent = `Status: ${detail.run.status}\n${logs}`.trim();
if (detail.run.status !== 'running' && detail.run.status !== 'queued') break;
}
await refreshScopedTasks();
} catch (err) {
taskOutputPre.textContent = err instanceof Error ? err.message : String(err);
} finally {
runTaskBtn.disabled = false;
}
});
tasksListHost.append(
el(
'div',
{ class: 'row-between' },
el('div', {}, el('strong', {}, wf.name), el('span', { class: 'muted mono' }, ` (${trigText})`)),
el('div', { class: 'row' }, statusBadge, runTaskBtn),
),
);
}
};
const saveTaskBtn = el('button', { type: 'submit', class: 'btn btn-sm btn-primary' }, 'Create Task');
scheduleFormWrap.append(
el('label', {}, 'Task Name', taskNameInput),
el('label', {}, 'System Action ID', taskActionInput),
el('div', { class: 'grid-2' }, el('label', {}, 'Cron (optional)', taskCronInput), el('label', {}, 'Timezone', taskTzInput)),
taskFormErr,
el('div', { class: 'row' }, saveTaskBtn),
);
scheduleFormWrap.addEventListener('submit', async (ev) => {
ev.preventDefault();
taskFormErr.hidden = true;
const slug = `${systemId}-${item.name}`
.toLowerCase()
.replace(/[^a-z0-9_-]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 28);
const id = `svc-${slug || 'task'}-${Date.now().toString(36)}`;
const cronExpr = taskCronInput.value.trim();
try {
await apiFetch('/api/workflows', {
method: 'POST',
body: {
id,
name: taskNameInput.value.trim() || `${item.name} task`,
enabled: true,
trigger: cronExpr
? { type: 'cron', expression: cronExpr, timezone: taskTzInput.value.trim() || 'UTC' }
: { type: 'manual' },
overlapPolicy: 'skip',
display: { mode: 'log', pinToDashboard: false },
scope: { serverId: targetServerId, systemId, item: item.name },
inputs: [],
steps: [
{
id: 'service-action',
type: 'system-action',
target: { serverId: targetServerId },
systemId,
action: taskActionInput.value.trim() || 'status',
item: item.name,
},
],
},
});
scheduleFormWrap.hidden = true;
await refreshScopedTasks();
} catch (err) {
taskFormErr.hidden = false;
taskFormErr.textContent = err instanceof Error ? err.message : String(err);
}
});
tasksPanel.append(
el(
'div',
{ class: 'row-between' },
el('h2', {}, 'Tasks & Cron'),
el('div', { class: 'row' }, toggleScheduleBtn, el('a', { href: '#workflows', class: 'btn btn-sm' }, 'All Workflows')),
),
scheduleFormWrap,
tasksListHost,
taskOutputPre,
);
root.append(tasksPanel);
void refreshScopedTasks();
return;
}

File diff suppressed because it is too large Load diff