diff --git a/src/client/index.html b/src/client/index.html
index 03dc22b..f58ec26 100644
--- a/src/client/index.html
+++ b/src/client/index.html
@@ -19,6 +19,7 @@
[OFFLINE]
[VAULT]
+ [ALERTS: 0]
diff --git a/src/client/ts/main.ts b/src/client/ts/main.ts
index 471210b..8f1f14d 100644
--- a/src/client/ts/main.ts
+++ b/src/client/ts/main.ts
@@ -26,7 +26,6 @@ import {
patchDashboardServerTick,
renderDashboardView,
} from './views/dashboard-view.js';
-import { renderSectionShell } from './views/section-shells.js';
import { renderServerDetailView } from './views/server-detail-view.js';
import { renderSettingsView } from './views/settings-view.js';
import { renderVaultView } from './views/vault-view.js';
@@ -54,6 +53,7 @@ const state: ClientState = {
safeMode: false,
defaultMobileSafeMode: true,
elevatedUntil: null,
+ activeAlertCount: 0,
theme: localStorage.getItem(THEME_STORAGE_KEY) ?? 'phosphor-green',
route: 'dashboard',
overview: null,
@@ -98,6 +98,7 @@ function updateTopBarUi(): void {
const safeBtn = document.getElementById('safe-toggle-btn')!;
const themeSelect = document.getElementById('theme-select') as HTMLSelectElement;
const stepupBadge = document.getElementById('stepup-badge')!;
+ const alertsBadge = document.getElementById('alerts-badge')!;
const banner = document.getElementById('global-banner')!;
topbar.hidden = !state.authenticated;
@@ -133,6 +134,13 @@ function updateTopBarUi(): void {
stepupBadge.hidden = true;
}
+ if (state.authenticated && state.activeAlertCount > 0) {
+ alertsBadge.hidden = false;
+ alertsBadge.textContent = `[ALERTS: ${state.activeAlertCount}]`;
+ } else {
+ alertsBadge.hidden = true;
+ }
+
const activeNavRoute = state.route === 'server-detail' ? 'dashboard' : state.route;
for (const link of nav.querySelectorAll('.nav-link')) {
const r = link.getAttribute('data-route');
@@ -150,7 +158,12 @@ function updateTopBarUi(): void {
}
async function refreshOverview(): Promise
{
- state.overview = await apiFetch('/api/config/overview');
+ const [overview, alertsSummary] = await Promise.all([
+ apiFetch('/api/config/overview'),
+ apiFetch<{ activeCount: number }>('/api/alerts?limit=1').catch(() => ({ activeCount: 0 })),
+ ]);
+ state.overview = overview;
+ state.activeAlertCount = alertsSummary.activeCount ?? 0;
updateTopBarUi();
}
@@ -233,9 +246,14 @@ async function renderCurrentView(): Promise {
await renderSystemsView(root, state, wsClient);
return;
}
-
- if (route === 'workflows' || route === 'alerts') {
- renderSectionShell(root, route, state.overview!);
+ if (route === 'workflows') {
+ const { renderWorkflowsView } = await import('./views/workflows-view.js');
+ await renderWorkflowsView(root, state, wsClient);
+ return;
+ }
+ if (route === 'alerts') {
+ const { renderAlertsView } = await import('./views/alerts-view.js');
+ await renderAlertsView(root, state);
}
}
@@ -406,6 +424,12 @@ document.addEventListener('DOMContentLoaded', () => {
if (needsRefresh) {
void renderCurrentView();
}
+ } else if (frame.type === 'alerts:update') {
+ state.activeAlertCount = frame.activeCount;
+ updateTopBarUi();
+ if (state.authenticated && state.route === 'alerts') {
+ void renderCurrentView();
+ }
}
});
diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts
index ab52baa..cd0f705 100644
--- a/src/client/ts/state.ts
+++ b/src/client/ts/state.ts
@@ -103,6 +103,7 @@ export interface ClientState {
safeMode: boolean;
defaultMobileSafeMode: boolean;
elevatedUntil: number | null;
+ activeAlertCount: number;
theme: string;
route: RouteId;
selectedServerId?: string;
diff --git a/src/client/ts/views/alerts-view.ts b/src/client/ts/views/alerts-view.ts
new file mode 100644
index 0000000..90cbec1
--- /dev/null
+++ b/src/client/ts/views/alerts-view.ts
@@ -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 {
+ root.replaceChildren();
+ const [data, credsRes] = await Promise.all([
+ apiFetch('/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);
+}
diff --git a/src/client/ts/views/dashboard-view.ts b/src/client/ts/views/dashboard-view.ts
index 84a1b3f..2e4c106 100644
--- a/src/client/ts/views/dashboard-view.ts
+++ b/src/client/ts/views/dashboard-view.ts
@@ -229,7 +229,20 @@ export async function renderDashboardView(
state: ClientState,
): Promise {
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(
diff --git a/src/client/ts/views/section-shells.ts b/src/client/ts/views/section-shells.ts
deleted file mode 100644
index d6f2b7e..0000000
--- a/src/client/ts/views/section-shells.ts
+++ /dev/null
@@ -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/.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);
-}
diff --git a/src/client/ts/views/systems-view.ts b/src/client/ts/views/systems-view.ts
index be72041..7491f6f 100644
--- a/src/client/ts/views/systems-view.ts
+++ b/src/client/ts/views/systems-view.ts
@@ -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 => {
+ 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;
}
diff --git a/src/client/ts/views/workflows-view.ts b/src/client/ts/views/workflows-view.ts
new file mode 100644
index 0000000..52030d8
--- /dev/null
+++ b/src/client/ts/views/workflows-view.ts
@@ -0,0 +1,1185 @@
+import type { ServerWsFrame } from '../../../shared/ws-protocol.js';
+import { apiFetch } from '../api.js';
+import { confirmDialog } from '../dialogs.js';
+import {
+ el,
+ extractErrorMessage,
+ fmtTime,
+ type ClientState,
+ type ServerEntry,
+} from '../state.js';
+import type { MultiplexWsClient } from '../ws-client.js';
+
+type WfSubTab = 'workflows' | 'broadcast' | 'snippets';
+
+interface WorkflowInputDef {
+ name: string;
+ type: 'string' | 'number' | 'boolean' | 'server' | 'select';
+ label?: string;
+ description?: string;
+ required?: boolean;
+ default?: string | number | boolean;
+ options?: string[];
+}
+
+interface WorkflowStepDef {
+ id: string;
+ type: 'exec' | 'read-file' | 'system-action' | 'transfer';
+ dependsOn?: Array;
+ target?: { serverId?: string; tags?: string[]; all?: boolean };
+ command?: string;
+ path?: string;
+ tailLines?: number | string;
+ systemId?: string;
+ action?: string;
+ item?: string;
+ subItem?: string;
+ mode?: 'hub-relayed' | 'direct';
+ source?: { serverId: string; path: string };
+ destination?: { serverId: string; path: string };
+ timeoutSec?: number;
+ sudo?: boolean;
+ captureAs?: string;
+ onFailure?: string | { action: string; channelId?: string; workflowId?: string };
+}
+
+interface WorkflowConfigItem {
+ id: string;
+ name: string;
+ description?: string;
+ enabled: boolean;
+ trigger:
+ | { type: 'manual' }
+ | { type: 'cron'; expression: string; timezone: string }
+ | { type: 'event'; event: string };
+ overlapPolicy: 'skip' | 'queue' | 'cancel-previous';
+ stopOnError?: boolean;
+ concurrency?: number;
+ display: { mode: 'log' | 'file-view' | 'json' | 'table' | 'summary'; syntax?: string; pinToDashboard?: boolean };
+ pinToDashboard?: boolean;
+ inputs: WorkflowInputDef[];
+ steps: WorkflowStepDef[];
+}
+
+interface WorkflowRunItem {
+ runId: string;
+ workflowId: string;
+ triggerSource: string;
+ status: string;
+ startedAt: number;
+ finishedAt: number | null;
+ cancelledBy: string | null;
+}
+
+interface WorkflowStepLogItem {
+ id: number;
+ runId: string;
+ stepId: string;
+ serverId: string;
+ exitCode: number | null;
+ durationMs: number;
+ stdout: string;
+ stderr: string;
+}
+
+interface WorkflowSummaryEntry {
+ workflow: WorkflowConfigItem;
+ nextRunAt: number | null;
+ activeRunId: string | null;
+ queuedCount: number;
+ latestRun: WorkflowRunItem | null;
+ latestStepLogs: WorkflowStepLogItem[];
+}
+
+interface SnippetItem {
+ id: string;
+ name: string;
+ description?: string;
+ command: string;
+ tags: string[];
+ inputs: WorkflowInputDef[];
+ sudo: boolean;
+ confirm: boolean;
+}
+
+let activeSubTab: WfSubTab = 'workflows';
+let selectedRunDetailId: string | null = null;
+let broadcastPresetSnippetId: string | null = null;
+let unsubWfWs: (() => void) | null = null;
+
+function statusBadgeClass(status: string): string {
+ if (status === 'succeeded' || status === 'ok') return 'badge badge-ok';
+ if (status === 'running' || status === 'queued' || status === 'pending') return 'badge badge-warn';
+ if (status === 'failed' || status === 'error' || status === 'cancelled') return 'badge badge-err';
+ return 'badge';
+}
+
+function renderStructuredOutput(
+ host: HTMLElement,
+ wf: WorkflowConfigItem | null,
+ run: WorkflowRunItem,
+ stepLogs: WorkflowStepLogItem[],
+): void {
+ host.replaceChildren();
+ const mode = wf?.display?.mode ?? 'log';
+ const hdr = el(
+ 'div',
+ { class: 'row-between' },
+ el('strong', {}, `Run ${run.runId} (${run.workflowId}) — Display: ${mode}`),
+ el('span', { class: statusBadgeClass(run.status) }, `[${run.status.toUpperCase()}]`),
+ );
+ host.append(hdr);
+
+ if (stepLogs.length === 0) {
+ host.append(el('p', { class: 'muted' }, 'No step logs recorded for this run yet.'));
+ return;
+ }
+
+ if (mode === 'summary') {
+ const okCount = stepLogs.filter((l) => l.exitCode === 0).length;
+ const failCount = stepLogs.length - okCount;
+ const totalMs = stepLogs.reduce((acc, l) => acc + l.durationMs, 0);
+ host.append(
+ el(
+ 'div',
+ { class: 'metric-grid', style: 'margin-top:8px' },
+ el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'PASSED'), el('div', { class: 'metric-val ok-text' }, String(okCount))),
+ el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'FAILED'), el('div', { class: 'metric-val err-text' }, String(failCount))),
+ el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'TOTAL STEPS'), el('div', { class: 'metric-val' }, String(stepLogs.length))),
+ el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'DURATION'), el('div', { class: 'metric-val mono' }, `${totalMs}ms`)),
+ ),
+ );
+ const last = stepLogs[stepLogs.length - 1];
+ if (last?.stdout) {
+ host.append(el('pre', { class: 'stream-log mono', style: 'margin-top:8px' }, last.stdout.trim().slice(-2000)));
+ }
+ return;
+ }
+
+ if (mode === 'json') {
+ const outObj = stepLogs.map((l) => {
+ let parsed: unknown = l.stdout.trim();
+ try {
+ parsed = JSON.parse(l.stdout);
+ } catch {
+ // Leave as text
+ }
+ return {
+ stepId: l.stepId,
+ serverId: l.serverId,
+ exitCode: l.exitCode,
+ durationMs: l.durationMs,
+ stdout: parsed,
+ stderr: l.stderr.trim() || undefined,
+ };
+ });
+ host.append(el('pre', { class: 'diff-body mono', style: 'margin-top:8px' }, JSON.stringify(outObj, null, 2)));
+ return;
+ }
+
+ if (mode === 'table') {
+ const tbl = el('table');
+ tbl.append(
+ el('thead', {}, el('tr', {}, el('th', {}, 'Step'), el('th', {}, 'Server'), el('th', {}, 'Exit'), el('th', {}, 'Time'), el('th', {}, 'Output'))),
+ );
+ const tbody = el('tbody');
+ for (const l of stepLogs) {
+ tbody.append(
+ el(
+ 'tr',
+ {},
+ el('td', { class: 'mono' }, l.stepId),
+ el('td', { class: 'mono' }, l.serverId),
+ el('td', {}, el('span', { class: statusBadgeClass(l.exitCode === 0 ? 'ok' : 'error') }, String(l.exitCode ?? '—'))),
+ el('td', { class: 'mono' }, `${l.durationMs}ms`),
+ el('td', { class: 'mono' }, (l.stdout || l.stderr || '—').trim().slice(0, 140)),
+ ),
+ );
+ }
+ tbl.append(tbody);
+ host.append(el('div', { class: 'table-wrap', style: 'margin-top:8px' }, tbl));
+ return;
+ }
+
+ if (mode === 'file-view') {
+ const combined = stepLogs
+ .map((l) => `# === ${l.stepId} @ ${l.serverId} ===\n${l.stdout}${l.stderr ? `\n[stderr] ${l.stderr}` : ''}`)
+ .join('\n');
+ host.append(el('pre', { class: 'diff-body mono', style: 'margin-top:8px', 'data-syntax': wf?.display?.syntax ?? 'log' }, combined));
+ return;
+ }
+
+ // Default 'log' mode
+ const logText = stepLogs
+ .map((l) => `[${l.stepId} @ ${l.serverId}] exit=${String(l.exitCode)} (${l.durationMs}ms)\n${l.stdout}${l.stderr ? `[stderr]\n${l.stderr}\n` : ''}`)
+ .join('\n');
+ host.append(el('pre', { class: 'stream-log mono', style: 'margin-top:8px' }, logText));
+}
+
+async function promptWorkflowInputs(
+ wfName: string,
+ defs: WorkflowInputDef[],
+ servers: ServerEntry[],
+): Promise | null> {
+ if (defs.length === 0) return {};
+
+ return new Promise((resolve) => {
+ const dialog = document.createElement('dialog');
+ dialog.className = 'dialog-wide';
+ dialog.setAttribute('aria-labelledby', 'wf-inputs-title');
+ const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Cancel');
+ const fields = new Map();
+ const formFields = el('div', { class: 'stack' });
+
+ for (const def of defs) {
+ let ctrl: HTMLInputElement | HTMLSelectElement;
+ if (def.type === 'server') {
+ const sel = el('select', { required: def.required });
+ for (const s of servers) {
+ sel.append(el('option', { value: s.config.id, selected: def.default === s.config.id }, `${s.config.name} (${s.config.id})`));
+ }
+ ctrl = sel;
+ } else if (def.type === 'select' && def.options) {
+ const sel = el('select', { required: def.required });
+ for (const o of def.options) {
+ sel.append(el('option', { value: o, selected: def.default === o }, o));
+ }
+ ctrl = sel;
+ } else if (def.type === 'boolean') {
+ ctrl = el('input', { type: 'checkbox', checked: Boolean(def.default) });
+ } else {
+ ctrl = el('input', {
+ type: def.type === 'number' ? 'number' : 'text',
+ value: def.default !== undefined ? String(def.default) : '',
+ required: def.required,
+ placeholder: def.description ?? def.name,
+ });
+ }
+ fields.set(def.name, ctrl);
+ formFields.append(el('label', {}, `${def.label ?? def.name} (${def.type})`), ctrl);
+ }
+
+ const form = el(
+ 'form',
+ { class: 'stack' },
+ formFields,
+ el('div', { class: 'dialog-actions' }, closeBtn, el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Execute')),
+ );
+
+ let done = false;
+ const finish = (val: Record | null) => {
+ if (done) return;
+ done = true;
+ if (dialog.open) dialog.close();
+ dialog.remove();
+ resolve(val);
+ };
+
+ closeBtn.addEventListener('click', () => finish(null));
+ dialog.addEventListener('close', () => finish(null));
+ form.addEventListener('submit', (ev) => {
+ ev.preventDefault();
+ const values: Record = {};
+ for (const def of defs) {
+ const node = fields.get(def.name)!;
+ if (def.type === 'boolean') values[def.name] = (node as HTMLInputElement).checked;
+ else if (def.type === 'number') values[def.name] = Number(node.value);
+ else values[def.name] = node.value;
+ }
+ finish(values);
+ });
+
+ dialog.append(el('h1', { id: 'wf-inputs-title' }, `Inputs: ${wfName}`), form);
+ document.body.append(dialog);
+ dialog.showModal();
+ });
+}
+
+function openWorkflowEditorDialog(
+ existing: WorkflowConfigItem | null,
+ servers: ServerEntry[],
+ systems: Array<{ system: { id: string; name: string; actions: Array<{ id: string; label: string }> } }>,
+ onSaved: () => Promise,
+): void {
+ const dialog = document.createElement('dialog');
+ dialog.className = 'dialog-wide';
+ dialog.setAttribute('aria-labelledby', 'wf-edit-title');
+
+ const idInput = el('input', {
+ value: existing?.id ?? '',
+ placeholder: 'nightly-health-check',
+ readonly: Boolean(existing),
+ required: true,
+ });
+ const nameInput = el('input', {
+ value: existing?.name ?? '',
+ placeholder: 'Nightly Health Check',
+ required: true,
+ });
+ const descInput = el('input', {
+ value: existing?.description ?? '',
+ placeholder: 'Optional description',
+ });
+ const enabledChk = el('input', {
+ type: 'checkbox',
+ checked: existing ? existing.enabled : true,
+ });
+ const trigSel = el(
+ 'select',
+ {},
+ el('option', { value: 'manual', selected: !existing || existing.trigger.type === 'manual' }, 'manual'),
+ el('option', { value: 'cron', selected: existing?.trigger.type === 'cron' }, 'cron'),
+ el('option', { value: 'event', selected: existing?.trigger.type === 'event' }, 'event'),
+ );
+ const cronExprInput = el('input', {
+ value: existing?.trigger.type === 'cron' ? existing.trigger.expression : '0 * * * *',
+ placeholder: '0 3 * * *',
+ });
+ const cronTzInput = el('input', {
+ value: existing?.trigger.type === 'cron' ? existing.trigger.timezone : 'UTC',
+ placeholder: 'UTC',
+ });
+ const eventSel = el(
+ 'select',
+ {},
+ ...['server.offline', 'server.online', 'probe.failed', 'system.unhealthy', 'alert.fired'].map(
+ (evName) =>
+ el(
+ 'option',
+ {
+ value: evName,
+ selected: existing?.trigger.type === 'event' && existing.trigger.event === evName,
+ },
+ evName,
+ ),
+ ),
+ );
+ const trigDetailBox = el('div', { class: 'grid-2' });
+ const redrawTrigDetail = () => {
+ trigDetailBox.replaceChildren();
+ if (trigSel.value === 'cron') {
+ trigDetailBox.append(
+ el('div', {}, el('label', {}, 'Cron Expression'), cronExprInput),
+ el('div', {}, el('label', {}, 'Timezone'), cronTzInput),
+ );
+ } else if (trigSel.value === 'event') {
+ trigDetailBox.append(el('div', {}, el('label', {}, 'System Event'), eventSel));
+ }
+ };
+ trigSel.addEventListener('change', redrawTrigDetail);
+ redrawTrigDetail();
+
+ const overlapSel = el(
+ 'select',
+ {},
+ el('option', { value: 'skip', selected: !existing || existing.overlapPolicy === 'skip' }, 'skip'),
+ el('option', { value: 'queue', selected: existing?.overlapPolicy === 'queue' }, 'queue'),
+ el('option', { value: 'cancel-previous', selected: existing?.overlapPolicy === 'cancel-previous' }, 'cancel-previous'),
+ );
+ const displaySel = el(
+ 'select',
+ {},
+ ...(['log', 'file-view', 'json', 'table', 'summary'] as const).map((m) =>
+ el('option', { value: m, selected: (existing?.display.mode ?? 'log') === m }, m),
+ ),
+ );
+ const stopOnErrChk = el('input', {
+ type: 'checkbox',
+ checked: existing ? existing.stopOnError !== false : true,
+ });
+ const pinChk = el('input', {
+ type: 'checkbox',
+ checked: Boolean(existing?.display.pinToDashboard || existing?.pinToDashboard),
+ });
+
+ const draftSteps: WorkflowStepDef[] = existing?.steps
+ ? existing.steps.map((s) => ({ ...s }))
+ : [
+ {
+ id: 'step-1',
+ type: 'exec',
+ target: { all: true },
+ command: 'uname -a',
+ sudo: false,
+ },
+ ];
+
+ const stepsHost = el('div', { class: 'stack' });
+ const redrawSteps = () => {
+ stepsHost.replaceChildren();
+ draftSteps.forEach((step, idx) => {
+ const card = el('div', { class: 'panel' });
+ const sId = el('input', { class: 'input-sm', value: step.id, placeholder: 'step-id' });
+ sId.addEventListener('input', () => {
+ step.id = sId.value.trim();
+ });
+
+ const sType = el(
+ 'select',
+ { class: 'input-sm' },
+ ...(['exec', 'read-file', 'system-action', 'transfer'] as const).map((t) =>
+ el('option', { value: t, selected: step.type === t }, t),
+ ),
+ );
+ sType.addEventListener('change', () => {
+ step.type = sType.value as WorkflowStepDef['type'];
+ if (step.type === 'transfer' && !step.source) {
+ step.mode = 'hub-relayed';
+ step.source = { serverId: servers[0]?.config.id ?? 'srv-1', path: '/tmp/file' };
+ step.destination = { serverId: servers[0]?.config.id ?? 'srv-1', path: '/tmp/file.bak' };
+ }
+ redrawSteps();
+ });
+
+ const depsVal = (step.dependsOn ?? [])
+ .map((d) => (typeof d === 'string' ? d : d.on === 'success' ? d.stepId : `${d.stepId}:${d.on}`))
+ .join(', ');
+ const sDeps = el('input', {
+ class: 'input-sm',
+ value: depsVal,
+ placeholder: 'dependsOn (e.g. step-1, step-2:failure)',
+ });
+ sDeps.addEventListener('input', () => {
+ const tokens = sDeps.value
+ .split(',')
+ .map((x) => x.trim())
+ .filter(Boolean);
+ step.dependsOn = tokens.map((tok) => {
+ const [stepId, onRaw] = tok.split(':');
+ if (onRaw === 'failure' || onRaw === 'always' || onRaw === 'success') {
+ return { stepId: stepId!, on: onRaw };
+ }
+ return stepId!;
+ });
+ });
+
+ const rmBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Remove');
+ rmBtn.addEventListener('click', () => {
+ if (draftSteps.length <= 1) return;
+ draftSteps.splice(idx, 1);
+ redrawSteps();
+ });
+
+ card.append(
+ el(
+ 'div',
+ { class: 'row-between' },
+ el('strong', {}, `Step #${idx + 1}`),
+ el('div', { class: 'row' }, sId, sType, rmBtn),
+ ),
+ sDeps,
+ );
+
+ if (step.type === 'transfer') {
+ const modeSel = el(
+ 'select',
+ { class: 'input-sm' },
+ el('option', { value: 'hub-relayed', selected: (step.mode ?? 'hub-relayed') === 'hub-relayed' }, 'hub-relayed'),
+ el('option', { value: 'direct', selected: step.mode === 'direct' }, 'direct (rsync)'),
+ );
+ const srcSrv = el('input', { class: 'input-sm', value: step.source?.serverId ?? '', placeholder: 'Source Server ID' });
+ const srcPath = el('input', { class: 'input-sm', value: step.source?.path ?? '', placeholder: 'Source Path' });
+ const dstSrv = el('input', { class: 'input-sm', value: step.destination?.serverId ?? '', placeholder: 'Dest Server ID' });
+ const dstPath = el('input', { class: 'input-sm', value: step.destination?.path ?? '', placeholder: 'Dest Path' });
+ const syncXfer = () => {
+ step.mode = modeSel.value as 'hub-relayed' | 'direct';
+ step.source = { serverId: srcSrv.value.trim(), path: srcPath.value.trim() };
+ step.destination = { serverId: dstSrv.value.trim(), path: dstPath.value.trim() };
+ };
+ [modeSel, srcSrv, srcPath, dstSrv, dstPath].forEach((n) => n.addEventListener('input', syncXfer));
+ card.append(
+ el('div', { class: 'grid-2', style: 'margin-top:6px' }, srcSrv, srcPath, dstSrv, dstPath),
+ el('div', { class: 'row', style: 'margin-top:6px' }, el('span', { class: 'muted' }, 'Mode:'), modeSel),
+ );
+ } else {
+ const tgtVal = step.target?.all
+ ? 'all'
+ : step.target?.tags?.length
+ ? `tags:${step.target.tags.join(',')}`
+ : step.target?.serverId ?? 'all';
+ const tgtInput = el('input', {
+ class: 'input-sm',
+ value: tgtVal,
+ placeholder: 'all | server-id | tags:prod,web',
+ });
+ tgtInput.addEventListener('input', () => {
+ const v = tgtInput.value.trim();
+ if (!v || v === 'all') step.target = { all: true };
+ else if (v.startsWith('tags:')) {
+ step.target = { tags: v.slice(5).split(',').map((t) => t.trim()).filter(Boolean) };
+ } else {
+ step.target = { serverId: v };
+ }
+ });
+
+ const sudoChk = el('input', { type: 'checkbox', checked: Boolean(step.sudo) });
+ sudoChk.addEventListener('change', () => {
+ step.sudo = sudoChk.checked;
+ });
+
+ const capInput = el('input', {
+ class: 'input-sm',
+ value: step.captureAs ?? '',
+ placeholder: 'captureAs (optional)',
+ });
+ capInput.addEventListener('input', () => {
+ step.captureAs = capInput.value.trim() || undefined;
+ });
+
+ card.append(
+ el('div', { class: 'row', style: 'margin-top:6px' }, el('span', { class: 'muted' }, 'Target:'), tgtInput, el('label', { class: 'chk-row' }, sudoChk, 'sudo'), capInput),
+ );
+
+ if (step.type === 'exec') {
+ const cmdArea = el('textarea', { rows: 2, placeholder: 'Shell command (e.g. df -h)' }, step.command ?? '');
+ cmdArea.value = step.command ?? '';
+ cmdArea.addEventListener('input', () => {
+ step.command = cmdArea.value;
+ });
+ card.append(cmdArea);
+ } else if (step.type === 'read-file') {
+ const pIn = el('input', { class: 'input-sm', value: step.path ?? '/var/log/syslog', placeholder: 'Remote file path' });
+ const tailIn = el('input', { class: 'input-sm', value: step.tailLines !== undefined ? String(step.tailLines) : '', placeholder: 'tailLines (optional)' });
+ pIn.addEventListener('input', () => {
+ step.path = pIn.value.trim();
+ });
+ tailIn.addEventListener('input', () => {
+ const raw = tailIn.value.trim();
+ step.tailLines = !raw ? undefined : /^\d+$/.test(raw) ? Number(raw) : raw;
+ });
+ card.append(el('div', { class: 'grid-2', style: 'margin-top:6px' }, pIn, tailIn));
+ } else {
+ const sysIn = el('input', {
+ class: 'input-sm',
+ value: step.systemId ?? systems[0]?.system.id ?? 'docker-compose',
+ placeholder: 'systemId',
+ });
+ const actIn = el('input', {
+ class: 'input-sm',
+ value: step.action ?? systems[0]?.system.actions[0]?.id ?? 'restart',
+ placeholder: 'action',
+ });
+ const itemIn = el('input', {
+ class: 'input-sm',
+ value: step.item ?? '*',
+ placeholder: 'item or *',
+ });
+ const syncSys = () => {
+ step.systemId = sysIn.value.trim();
+ step.action = actIn.value.trim();
+ step.item = itemIn.value.trim() || '*';
+ };
+ [sysIn, actIn, itemIn].forEach((n) => n.addEventListener('input', syncSys));
+ syncSys();
+ card.append(el('div', { class: 'grid-3', style: 'margin-top:6px' }, sysIn, actIn, itemIn));
+ }
+ }
+ stepsHost.append(card);
+ });
+ };
+ redrawSteps();
+
+ const addStepBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '+ Add Step');
+ addStepBtn.addEventListener('click', () => {
+ draftSteps.push({
+ id: `step-${draftSteps.length + 1}`,
+ type: 'exec',
+ target: { all: true },
+ command: 'echo ok',
+ sudo: false,
+ });
+ redrawSteps();
+ });
+
+ const msgEl = el('p', { class: 'form-msg err-text' });
+ const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Cancel');
+ closeBtn.addEventListener('click', () => {
+ if (dialog.open) dialog.close();
+ });
+
+ const form = el(
+ 'form',
+ { class: 'stack' },
+ el('div', { class: 'grid-2' },
+ el('div', {}, el('label', {}, 'Workflow ID'), idInput),
+ el('div', {}, el('label', {}, 'Name'), nameInput),
+ ),
+ el('div', {}, el('label', {}, 'Description'), descInput),
+ el('div', { class: 'grid-3' },
+ el('div', {}, el('label', {}, 'Trigger'), trigSel),
+ el('div', {}, el('label', {}, 'Overlap Policy'), overlapSel),
+ el('div', {}, el('label', {}, 'Display Mode'), displaySel),
+ ),
+ trigDetailBox,
+ el('div', { class: 'row' },
+ el('label', { class: 'chk-row' }, enabledChk, 'Enabled'),
+ el('label', { class: 'chk-row' }, stopOnErrChk, 'Stop on Error'),
+ el('label', { class: 'chk-row' }, pinChk, 'Pin to Dashboard'),
+ ),
+ el('div', { class: 'row-between' }, el('h2', {}, 'DAG Steps'), addStepBtn),
+ stepsHost,
+ msgEl,
+ el('div', { class: 'dialog-actions' }, closeBtn, el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Save Workflow')),
+ );
+
+ form.addEventListener('submit', async (ev) => {
+ ev.preventDefault();
+ msgEl.textContent = '';
+
+ const trigger =
+ trigSel.value === 'cron'
+ ? { type: 'cron', expression: cronExprInput.value.trim(), timezone: cronTzInput.value.trim() || 'UTC' }
+ : trigSel.value === 'event'
+ ? { type: 'event', event: eventSel.value }
+ : { type: 'manual' };
+
+ const payload = {
+ id: idInput.value.trim(),
+ name: nameInput.value.trim(),
+ description: descInput.value.trim() || undefined,
+ enabled: enabledChk.checked,
+ trigger,
+ overlapPolicy: overlapSel.value,
+ stopOnError: stopOnErrChk.checked,
+ display: {
+ mode: displaySel.value,
+ pinToDashboard: pinChk.checked,
+ },
+ pinToDashboard: pinChk.checked,
+ inputs: existing?.inputs ?? [],
+ steps: draftSteps,
+ };
+
+ try {
+ await apiFetch(
+ existing ? `/api/workflows/${encodeURIComponent(existing.id)}` : '/api/workflows',
+ { method: existing ? 'PUT' : 'POST', body: payload },
+ );
+ if (dialog.open) dialog.close();
+ await onSaved();
+ } catch (err) {
+ msgEl.textContent = extractErrorMessage(err);
+ }
+ });
+
+ dialog.append(el('h1', { id: 'wf-edit-title' }, existing ? `Edit Workflow: ${existing.id}` : 'Create Workflow'), form);
+ dialog.addEventListener('close', () => dialog.remove());
+ document.body.append(dialog);
+ dialog.showModal();
+}
+
+export async function renderWorkflowsView(
+ root: HTMLElement,
+ state: ClientState,
+ wsClient: MultiplexWsClient,
+): Promise {
+ if (unsubWfWs) {
+ unsubWfWs();
+ unsubWfWs = null;
+ }
+ wsClient.subscribe(['workflows']);
+ root.replaceChildren();
+
+ const tabBar = el(
+ 'div',
+ { class: 'row' },
+ ...([
+ ['workflows', 'Workflows & Runs'],
+ ['broadcast', 'Ad-Hoc Fleet Broadcast'],
+ ['snippets', 'Command Snippets'],
+ ] as const).map(([id, label]) => {
+ const btn = el(
+ 'button',
+ { type: 'button', class: `btn btn-sm${activeSubTab === id ? ' btn-primary' : ''}` },
+ label,
+ );
+ btn.addEventListener('click', () => {
+ activeSubTab = id;
+ void renderWorkflowsView(root, state, wsClient);
+ });
+ return btn;
+ }),
+ );
+
+ root.append(
+ el(
+ 'section',
+ { class: 'panel row-between' },
+ el('div', {}, el('h1', {}, 'Automation, Broadcast & Snippets'), el('p', { class: 'muted' }, 'DAG workflows, croner triggers, hub-relayed transfers, and saved snippets.')),
+ tabBar,
+ ),
+ );
+
+ const [serversRes, snippetsRes] = await Promise.all([
+ apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
+ apiFetch<{ snippets: SnippetItem[] }>('/api/snippets'),
+ ]);
+ const servers = serversRes.servers;
+ const snippets = snippetsRes.snippets;
+
+ if (activeSubTab === 'workflows') {
+ const [wfRes, runsRes, sysRes] = await Promise.all([
+ apiFetch<{ workflows: WorkflowSummaryEntry[] }>('/api/workflows'),
+ apiFetch<{ runs: WorkflowRunItem[] }>('/api/workflows/runs?limit=25'),
+ apiFetch<{ systems: Array<{ system: { id: string; name: string; actions: Array<{ id: string; label: string }> } }> }>('/api/systems'),
+ ]);
+
+ const previewBox = el('section', { class: 'panel', hidden: true });
+ const streamPanel = el('section', { class: 'panel', hidden: true });
+ const detailPanel = el('section', { class: 'panel', hidden: true });
+
+ const newBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, '+ New Workflow');
+ newBtn.addEventListener('click', () => {
+ openWorkflowEditorDialog(null, servers, sysRes.systems, () => renderWorkflowsView(root, state, wsClient));
+ });
+ const refBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh');
+ refBtn.addEventListener('click', () => {
+ void renderWorkflowsView(root, state, wsClient);
+ });
+
+ const wfSection = el('section', { class: 'panel panel-region' });
+ wfSection.append(el('div', { class: 'row-between' }, el('h2', {}, `Configured Workflows (${wfRes.workflows.length})`), el('div', { class: 'row' }, newBtn, refBtn)));
+
+ const watchRunStream = (runId: string, wfId: string) => {
+ streamPanel.hidden = false;
+ const logPre = el('pre', { class: 'stream-log mono' }, `Subscribed to live run ${runId} (${wfId})...\n`);
+ const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Cancel Run');
+ cancelBtn.addEventListener('click', async () => {
+ cancelBtn.disabled = true;
+ await apiFetch(`/api/workflows/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' });
+ });
+ streamPanel.replaceChildren(
+ el('div', { class: 'row-between' }, el('strong', {}, `Live Run Stream: ${wfId} (${runId})`), cancelBtn),
+ logPre,
+ );
+
+ if (unsubWfWs) unsubWfWs();
+ unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => {
+ if (frame.type === 'stream:chunk' && frame.jobId === `wf:${runId}`) {
+ if (frame.stream !== 'meta') {
+ logPre.textContent += frame.data;
+ logPre.scrollTop = logPre.scrollHeight;
+ } else {
+ try {
+ const m = JSON.parse(frame.data) as { event?: string; status?: string };
+ if (m.event === 'done') {
+ cancelBtn.disabled = true;
+ selectedRunDetailId = runId;
+ void loadRunDetail(runId);
+ }
+ } catch {
+ // Ignore meta parse error
+ }
+ }
+ }
+ });
+ wsClient.subscribe([`stream:wf:${runId}`]);
+ };
+
+ const loadRunDetail = async (runId: string) => {
+ const res = await apiFetch<{
+ run: WorkflowRunItem;
+ stepLogs: WorkflowStepLogItem[];
+ workflow: WorkflowConfigItem | null;
+ }>(`/api/workflows/runs/${encodeURIComponent(runId)}`);
+ detailPanel.hidden = false;
+ renderStructuredOutput(detailPanel, res.workflow, res.run, res.stepLogs);
+ };
+
+ if (wfRes.workflows.length === 0) {
+ wfSection.append(el('p', { class: 'muted' }, 'No workflows configured yet. Click "+ New Workflow" to create one.'));
+ } else {
+ for (const item of wfRes.workflows) {
+ const wf = item.workflow;
+ const trigText =
+ wf.trigger.type === 'cron'
+ ? `CRON "${wf.trigger.expression}" (${wf.trigger.timezone}) | Next: ${fmtTime(item.nextRunAt)}`
+ : wf.trigger.type === 'event'
+ ? `EVENT: ${wf.trigger.event}`
+ : 'MANUAL';
+
+ const dryBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Dry-Run');
+ dryBtn.addEventListener('click', async () => {
+ const inp = await promptWorkflowInputs(wf.name, wf.inputs, servers);
+ if (!inp) return;
+ const dry = await apiFetch<{
+ plan: {
+ workflowId: string;
+ inputs: Record;
+ steps: Array<{
+ stepId: string;
+ type: string;
+ wave: number;
+ targets: Array<{ serverId: string }>;
+ renderedCommand?: string;
+ renderedPath?: string;
+ transferPreview?: { mode: string; sourceServerId: string; sourcePath: string; destinationServerId: string; destinationPath: string };
+ }>;
+ };
+ }>(`/api/workflows/${encodeURIComponent(wf.id)}/dry-run`, {
+ method: 'POST',
+ body: { inputs: inp },
+ });
+ const closePreviewBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close');
+ closePreviewBtn.addEventListener('click', () => { previewBox.hidden = true; });
+ previewBox.hidden = false;
+ previewBox.replaceChildren(
+ el('div', { class: 'row-between' }, el('strong', {}, `Dry-Run Preview: ${wf.name}`), closePreviewBtn),
+ el('pre', { class: 'diff-body mono', style: 'margin-top:8px' }, JSON.stringify(dry.plan, null, 2)),
+ );
+ });
+
+ const runBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Run Now');
+ runBtn.addEventListener('click', async () => {
+ const inp = await promptWorkflowInputs(wf.name, wf.inputs, servers);
+ if (!inp) return;
+ const triggered = await apiFetch<{ runId: string; status: string }>(
+ `/api/workflows/${encodeURIComponent(wf.id)}/run`,
+ { method: 'POST', body: { inputs: inp } },
+ );
+ if (triggered.status !== 'skipped') {
+ watchRunStream(triggered.runId, wf.id);
+ } else {
+ previewBox.hidden = false;
+ previewBox.replaceChildren(el('p', { class: 'warn-text' }, `Run ${triggered.runId} skipped due to overlapPolicy="skip".`));
+ }
+ });
+
+ const editBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Edit');
+ editBtn.addEventListener('click', () => {
+ openWorkflowEditorDialog(wf, servers, sysRes.systems, () => renderWorkflowsView(root, state, wsClient));
+ });
+
+ const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
+ delBtn.addEventListener('click', async () => {
+ const ok = await confirmDialog('dialog-confirm', `Delete workflow "${wf.id}"?`);
+ if (!ok) return;
+ await apiFetch(`/api/workflows/${encodeURIComponent(wf.id)}`, { method: 'DELETE' });
+ await renderWorkflowsView(root, state, wsClient);
+ });
+
+ wfSection.append(
+ el(
+ 'div',
+ { class: 'panel' },
+ el(
+ 'div',
+ { class: 'row-between' },
+ el(
+ 'div',
+ {},
+ el('strong', {}, `${wf.name} `),
+ el('span', { class: 'mono muted' }, `(${wf.id})`),
+ wf.display.pinToDashboard || wf.pinToDashboard
+ ? el('span', { class: 'badge badge-ok' }, '[PINNED]')
+ : '',
+ item.latestRun
+ ? el('span', { class: statusBadgeClass(item.latestRun.status) }, `[LAST: ${item.latestRun.status.toUpperCase()}]`)
+ : '',
+ ),
+ el('div', { class: 'row' }, dryBtn, runBtn, editBtn, delBtn),
+ ),
+ el('div', { class: 'mono muted', style: 'margin-top:4px' }, `${trigText} | Overlap: ${wf.overlapPolicy} | Mode: ${wf.display.mode} | Steps: ${wf.steps.length}${item.queuedCount > 0 ? ` | Queued: ${item.queuedCount}` : ''}`),
+ ),
+ );
+ }
+ }
+
+ const runsSection = el('section', { class: 'panel panel-region' });
+ runsSection.append(el('h2', {}, `Recent Runs (${runsRes.runs.length})`));
+ const rTbl = el('table');
+ rTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'Run ID'), el('th', {}, 'Workflow'), el('th', {}, 'Trigger'), el('th', {}, 'Status'), el('th', {}, 'Started'), el('th', {}, 'Actions'))));
+ const rBody = el('tbody');
+ if (runsRes.runs.length === 0) {
+ rBody.append(el('tr', {}, el('td', { colspan: 6, class: 'muted' }, 'No workflow runs yet.')));
+ } else {
+ for (const r of runsRes.runs) {
+ const inspectBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Output');
+ inspectBtn.addEventListener('click', () => {
+ selectedRunDetailId = r.runId;
+ void loadRunDetail(r.runId);
+ });
+ const actRow = el('div', { class: 'row' }, inspectBtn);
+ if (r.status === 'running' || r.status === 'queued') {
+ const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Cancel');
+ cancelBtn.addEventListener('click', async () => {
+ await apiFetch(`/api/workflows/runs/${encodeURIComponent(r.runId)}/cancel`, { method: 'POST' });
+ await renderWorkflowsView(root, state, wsClient);
+ });
+ actRow.append(cancelBtn);
+ }
+ rBody.append(
+ el(
+ 'tr',
+ {},
+ el('td', { class: 'mono' }, r.runId),
+ el('td', { class: 'mono' }, r.workflowId),
+ el('td', { class: 'mono' }, r.triggerSource),
+ el('td', {}, el('span', { class: statusBadgeClass(r.status) }, `[${r.status.toUpperCase()}]`)),
+ el('td', { class: 'mono' }, fmtTime(r.startedAt)),
+ el('td', {}, actRow),
+ ),
+ );
+ }
+ }
+ rTbl.append(rBody);
+ runsSection.append(el('div', { class: 'table-wrap' }, rTbl));
+
+ root.append(wfSection, previewBox, streamPanel, detailPanel, runsSection);
+ if (selectedRunDetailId) {
+ void loadRunDetail(selectedRunDetailId).catch(() => undefined);
+ }
+ return;
+ }
+
+ if (activeSubTab === 'broadcast') {
+ const panel = el('section', { class: 'panel' });
+ const modeSel = el(
+ 'select',
+ {},
+ el('option', { value: 'adhoc' }, 'Ad-Hoc Shell Command'),
+ el('option', { value: 'snippet', selected: Boolean(broadcastPresetSnippetId) }, 'Saved Command Snippet'),
+ );
+ const snipSel = el(
+ 'select',
+ {},
+ ...snippets.map((s) =>
+ el('option', { value: s.id, selected: broadcastPresetSnippetId === s.id }, `${s.name} (${s.id})`),
+ ),
+ );
+ const cmdArea = el('textarea', { rows: 3, placeholder: 'uptime && free -m' });
+ const sudoChk = el('input', { type: 'checkbox' });
+ const concInput = el('input', { type: 'number', min: 1, max: 32, value: '4' });
+ const tgtModeSel = el(
+ 'select',
+ {},
+ el('option', { value: 'all' }, 'All Enabled Servers'),
+ el('option', { value: 'tags' }, 'Filter by Tags'),
+ el('option', { value: 'selected' }, 'Select Specific Servers'),
+ );
+ const tagsInput = el('input', { placeholder: 'prod, web' });
+ const srvChecks = new Map();
+ const srvChecksBox = el('div', { class: 'chip-list' });
+ for (const s of servers.filter((x) => x.config.enabled)) {
+ const c = el('input', { type: 'checkbox', checked: true });
+ srvChecks.set(s.config.id, c);
+ srvChecksBox.append(el('label', { class: 'chk-row mono' }, c, s.config.id));
+ }
+
+ const modeBox = el('div', { class: 'stack' });
+ const tgtBox = el('div', { class: 'stack' });
+ const redrawBroadcastForm = () => {
+ modeBox.replaceChildren();
+ if (modeSel.value === 'snippet' && snippets.length > 0) {
+ const chosen = snippets.find((s) => s.id === snipSel.value);
+ modeBox.append(
+ el('label', {}, 'Snippet'),
+ snipSel,
+ el('div', { class: 'mono muted' }, chosen?.command ?? ''),
+ );
+ } else {
+ modeBox.append(el('label', {}, 'Ad-Hoc Command'), cmdArea);
+ }
+ tgtBox.replaceChildren();
+ if (tgtModeSel.value === 'tags') tgtBox.append(el('label', {}, 'Tags (comma-separated)'), tagsInput);
+ else if (tgtModeSel.value === 'selected') tgtBox.append(srvChecksBox);
+ };
+ modeSel.addEventListener('change', redrawBroadcastForm);
+ snipSel.addEventListener('change', redrawBroadcastForm);
+ tgtModeSel.addEventListener('change', redrawBroadcastForm);
+ redrawBroadcastForm();
+
+ const msgEl = el('p', { class: 'form-msg' });
+ const cardsGrid = el('div', { class: 'grid-2' });
+ const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action', hidden: true }, 'Cancel Broadcast');
+ let activeJobId: string | null = null;
+ cancelBtn.addEventListener('click', async () => {
+ if (!activeJobId) return;
+ cancelBtn.disabled = true;
+ await apiFetch(`/api/workflows/broadcast/${encodeURIComponent(activeJobId)}/cancel`, { method: 'POST' });
+ });
+
+ const form = el(
+ 'form',
+ { class: 'stack' },
+ el('div', { class: 'grid-3' },
+ el('div', {}, el('label', {}, 'Source'), modeSel),
+ el('div', {}, el('label', {}, 'Target Scope'), tgtModeSel),
+ el('div', {}, el('label', {}, 'Concurrency'), concInput),
+ ),
+ modeBox,
+ tgtBox,
+ el('div', { class: 'row-between' }, el('label', { class: 'chk-row' }, sudoChk, 'Run with sudo'), el('div', { class: 'row' }, cancelBtn, el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Run Fleet Broadcast'))),
+ msgEl,
+ );
+
+ form.addEventListener('submit', async (ev) => {
+ ev.preventDefault();
+ msgEl.textContent = '';
+ cardsGrid.replaceChildren();
+
+ const target: { all?: boolean; tags?: string[]; serverIds?: string[] } =
+ tgtModeSel.value === 'tags'
+ ? { tags: tagsInput.value.split(',').map((t) => t.trim()).filter(Boolean) }
+ : tgtModeSel.value === 'selected'
+ ? { serverIds: [...srvChecks.entries()].filter(([, chk]) => chk.checked).map(([id]) => id) }
+ : { all: true };
+
+ try {
+ const res = await apiFetch<{
+ job: {
+ jobId: string;
+ targets: Array<{ serverId: string; serverName: string; status: string }>;
+ };
+ }>('/api/workflows/broadcast', {
+ method: 'POST',
+ body: {
+ snippetId: modeSel.value === 'snippet' ? snipSel.value : undefined,
+ command: modeSel.value === 'adhoc' ? cmdArea.value : undefined,
+ sudo: sudoChk.checked,
+ concurrency: Number(concInput.value || 4),
+ target,
+ },
+ });
+
+ activeJobId = res.job.jobId;
+ cancelBtn.hidden = false;
+ cancelBtn.disabled = false;
+ const cardMap = new Map();
+
+ for (const t of res.job.targets) {
+ const badge = el('span', { class: 'badge badge-warn' }, '[PENDING]');
+ const pre = el('pre', { class: 'stream-log mono', style: 'max-height:180px' });
+ cardMap.set(t.serverId, { badge, pre });
+ cardsGrid.append(
+ el('article', { class: 'panel' }, el('div', { class: 'row-between' }, el('strong', {}, `${t.serverName} (${t.serverId})`), badge), pre),
+ );
+ }
+
+ if (unsubWfWs) unsubWfWs();
+ unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => {
+ if (frame.type !== 'stream:chunk' || frame.jobId !== activeJobId || frame.stream !== 'meta') return;
+ try {
+ const m = JSON.parse(frame.data) as {
+ event?: string;
+ serverId?: string;
+ data?: string;
+ status?: string;
+ exitCode?: number | null;
+ okCount?: number;
+ total?: number;
+ };
+ if (m.event === 'server-start' && m.serverId) {
+ const card = cardMap.get(m.serverId);
+ if (card) {
+ card.badge.className = 'badge badge-warn';
+ card.badge.textContent = '[RUNNING]';
+ }
+ } else if (m.event === 'server-output' && m.serverId && m.data) {
+ const card = cardMap.get(m.serverId);
+ if (card) {
+ card.pre.textContent += m.data;
+ card.pre.scrollTop = card.pre.scrollHeight;
+ }
+ } else if (m.event === 'server-exit' && m.serverId) {
+ const card = cardMap.get(m.serverId);
+ if (card) {
+ card.badge.className = statusBadgeClass(m.status ?? 'error');
+ card.badge.textContent = `[${String(m.status).toUpperCase()} exit=${String(m.exitCode)}]`;
+ }
+ } else if (m.event === 'done') {
+ cancelBtn.hidden = true;
+ msgEl.className = 'form-msg ok-text';
+ msgEl.textContent = `Broadcast finished: ${String(m.okCount)}/${String(m.total)} succeeded.`;
+ }
+ } catch {
+ // Ignore meta parse error
+ }
+ });
+ wsClient.subscribe([`stream:${activeJobId}`]);
+ } catch (err) {
+ msgEl.className = 'form-msg err-text';
+ msgEl.textContent = extractErrorMessage(err);
+ }
+ });
+
+ panel.append(el('h2', {}, 'Ad-Hoc Fleet Broadcast'), form);
+ root.append(panel, cardsGrid);
+ return;
+ }
+
+ // Command Snippets tab
+ const listPanel = el('section', { class: 'panel panel-region' });
+ listPanel.append(el('h2', {}, `Saved Command Snippets (${snippets.length})`));
+ const sTbl = el('table');
+ sTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'ID'), el('th', {}, 'Name'), el('th', {}, 'Command'), el('th', {}, 'Flags'), el('th', {}, 'Actions'))));
+ const sBody = el('tbody');
+ for (const s of snippets) {
+ const bcastBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary' }, 'Broadcast →');
+ bcastBtn.addEventListener('click', () => {
+ broadcastPresetSnippetId = s.id;
+ activeSubTab = 'broadcast';
+ void renderWorkflowsView(root, state, wsClient);
+ });
+ const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
+ delBtn.addEventListener('click', async () => {
+ const ok = await confirmDialog('dialog-confirm', `Delete snippet "${s.id}"?`);
+ if (!ok) return;
+ await apiFetch(`/api/snippets/${encodeURIComponent(s.id)}`, { method: 'DELETE' });
+ await renderWorkflowsView(root, state, wsClient);
+ });
+ sBody.append(
+ el(
+ 'tr',
+ {},
+ el('td', { class: 'mono' }, s.id),
+ el('td', {}, s.name),
+ el('td', { class: 'mono' }, s.command),
+ el('td', { class: 'mono' }, `${s.sudo ? 'sudo ' : ''}${s.confirm ? 'confirm ' : ''}${s.tags.join(',')}`),
+ el('td', {}, el('div', { class: 'row' }, bcastBtn, delBtn)),
+ ),
+ );
+ }
+ sTbl.append(sBody);
+ listPanel.append(el('div', { class: 'table-wrap' }, sTbl));
+
+ const addPanel = el('section', { class: 'panel' });
+ const snId = el('input', { placeholder: 'check-nginx', required: true });
+ const snName = el('input', { placeholder: 'Check Nginx Config', required: true });
+ const snCmd = el('textarea', { rows: 2, placeholder: 'nginx -t', required: true });
+ const snTags = el('input', { placeholder: 'web, diagnostics' });
+ const snSudo = el('input', { type: 'checkbox' });
+ const snMsg = el('p', { class: 'form-msg' });
+ const snForm = el(
+ 'form',
+ { class: 'stack' },
+ el('div', { class: 'grid-2' }, el('div', {}, el('label', {}, 'Snippet ID'), snId), el('div', {}, el('label', {}, 'Name'), snName)),
+ el('label', {}, 'Command'),
+ snCmd,
+ el('div', { class: 'row-between' }, el('div', { class: 'row' }, el('label', {}, 'Tags'), snTags, el('label', { class: 'chk-row' }, snSudo, 'sudo')), el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Save Snippet')),
+ snMsg,
+ );
+ snForm.addEventListener('submit', async (ev) => {
+ ev.preventDefault();
+ snMsg.textContent = '';
+ try {
+ await apiFetch('/api/snippets', {
+ method: 'POST',
+ body: {
+ id: snId.value.trim(),
+ name: snName.value.trim(),
+ command: snCmd.value.trim(),
+ tags: snTags.value.split(',').map((t) => t.trim()).filter(Boolean),
+ sudo: snSudo.checked,
+ inputs: [],
+ },
+ });
+ await renderWorkflowsView(root, state, wsClient);
+ } catch (err) {
+ snMsg.className = 'form-msg err-text';
+ snMsg.textContent = extractErrorMessage(err);
+ }
+ });
+ addPanel.append(el('h2', {}, 'Add Command Snippet'), snForm);
+ root.append(listPanel, addPanel);
+}
diff --git a/src/client/ts/ws-client.ts b/src/client/ts/ws-client.ts
index cd84612..507dcbb 100644
--- a/src/client/ts/ws-client.ts
+++ b/src/client/ts/ws-client.ts
@@ -8,7 +8,7 @@ export class MultiplexWsClient {
private reconnectTimer: number | null = null;
private pingTimer: number | null = null;
private shouldRun = false;
- private channels = new Set(['config', 'alerts', 'metrics']);
+ private channels = new Set(['config', 'alerts', 'metrics', 'workflows']);
private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>();
private readonly statusListeners = new Set<(status: WsConnectionStatus) => void>();