843 lines
30 KiB
TypeScript
843 lines
30 KiB
TypeScript
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';
|
|
|
|
interface SystemActionDef {
|
|
id: string;
|
|
label: string;
|
|
scope: 'system' | 'item' | 'subitem';
|
|
mode: 'oneshot' | 'stream' | 'interactive';
|
|
sudo: boolean;
|
|
confirm: boolean;
|
|
}
|
|
|
|
interface SystemParamDef {
|
|
name: string;
|
|
type: 'string' | 'number' | 'boolean' | 'string[]';
|
|
default?: unknown;
|
|
required: boolean;
|
|
description?: string;
|
|
}
|
|
|
|
interface SystemConfigView {
|
|
id: string;
|
|
name: string;
|
|
description?: string;
|
|
cacheTtlSec: number;
|
|
params: SystemParamDef[];
|
|
actions: SystemActionDef[];
|
|
editableFiles: string[];
|
|
}
|
|
|
|
interface DiscoveredItemView {
|
|
name: string;
|
|
dir?: string;
|
|
activeFiles: string[];
|
|
selectableFiles: string[];
|
|
editableFiles: string[];
|
|
status: {
|
|
health: 'ok' | 'warn' | 'down' | 'unknown';
|
|
subItems: Array<{ name: string; health: 'ok' | 'warn' | 'down' | 'unknown'; stateText?: string }>;
|
|
rawSummary: string;
|
|
exitCode: number | null;
|
|
};
|
|
}
|
|
|
|
interface ServerSnapshotView {
|
|
serverId: string;
|
|
systemId: string;
|
|
fetchedAt: number;
|
|
cached: boolean;
|
|
error?: string;
|
|
params: Record<string, unknown>;
|
|
items: DiscoveredItemView[];
|
|
systemHealth: 'ok' | 'warn' | 'down' | 'unknown';
|
|
}
|
|
|
|
let unsubStreamListener: (() => void) | null = null;
|
|
|
|
function healthBadgeClass(h: string): string {
|
|
if (h === 'ok') return 'badge badge-ok';
|
|
if (h === 'warn') return 'badge badge-warn';
|
|
if (h === 'down') return 'badge badge-err';
|
|
return 'badge';
|
|
}
|
|
|
|
async function openAttachModal(
|
|
system: SystemConfigView,
|
|
onSaved: () => Promise<void>,
|
|
): Promise<void> {
|
|
const serversRes = await apiFetch<{ servers: ServerEntry[] }>('/api/servers');
|
|
const dialog = document.createElement('dialog');
|
|
dialog.setAttribute('aria-labelledby', 'attach-sys-title');
|
|
|
|
const closeBtn = el('button', { type: 'button', class: 'btn btn-sm', autofocus: true }, 'Cancel');
|
|
closeBtn.addEventListener('click', () => {
|
|
if (dialog.open) dialog.close();
|
|
});
|
|
|
|
const serverSel = el('select', { name: 'serverId', required: true });
|
|
for (const s of serversRes.servers) {
|
|
serverSel.append(el('option', { value: s.config.id }, `${s.config.name} (${s.config.id})`));
|
|
}
|
|
|
|
const paramControls = new Map<string, { def: SystemParamDef; node: HTMLInputElement }>();
|
|
const fieldsBox = el('div', { class: 'stack' });
|
|
for (const p of system.params) {
|
|
const defText = Array.isArray(p.default)
|
|
? p.default.join(', ')
|
|
: p.default !== undefined
|
|
? String(p.default)
|
|
: '';
|
|
const inp = el('input', {
|
|
type: p.type === 'number' ? 'number' : p.type === 'boolean' ? 'checkbox' : 'text',
|
|
value: p.type === 'boolean' ? undefined : defText,
|
|
checked: p.type === 'boolean' ? Boolean(p.default) : undefined,
|
|
placeholder: p.description ?? p.name,
|
|
});
|
|
paramControls.set(p.name, { def: p, node: inp });
|
|
fieldsBox.append(
|
|
el('label', {}, `${p.name} (${p.type})${p.description ? ` — ${p.description}` : ''}`),
|
|
inp,
|
|
);
|
|
}
|
|
|
|
const errEl = el('p', { class: 'form-msg err-text' });
|
|
const form = el(
|
|
'form',
|
|
{ class: 'stack' },
|
|
el('label', {}, 'Target Server'),
|
|
serverSel,
|
|
fieldsBox,
|
|
errEl,
|
|
el('div', { class: 'dialog-actions' }, closeBtn, el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Attach System')),
|
|
);
|
|
|
|
form.addEventListener('submit', async (ev) => {
|
|
ev.preventDefault();
|
|
errEl.textContent = '';
|
|
if (!serverSel.value) {
|
|
errEl.textContent = 'Register a server first.';
|
|
return;
|
|
}
|
|
|
|
const paramsPayload: Record<string, unknown> = {};
|
|
for (const [name, { def, node }] of paramControls.entries()) {
|
|
if (def.type === 'boolean') paramsPayload[name] = node.checked;
|
|
else if (def.type === 'number') paramsPayload[name] = Number(node.value || 0);
|
|
else if (def.type === 'string[]') {
|
|
paramsPayload[name] = node.value
|
|
.split(/[\n,]/)
|
|
.map((s) => s.trim())
|
|
.filter(Boolean);
|
|
} else {
|
|
paramsPayload[name] = node.value;
|
|
}
|
|
}
|
|
|
|
try {
|
|
await apiFetch(
|
|
`/api/systems/${encodeURIComponent(system.id)}/servers/${encodeURIComponent(serverSel.value)}/attach`,
|
|
{ method: 'PUT', body: { params: paramsPayload } },
|
|
);
|
|
if (dialog.open) dialog.close();
|
|
await onSaved();
|
|
} catch (err) {
|
|
errEl.textContent = extractErrorMessage(err);
|
|
}
|
|
});
|
|
|
|
dialog.append(el('h1', { id: 'attach-sys-title' }, `Attach ${system.name}`), form);
|
|
dialog.addEventListener('close', () => dialog.remove());
|
|
document.body.append(dialog);
|
|
dialog.showModal();
|
|
}
|
|
|
|
async function runSystemAction(opts: {
|
|
systemId: string;
|
|
serverId: string;
|
|
action: SystemActionDef;
|
|
itemName?: string;
|
|
subItemName?: string;
|
|
outputHost: HTMLElement;
|
|
wsClient: MultiplexWsClient;
|
|
onFinished: () => Promise<void>;
|
|
}): Promise<void> {
|
|
const { action } = opts;
|
|
if (action.confirm) {
|
|
const target = opts.subItemName ?? opts.itemName ?? opts.serverId;
|
|
const ok = await confirmDialog(
|
|
'dialog-confirm',
|
|
`Run "${action.label}" (${action.mode}) on ${target}?`,
|
|
);
|
|
if (!ok) return;
|
|
}
|
|
|
|
opts.outputHost.replaceChildren(el('p', { class: 'muted mono' }, `Running ${action.label}...`));
|
|
|
|
const res = await apiFetch<
|
|
| { mode: 'oneshot'; exitCode: number | null; stdout: string; stderr: string; durationMs: number }
|
|
| { mode: 'stream'; jobId: string }
|
|
| { mode: 'interactive'; session: { sessionId: string } }
|
|
>(
|
|
`/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`,
|
|
{
|
|
method: 'POST',
|
|
body: {
|
|
itemName: opts.itemName,
|
|
subItemName: opts.subItemName,
|
|
},
|
|
},
|
|
);
|
|
|
|
if (res.mode === 'interactive') {
|
|
window.location.hash = `#terminal?session=${encodeURIComponent(res.session.sessionId)}`;
|
|
return;
|
|
}
|
|
|
|
if (res.mode === 'oneshot') {
|
|
opts.outputHost.replaceChildren(
|
|
el(
|
|
'div',
|
|
{ class: 'panel' },
|
|
el('div', { class: 'row-between' }, el('strong', {}, `${action.label} finished (exit ${String(res.exitCode)}, ${res.durationMs}ms)`)),
|
|
el('pre', { class: 'stream-log mono' }, [res.stdout, res.stderr].filter(Boolean).join('\n') || '(no output)'),
|
|
),
|
|
);
|
|
await opts.onFinished();
|
|
return;
|
|
}
|
|
|
|
// Stream mode
|
|
if (unsubStreamListener) {
|
|
unsubStreamListener();
|
|
unsubStreamListener = null;
|
|
}
|
|
|
|
const logPre = el('pre', { class: 'stream-log mono' });
|
|
const stopBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Stop Stream');
|
|
stopBtn.addEventListener('click', async () => {
|
|
await apiFetch(`/api/systems/streams/${encodeURIComponent(res.jobId)}/cancel`, { method: 'POST' });
|
|
stopBtn.disabled = true;
|
|
});
|
|
|
|
opts.outputHost.replaceChildren(
|
|
el(
|
|
'div',
|
|
{ class: 'panel' },
|
|
el('div', { class: 'row-between' }, el('strong', {}, `Live Stream: ${action.label} (${res.jobId})`), stopBtn),
|
|
logPre,
|
|
),
|
|
);
|
|
|
|
unsubStreamListener = opts.wsClient.onFrame((frame: ServerWsFrame) => {
|
|
if (frame.type !== 'stream:chunk' || frame.jobId !== res.jobId) return;
|
|
if (frame.stream === 'meta') {
|
|
try {
|
|
const meta = JSON.parse(frame.data) as { event?: string; exitCode?: number | null };
|
|
if (meta.event === 'exit') {
|
|
logPre.textContent += `\n[Exited with code ${String(meta.exitCode)}]\n`;
|
|
stopBtn.disabled = true;
|
|
void opts.onFinished();
|
|
}
|
|
} catch {
|
|
// Ignore meta parse errors
|
|
}
|
|
} else {
|
|
logPre.textContent += frame.data;
|
|
}
|
|
logPre.scrollTop = logPre.scrollHeight;
|
|
});
|
|
|
|
opts.wsClient.subscribe([`stream:${res.jobId}`]);
|
|
}
|
|
|
|
export async function renderSystemsView(
|
|
root: HTMLElement,
|
|
state: ClientState,
|
|
wsClient: MultiplexWsClient,
|
|
): Promise<void> {
|
|
if (unsubStreamListener) {
|
|
unsubStreamListener();
|
|
unsubStreamListener = null;
|
|
}
|
|
root.replaceChildren();
|
|
const segs = state.routeSegments ?? [];
|
|
const forceRefresh = state.routeQuery?.refresh === '1';
|
|
|
|
// 1. Hub: #systems
|
|
if (segs.length === 0) {
|
|
const res = await apiFetch<{
|
|
systems: Array<{
|
|
system: SystemConfigView;
|
|
attachedServers: Array<{ serverId: string; serverName: string; params: Record<string, unknown> }>;
|
|
}>;
|
|
}>('/api/systems');
|
|
|
|
root.append(
|
|
el(
|
|
'section',
|
|
{ class: 'panel row-between' },
|
|
el('div', {}, el('h1', {}, 'Custom Systems Engine'), el('p', { class: 'muted' }, 'Declarative service managers defined in /data/config/systems/*.json')),
|
|
el('a', { href: '#config', class: 'btn btn-sm' }, 'Edit System JSONs'),
|
|
),
|
|
);
|
|
|
|
const grid = el('div', { class: 'grid-3' });
|
|
for (const entry of res.systems) {
|
|
const attachBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ Attach Server');
|
|
attachBtn.addEventListener('click', () => {
|
|
void openAttachModal(entry.system, () => renderSystemsView(root, state, wsClient));
|
|
});
|
|
|
|
grid.append(
|
|
el(
|
|
'article',
|
|
{ class: 'panel panel-region' },
|
|
el('h2', {}, entry.system.name),
|
|
el('p', { class: 'muted' }, entry.system.description ?? ''),
|
|
el('div', { class: 'mono' }, `ID: ${entry.system.id} | TTL: ${entry.system.cacheTtlSec}s`),
|
|
el('div', { class: 'mono muted' }, `Attached Servers: ${entry.attachedServers.length}`),
|
|
el('div', { class: 'muted' }, `Actions: ${entry.system.actions.map((a) => a.label).join(', ')}`),
|
|
el(
|
|
'div',
|
|
{ class: 'row', style: 'margin-top:8px' },
|
|
el('a', { href: `#systems/${encodeURIComponent(entry.system.id)}`, class: 'btn btn-sm btn-primary' }, 'Open System →'),
|
|
attachBtn,
|
|
),
|
|
),
|
|
);
|
|
}
|
|
root.append(grid);
|
|
return;
|
|
}
|
|
|
|
const systemId = segs[0]!;
|
|
const targetServerId = segs[1];
|
|
const targetItemName = segs[2];
|
|
|
|
const data = await apiFetch<{ system: SystemConfigView; snapshots: ServerSnapshotView[] }>(
|
|
`/api/systems/${encodeURIComponent(systemId)}?refresh=${forceRefresh ? '1' : '0'}${targetServerId ? `&serverId=${encodeURIComponent(targetServerId)}` : ''}`,
|
|
);
|
|
const { system, snapshots } = data;
|
|
const actionOutputHost = el('div', { class: 'stack' });
|
|
|
|
// 3. Service Detail: #systems/<systemId>/<serverId>/<item>
|
|
if (targetServerId && targetItemName) {
|
|
const snap = snapshots.find((s) => s.serverId === targetServerId);
|
|
const item = snap?.items.find((i) => i.name === targetItemName);
|
|
if (!snap || !item) {
|
|
root.append(
|
|
el(
|
|
'section',
|
|
{ class: 'panel' },
|
|
el('h1', {}, `Service "${targetItemName}" not found`),
|
|
el('a', { href: `#systems/${encodeURIComponent(systemId)}`, class: 'btn btn-sm' }, `← Back to ${system.name}`),
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
|
|
const itemActions = system.actions.filter((a) => a.scope === 'item');
|
|
const actionRow = el('div', { class: 'row' });
|
|
for (const act of itemActions) {
|
|
const btn = el(
|
|
'button',
|
|
{ type: 'button', class: `btn btn-sm mutating-action${act.id === 'down' ? ' btn-danger' : ''}` },
|
|
act.label,
|
|
);
|
|
btn.addEventListener('click', () => {
|
|
void runSystemAction({
|
|
systemId,
|
|
serverId: targetServerId,
|
|
action: act,
|
|
itemName: item.name,
|
|
outputHost: actionOutputHost,
|
|
wsClient,
|
|
onFinished: async () => {
|
|
state.routeQuery = { ...state.routeQuery, refresh: '1' };
|
|
await renderSystemsView(root, state, wsClient);
|
|
},
|
|
});
|
|
});
|
|
actionRow.append(btn);
|
|
}
|
|
|
|
root.append(
|
|
el(
|
|
'section',
|
|
{ class: 'panel' },
|
|
el(
|
|
'div',
|
|
{ class: 'row-between' },
|
|
el(
|
|
'div',
|
|
{},
|
|
el('h1', {}, `${system.name} / ${item.name}`),
|
|
el('div', { class: 'mono muted' }, `${targetServerId}${item.dir ? ` — ${item.dir}` : ''}`),
|
|
),
|
|
el(
|
|
'div',
|
|
{ class: 'row' },
|
|
el('span', { class: healthBadgeClass(item.status.health) }, `[${item.status.health.toUpperCase()}]`),
|
|
el('a', { href: `#systems/${encodeURIComponent(systemId)}`, class: 'btn btn-sm' }, `← ${system.name}`),
|
|
),
|
|
),
|
|
el('div', { style: 'margin-top:8px' }, actionRow),
|
|
),
|
|
actionOutputHost,
|
|
);
|
|
|
|
// Multi-file activeFiles[] overlay selector
|
|
if (item.selectableFiles.length > 0) {
|
|
const overlayPanel = el('section', { class: 'panel' });
|
|
let orderedSelected = [...item.activeFiles];
|
|
const availableExtras = item.selectableFiles.filter((f) => !orderedSelected.includes(f));
|
|
let displayList = [...orderedSelected, ...availableExtras];
|
|
const filesListEl = el('div', { class: 'stack' });
|
|
const overlayMsg = el('p', { class: 'form-msg' });
|
|
|
|
const redrawFiles = () => {
|
|
filesListEl.replaceChildren();
|
|
displayList.forEach((fname, idx) => {
|
|
const checked = orderedSelected.includes(fname);
|
|
const chk = el('input', { type: 'checkbox', checked });
|
|
chk.addEventListener('change', () => {
|
|
if (chk.checked && !orderedSelected.includes(fname)) {
|
|
orderedSelected.push(fname);
|
|
} else if (!chk.checked) {
|
|
orderedSelected = orderedSelected.filter((x) => x !== fname);
|
|
}
|
|
});
|
|
const upBtn = el('button', { type: 'button', class: 'btn btn-sm', disabled: idx === 0 }, '↑');
|
|
upBtn.addEventListener('click', () => {
|
|
if (idx <= 0) return;
|
|
const prev = displayList[idx - 1]!;
|
|
displayList[idx - 1] = fname;
|
|
displayList[idx] = prev;
|
|
orderedSelected = displayList.filter((f) => orderedSelected.includes(f));
|
|
redrawFiles();
|
|
});
|
|
filesListEl.append(
|
|
el('div', { class: 'row-between' }, el('label', { class: 'chk-row mono' }, chk, fname), upBtn),
|
|
);
|
|
});
|
|
};
|
|
redrawFiles();
|
|
|
|
const saveOverlaysBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Save activeFiles[] & Refresh');
|
|
saveOverlaysBtn.addEventListener('click', async () => {
|
|
if (orderedSelected.length === 0) {
|
|
overlayMsg.className = 'form-msg err-text';
|
|
overlayMsg.textContent = 'Select at least one config file.';
|
|
return;
|
|
}
|
|
await apiFetch(
|
|
`/api/systems/${encodeURIComponent(systemId)}/servers/${encodeURIComponent(targetServerId)}/items/${encodeURIComponent(item.name)}/files`,
|
|
{ method: 'PUT', body: { activeFiles: orderedSelected } },
|
|
);
|
|
state.routeQuery = { ...state.routeQuery, refresh: '1' };
|
|
await renderSystemsView(root, state, wsClient);
|
|
});
|
|
|
|
overlayPanel.append(
|
|
el('div', { class: 'row-between' }, el('h2', {}, 'Active Overlay Files (activeFiles[])'), saveOverlaysBtn),
|
|
filesListEl,
|
|
overlayMsg,
|
|
);
|
|
root.append(overlayPanel);
|
|
}
|
|
|
|
// Sub-items table (containers / processes)
|
|
const subActions = system.actions.filter((a) => a.scope === 'subitem');
|
|
const subPanel = el('section', { class: 'panel' });
|
|
subPanel.append(el('h2', {}, `Sub-Items (${item.status.subItems.length})`));
|
|
if (item.status.subItems.length === 0) {
|
|
subPanel.append(el('div', { class: 'mono muted' }, item.status.rawSummary || 'No sub-items reported.'));
|
|
} else {
|
|
const tbl = el('table');
|
|
tbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'Name'), el('th', {}, 'Health'), el('th', {}, 'State'), el('th', {}, 'Actions'))));
|
|
const tbody = el('tbody');
|
|
for (const sub of item.status.subItems) {
|
|
const sRow = el('div', { class: 'row' });
|
|
for (const act of subActions) {
|
|
const btn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, act.label);
|
|
btn.addEventListener('click', () => {
|
|
void runSystemAction({
|
|
systemId,
|
|
serverId: targetServerId,
|
|
action: act,
|
|
itemName: item.name,
|
|
subItemName: sub.name,
|
|
outputHost: actionOutputHost,
|
|
wsClient,
|
|
onFinished: async () => undefined,
|
|
});
|
|
});
|
|
sRow.append(btn);
|
|
}
|
|
tbody.append(
|
|
el(
|
|
'tr',
|
|
{},
|
|
el('td', { class: 'mono' }, sub.name),
|
|
el('td', {}, el('span', { class: healthBadgeClass(sub.health) }, `[${sub.health.toUpperCase()}]`)),
|
|
el('td', { class: 'mono' }, sub.stateText ?? '—'),
|
|
el('td', {}, sRow),
|
|
),
|
|
);
|
|
}
|
|
tbl.append(tbody);
|
|
subPanel.append(el('div', { class: 'table-wrap' }, tbl));
|
|
}
|
|
root.append(subPanel);
|
|
|
|
// Quick Editable Files via SFTP inline diff editor
|
|
if (item.editableFiles.length > 0) {
|
|
const editRow = el('div', { class: 'chip-list' });
|
|
for (const fPath of item.editableFiles) {
|
|
editRow.append(
|
|
el(
|
|
'a',
|
|
{
|
|
href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}`,
|
|
class: 'btn btn-sm',
|
|
},
|
|
`Edit ${fPath.split('/').pop()}`,
|
|
),
|
|
);
|
|
}
|
|
root.append(el('section', { class: 'panel' }, el('h2', {}, 'Editable Service Files (SFTP Inline Diff)'), editRow));
|
|
}
|
|
|
|
// Per-Service Tasks & Cron workflows matching scope
|
|
const tasksPanel = el('section', { class: 'panel' });
|
|
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',
|
|
);
|
|
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;
|
|
}
|
|
|
|
// 2. System Page: #systems/<systemId>
|
|
const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Force Refresh');
|
|
refreshBtn.addEventListener('click', () => {
|
|
state.routeQuery = { ...state.routeQuery, refresh: '1' };
|
|
void renderSystemsView(root, state, wsClient);
|
|
});
|
|
const attachBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, '+ Attach Server');
|
|
attachBtn.addEventListener('click', () => {
|
|
void openAttachModal(system, () => renderSystemsView(root, state, wsClient));
|
|
});
|
|
|
|
root.append(
|
|
el(
|
|
'section',
|
|
{ class: 'panel row-between' },
|
|
el('div', {}, el('h1', {}, system.name), el('p', { class: 'muted' }, system.description ?? '')),
|
|
el('div', { class: 'row' }, refreshBtn, attachBtn, el('a', { href: '#systems', class: 'btn btn-sm' }, '← All Systems')),
|
|
),
|
|
actionOutputHost,
|
|
);
|
|
|
|
if (snapshots.length === 0) {
|
|
root.append(
|
|
el('section', { class: 'panel' }, el('p', { class: 'muted' }, 'No enabled servers have this system attached yet. Click "+ Attach Server" above.')),
|
|
);
|
|
return;
|
|
}
|
|
|
|
const systemActions = system.actions.filter((a) => a.scope === 'system');
|
|
const itemActions = system.actions.filter((a) => a.scope === 'item');
|
|
|
|
for (const snap of snapshots) {
|
|
const srvPanel = el('section', { class: 'panel panel-region' });
|
|
const sysBtns = el('div', { class: 'row' });
|
|
for (const act of systemActions) {
|
|
const btn = el(
|
|
'button',
|
|
{ type: 'button', class: `btn btn-sm mutating-action${act.confirm ? ' btn-danger' : ''}` },
|
|
act.label,
|
|
);
|
|
btn.addEventListener('click', () => {
|
|
void runSystemAction({
|
|
systemId,
|
|
serverId: snap.serverId,
|
|
action: act,
|
|
outputHost: actionOutputHost,
|
|
wsClient,
|
|
onFinished: async () => {
|
|
state.routeQuery = { ...state.routeQuery, refresh: '1' };
|
|
await renderSystemsView(root, state, wsClient);
|
|
},
|
|
});
|
|
});
|
|
sysBtns.append(btn);
|
|
}
|
|
|
|
const detachBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Detach');
|
|
detachBtn.addEventListener('click', async () => {
|
|
const ok = await confirmDialog('dialog-confirm', `Detach "${system.name}" from "${snap.serverId}"?`);
|
|
if (!ok) return;
|
|
await apiFetch(
|
|
`/api/systems/${encodeURIComponent(systemId)}/servers/${encodeURIComponent(snap.serverId)}/attach`,
|
|
{ method: 'DELETE' },
|
|
);
|
|
await renderSystemsView(root, state, wsClient);
|
|
});
|
|
|
|
srvPanel.append(
|
|
el(
|
|
'div',
|
|
{ class: 'row-between', style: 'margin-bottom:8px' },
|
|
el(
|
|
'div',
|
|
{},
|
|
el('h2', {}, snap.serverId),
|
|
el('div', { class: 'mono muted' }, `Updated ${fmtTime(snap.fetchedAt)}${snap.cached ? ' (cached)' : ''}`),
|
|
),
|
|
el('div', { class: 'row' }, el('span', { class: healthBadgeClass(snap.systemHealth) }, `[${snap.systemHealth.toUpperCase()}]`), sysBtns, detachBtn),
|
|
),
|
|
);
|
|
|
|
if (snap.error) {
|
|
srvPanel.append(el('p', { class: 'err-text mono' }, snap.error));
|
|
} else if (snap.items.length === 0) {
|
|
srvPanel.append(el('p', { class: 'muted' }, 'No services discovered for the configured roots/filter.'));
|
|
} else {
|
|
const tbl = el('table');
|
|
tbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'Service / Item'), el('th', {}, 'Health'), el('th', {}, 'Active Files / Summary'), el('th', {}, 'Quick Actions'))));
|
|
const tbody = el('tbody');
|
|
for (const item of snap.items) {
|
|
const qRow = el('div', { class: 'row' });
|
|
for (const act of itemActions.slice(0, 4)) {
|
|
const b = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, act.label);
|
|
b.addEventListener('click', () => {
|
|
void runSystemAction({
|
|
systemId,
|
|
serverId: snap.serverId,
|
|
action: act,
|
|
itemName: item.name,
|
|
outputHost: actionOutputHost,
|
|
wsClient,
|
|
onFinished: async () => {
|
|
state.routeQuery = { ...state.routeQuery, refresh: '1' };
|
|
await renderSystemsView(root, state, wsClient);
|
|
},
|
|
});
|
|
});
|
|
qRow.append(b);
|
|
}
|
|
qRow.append(
|
|
el(
|
|
'a',
|
|
{
|
|
href: `#systems/${encodeURIComponent(systemId)}/${encodeURIComponent(snap.serverId)}/${encodeURIComponent(item.name)}`,
|
|
class: 'btn btn-sm btn-primary',
|
|
},
|
|
'Manage →',
|
|
),
|
|
);
|
|
|
|
tbody.append(
|
|
el(
|
|
'tr',
|
|
{},
|
|
el('td', {}, el('strong', {}, item.name), item.dir ? el('div', { class: 'mono muted' }, item.dir) : ''),
|
|
el('td', {}, el('span', { class: healthBadgeClass(item.status.health) }, `[${item.status.health.toUpperCase()}]`)),
|
|
el(
|
|
'td',
|
|
{ class: 'mono' },
|
|
item.activeFiles.length > 0 ? el('div', {}, `files: ${item.activeFiles.join(', ')}`) : '',
|
|
el('div', { class: 'muted' }, item.status.rawSummary.slice(0, 120)),
|
|
),
|
|
el('td', {}, qRow),
|
|
),
|
|
);
|
|
}
|
|
tbl.append(tbody);
|
|
srvPanel.append(el('div', { class: 'table-wrap' }, tbl));
|
|
}
|
|
|
|
root.append(srvPanel);
|
|
}
|
|
}
|