CI / Lint (eslint) (pull_request) Successful in 20s
CI / Test (jest) (pull_request) Successful in 21s
CI / Security (npm audit) (pull_request) Successful in 15s
CI / Integration (api) (pull_request) Successful in 2m43s
CI / Scan (secrets, workflows, shell) (pull_request) Successful in 2m44s
CI / UI (playwright) (pull_request) Successful in 2m35s
CI / Deploy (pull_request) Skipped
CI / Deploy worker (pull_request) Skipped
CI / Notify (pull_request) Skipped
CI / UI screenshots (before/after) (pull_request) Successful in 1m54s
A shared output block (Pulse.output.render) now draws every command output in Executions and Quick Command: - ANSI escape codes (colours, cursor moves, titles, charset switches) are stripped, so systemctl, ls --color and docker read cleanly. - Copy and .txt use the full, clean text; .txt downloads it as a file. - Wrap turns long-line wrapping on or off for every block, remembered. - Output over 25 lines starts at 24rem high with an Expand button. - Over 100,000 characters, the display is cut with a notice saying how much is hidden; Copy and .txt still include all of it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
433 lines
19 KiB
JavaScript
433 lines
19 KiB
JavaScript
/* =====================================================================
|
|
PULSE: Quick Command page (WP-F)
|
|
Owns DOM id prefix `qc-` and action namespace `qc:*`.
|
|
===================================================================== */
|
|
'use strict';
|
|
|
|
(function () {
|
|
const esc = Pulse.esc;
|
|
|
|
const HISTORY_KEY = 'commandHistory';
|
|
const HISTORY_LIMIT = 50;
|
|
const RERUN_KEY = 'pulse_rerun';
|
|
|
|
/* Copied verbatim from the pre-redesign public/index.html commandTemplates
|
|
array (12 templates): kept static here since pageConfig only carries
|
|
isAdmin from server.js (WP-A), not a templates list. */
|
|
const TEMPLATES = [
|
|
{ name: 'System Info', cmd: 'uname -a', desc: 'Show system information' },
|
|
{ name: 'Uptime', cmd: 'uptime', desc: 'Show system uptime and load' },
|
|
{ name: 'Disk Usage', cmd: 'df -h', desc: 'Show disk space usage' },
|
|
{ name: 'Memory Usage', cmd: 'free -h', desc: 'Show memory usage' },
|
|
{ name: 'CPU Info', cmd: 'lscpu', desc: 'Show CPU information' },
|
|
{ name: 'Running Processes', cmd: 'ps aux --sort=-%mem | head -20', desc: 'Top 20 processes by memory' },
|
|
{ name: 'Network Interfaces', cmd: 'ip addr show', desc: 'Show network interfaces' },
|
|
{ name: 'Active Connections', cmd: 'ss -tunap', desc: 'Show active network connections' },
|
|
{ name: 'Docker Containers', cmd: 'docker ps -a', desc: 'List all Docker containers' },
|
|
{ name: 'System Log Tail', cmd: 'tail -n 50 /var/log/syslog', desc: 'Last 50 lines of system log' },
|
|
{ name: 'Who is Logged In', cmd: 'w', desc: 'Show logged in users' },
|
|
{ name: 'Last Logins', cmd: 'last -n 20', desc: 'Show last 20 logins' },
|
|
];
|
|
|
|
let _workers = [];
|
|
|
|
/* -------------------------------------------------------------------
|
|
History (localStorage, verbatim key/shape from the old UI)
|
|
------------------------------------------------------------------- */
|
|
function loadHistory() {
|
|
return Pulse.util.storage.get(HISTORY_KEY, []) || [];
|
|
}
|
|
|
|
function addToHistory(command, workerLabel) {
|
|
const history = loadHistory();
|
|
history.unshift({ command: command, worker: workerLabel, timestamp: new Date().toISOString() });
|
|
if (history.length > HISTORY_LIMIT) history.splice(HISTORY_LIMIT);
|
|
Pulse.util.storage.set(HISTORY_KEY, history);
|
|
}
|
|
|
|
/* -------------------------------------------------------------------
|
|
Worker select / checkbox list
|
|
------------------------------------------------------------------- */
|
|
/* Last mode and worker choice, kept across reloads (#31). */
|
|
const PREFS_KEY = 'pulse_qc_prefs';
|
|
function loadPrefs() {
|
|
const p = Pulse.util.storage.get(PREFS_KEY, null);
|
|
return p && typeof p === 'object' ? p : {};
|
|
}
|
|
function savePrefs(patch) {
|
|
Pulse.util.storage.set(PREFS_KEY, Object.assign(loadPrefs(), patch));
|
|
}
|
|
|
|
function currentMode() {
|
|
const checked = document.querySelector('input[name="qc-exec-mode"]:checked');
|
|
return checked ? checked.value : 'single';
|
|
}
|
|
|
|
function applyMode() {
|
|
const mode = currentMode();
|
|
const single = document.getElementById('qc-single-mode');
|
|
const multi = document.getElementById('qc-multi-mode');
|
|
if (single) single.hidden = mode !== 'single';
|
|
if (multi) multi.hidden = mode !== 'multi';
|
|
}
|
|
|
|
function renderWorkerSelect(workers, preserveId) {
|
|
const select = document.getElementById('qc-worker');
|
|
if (!select) return;
|
|
if (workers.length === 0) {
|
|
select.innerHTML = '<option value="">No workers available</option>';
|
|
return;
|
|
}
|
|
select.innerHTML = workers.map(w =>
|
|
'<option value="' + esc(w.id) + '">' + esc(w.name) + ' (' + esc(w.status) + ')</option>'
|
|
).join('');
|
|
if (preserveId && workers.some(w => w.id === preserveId)) select.value = preserveId;
|
|
}
|
|
|
|
function renderWorkerCheckboxes(workers, preserveIds) {
|
|
const wrap = document.getElementById('qc-worker-list');
|
|
if (!wrap) return;
|
|
if (workers.length === 0) {
|
|
wrap.innerHTML = '<div class="lt-empty-state lt-empty-state--sm"><div class="lt-empty-state-title">No workers available</div>' +
|
|
'<div class="lt-empty-state-body">Connect one first: see <a href="/workers">Workers</a>.</div></div>';
|
|
return;
|
|
}
|
|
const keep = preserveIds || new Set();
|
|
wrap.innerHTML = workers.map(w => {
|
|
const checked = keep.has(w.id) ? ' checked' : '';
|
|
return (
|
|
'<label class="qc-worker-row' + (w.status === 'online' ? ' qc-worker-row--online' : '') + '">' +
|
|
'<input type="checkbox" class="lt-checkbox" name="qc-worker-cb" value="' + esc(w.id) + '" data-status="' + esc(w.status) + '"' + checked + '>' +
|
|
'<span class="' + Pulse.fmt.status(w.status) + '">' + (w.status === 'online' ? '●' : '○') + '</span>' +
|
|
'<strong>' + esc(w.name) + '</strong>' +
|
|
'</label>'
|
|
);
|
|
}).join('');
|
|
}
|
|
|
|
function selectedWorkerCheckboxIds() {
|
|
return Array.from(document.querySelectorAll('input[name="qc-worker-cb"]:checked')).map(cb => cb.value);
|
|
}
|
|
|
|
let _restored = false;
|
|
async function loadWorkers() {
|
|
const select = document.getElementById('qc-worker');
|
|
let preserveSingle = select ? select.value : '';
|
|
let preserveMulti = new Set(selectedWorkerCheckboxIds());
|
|
if (!_restored) {
|
|
// First load: start from the saved choice rather than the first worker.
|
|
_restored = true;
|
|
const prefs = loadPrefs();
|
|
preserveSingle = prefs.worker || preserveSingle;
|
|
if (Array.isArray(prefs.workers)) preserveMulti = new Set(prefs.workers);
|
|
}
|
|
try {
|
|
_workers = await Pulse.api.get('/api/workers') || [];
|
|
} catch (e) {
|
|
_workers = [];
|
|
console.error('[Pulse:quick] failed to load workers', e);
|
|
}
|
|
renderWorkerSelect(_workers, preserveSingle);
|
|
renderWorkerCheckboxes(_workers, preserveMulti);
|
|
return _workers;
|
|
}
|
|
|
|
/* -------------------------------------------------------------------
|
|
Templates modal
|
|
------------------------------------------------------------------- */
|
|
function renderTemplates() {
|
|
const list = document.getElementById('qc-templates-list');
|
|
if (!list) return;
|
|
list.innerHTML = TEMPLATES.map((t, i) =>
|
|
'<div class="qc-list-item" data-action="qc:template-use" data-index="' + i + '">' +
|
|
'<div class="qc-list-item-title">' + esc(t.name) + '</div>' +
|
|
'<div class="qc-list-item-code"><code>' + esc(t.cmd) + '</code></div>' +
|
|
'<div class="qc-list-item-meta">' + esc(t.desc) + '</div>' +
|
|
'</div>'
|
|
).join('');
|
|
}
|
|
|
|
function renderHistory() {
|
|
const list = document.getElementById('qc-history-list');
|
|
if (!list) return;
|
|
const history = loadHistory();
|
|
if (history.length === 0) {
|
|
list.innerHTML = '<div class="lt-empty-state lt-empty-state--sm"><div class="lt-empty-state-title">No command history yet</div></div>';
|
|
return;
|
|
}
|
|
list.innerHTML = history.map((item, i) =>
|
|
'<div class="qc-list-item" data-action="qc:history-use" data-index="' + i + '">' +
|
|
'<div class="qc-list-item-code"><code>' + esc(item.command) + '</code></div>' +
|
|
'<div class="qc-list-item-meta">' + esc(Pulse.fmt.dateTime(item.timestamp)) + ' | ' + esc(item.worker) + '</div>' +
|
|
'</div>'
|
|
).join('');
|
|
}
|
|
|
|
/* -------------------------------------------------------------------
|
|
Result rendering
|
|
------------------------------------------------------------------- */
|
|
/* Results show here as they arrive, per worker, instead of only in Executions (#5).
|
|
A card per run: "running" until its command_result comes in over the live
|
|
connection, or a poll finds it finished if that event was missed. */
|
|
const _runs = new Map(); // execution id -> { card, startedAt, timer }
|
|
const _early = new Map(); // results that beat the POST response
|
|
|
|
function forgetRuns() {
|
|
_runs.forEach(r => clearTimeout(r.timer));
|
|
_runs.clear();
|
|
}
|
|
|
|
function renderRuns(entries, summary) {
|
|
forgetRuns();
|
|
const wrap = document.getElementById('qc-result');
|
|
if (!wrap) return;
|
|
const head = summary ? '<div class="qc-run-summary">' + esc(summary) + '</div>' : '';
|
|
wrap.innerHTML = head + entries.map(runCard).join('');
|
|
entries.forEach((e, i) => {
|
|
if (!e.executionId) return;
|
|
const run = { card: document.getElementById('qc-run-' + i), startedAt: Date.now(), timer: null };
|
|
_runs.set(e.executionId, run);
|
|
if (_early.has(e.executionId)) { showResult(e.executionId, _early.get(e.executionId)); return; }
|
|
run.timer = setTimeout(() => pollRun(e.executionId, 0), 5000);
|
|
});
|
|
}
|
|
|
|
function runCard(e, i) {
|
|
const id = e.executionId;
|
|
const worker = esc(e.worker);
|
|
if (!id) {
|
|
return '<div class="qc-run" id="qc-run-' + i + '"><div class="qc-run-head">' +
|
|
'<strong class="qc-run-worker">' + worker + '</strong>' +
|
|
'<span class="lt-status lt-status-failed qc-run-status">✕ Not sent</span></div>' +
|
|
'<div class="qc-run-body"><pre class="lt-log-output qc-out-err">' + esc(e.error || 'Failed to send') + '</pre></div></div>';
|
|
}
|
|
return '<div class="qc-run" id="qc-run-' + i + '"><div class="qc-run-head">' +
|
|
'<strong class="qc-run-worker">' + worker + '</strong>' +
|
|
'<span class="lt-status lt-status-running qc-run-status">Running…</span>' +
|
|
'<span class="qc-run-time"></span>' +
|
|
'<a class="qc-run-link" href="/executions?open=' + encodeURIComponent(id) + '">view in Executions</a></div>' +
|
|
'<div class="qc-run-body"></div></div>';
|
|
}
|
|
|
|
function failureLabel(r) {
|
|
if (r.timed_out) return 'Timed out';
|
|
if (r.signal) return 'Killed (' + r.signal + ')';
|
|
if (typeof r.exit_code === 'number') return 'Failed (exit ' + r.exit_code + ')';
|
|
return 'Failed';
|
|
}
|
|
|
|
function showResult(executionId, r) {
|
|
const run = _runs.get(executionId);
|
|
if (!run || !run.card) return;
|
|
clearTimeout(run.timer);
|
|
_runs.delete(executionId);
|
|
_early.delete(executionId);
|
|
const status = run.card.querySelector('.qc-run-status');
|
|
const ok = Boolean(r.success);
|
|
const label = ok ? 'Completed' : failureLabel(r);
|
|
status.className = 'lt-status qc-run-status ' + (ok ? 'lt-status-completed' : 'lt-status-failed');
|
|
status.textContent = (ok ? '\u2713 ' : '\u2715 ') + label;
|
|
const ms = typeof r.duration === 'number' ? r.duration : Date.now() - run.startedAt;
|
|
run.card.querySelector('.qc-run-time').textContent = ms < 1000 ? ms + ' ms' : (ms / 1000).toFixed(1) + ' s';
|
|
const parts = [];
|
|
const name = 'pulse-' + String(executionId).slice(0, 8);
|
|
if (r.stdout) parts.push(Pulse.output.render(r.stdout, { cls: 'qc-out', name: name }));
|
|
if (r.stderr) parts.push(Pulse.output.render(r.stderr, { err: true, cls: 'qc-out-err', name: name + '-stderr' }));
|
|
if (!r.success && r.error && !r.stderr) parts.push('<pre class="lt-log-output qc-out-err">' + esc(r.error) + '</pre>');
|
|
if (!parts.length) parts.push('<div class="qc-out-note">No output</div>');
|
|
const body = run.card.querySelector('.qc-run-body');
|
|
body.innerHTML = parts.join('');
|
|
}
|
|
|
|
// Fallback for a result event that never arrived (e.g. the live connection dropped).
|
|
async function pollRun(executionId, tries) {
|
|
const run = _runs.get(executionId);
|
|
if (!run) return;
|
|
try {
|
|
const ex = await Pulse.api.get('/api/executions/' + encodeURIComponent(executionId));
|
|
if (ex && ex.status !== 'running') {
|
|
const logs = Array.isArray(ex.logs) ? ex.logs : [];
|
|
const r = logs.filter(l => l.action === 'command_result').pop();
|
|
showResult(executionId, r || { success: ex.status === 'completed', error: 'No result recorded (' + ex.status + ')' });
|
|
return;
|
|
}
|
|
} catch (e) { /* try again */ }
|
|
if (tries < 180 && _runs.has(executionId)) run.timer = setTimeout(() => pollRun(executionId, tries + 1), 5000);
|
|
}
|
|
|
|
function onCommandResult(data) {
|
|
if (!data || !data.execution_id) return false;
|
|
if (_runs.has(data.execution_id)) { showResult(data.execution_id, data); return true; }
|
|
// Can arrive before the POST that started it returns: keep it briefly.
|
|
_early.set(data.execution_id, data);
|
|
if (_early.size > 100) _early.delete(_early.keys().next().value);
|
|
return false;
|
|
}
|
|
|
|
function renderExecuting(count) {
|
|
forgetRuns();
|
|
const wrap = document.getElementById('qc-result');
|
|
if (!wrap) return;
|
|
wrap.innerHTML = '<div class="lt-empty-state lt-empty-state--sm"><div class="lt-empty-state-title">Sending' +
|
|
(count > 1 ? ' to ' + count + ' workers' : '') + '…</div></div>';
|
|
}
|
|
|
|
/* -------------------------------------------------------------------
|
|
Execute
|
|
------------------------------------------------------------------- */
|
|
async function execute() {
|
|
const commandEl = document.getElementById('qc-command');
|
|
const command = commandEl ? commandEl.value.trim() : '';
|
|
if (!command) {
|
|
Pulse.toast.error('Please enter a command');
|
|
return;
|
|
}
|
|
const mode = currentMode();
|
|
|
|
if (mode === 'single') {
|
|
const select = document.getElementById('qc-worker');
|
|
const workerId = select ? select.value : '';
|
|
if (!workerId) {
|
|
Pulse.toast.error('Please select a worker');
|
|
return;
|
|
}
|
|
const worker = _workers.find(w => w.id === workerId);
|
|
const workerName = worker ? worker.name : 'Unknown';
|
|
savePrefs({ mode: 'single', worker: workerId });
|
|
renderExecuting(1);
|
|
try {
|
|
const data = await Pulse.api.post('/api/workers/' + encodeURIComponent(workerId) + '/command', { command });
|
|
addToHistory(command, workerName);
|
|
renderRuns([{ worker: workerName, executionId: data && data.execution_id }]);
|
|
} catch (e) {
|
|
renderRuns([{ worker: workerName, error: e.message || 'Failed to execute command' }]);
|
|
Pulse.beep('error');
|
|
}
|
|
return;
|
|
}
|
|
|
|
const workerIds = selectedWorkerCheckboxIds();
|
|
if (workerIds.length === 0) {
|
|
Pulse.toast.error('Please select at least one worker');
|
|
return;
|
|
}
|
|
savePrefs({ mode: 'multi', workers: workerIds });
|
|
renderExecuting(workerIds.length);
|
|
// Send to every selected worker at once (#26); results keep the selection order.
|
|
const results = await Promise.all(workerIds.map(async (workerId) => {
|
|
const worker = _workers.find(w => w.id === workerId);
|
|
const workerLabel = worker ? worker.name : workerId;
|
|
try {
|
|
const data = await Pulse.api.post('/api/workers/' + encodeURIComponent(workerId) + '/command', { command });
|
|
return { worker: workerLabel, success: true, executionId: data && data.execution_id };
|
|
} catch (e) {
|
|
return { worker: workerLabel, success: false, error: e.message || 'Failed to execute' };
|
|
}
|
|
}));
|
|
const successCount = results.filter(r => r.success).length;
|
|
const failCount = results.length - successCount;
|
|
addToHistory(command, workerIds.length + ' workers');
|
|
renderRuns(results, failCount === 0
|
|
? 'Sent to ' + successCount + ' workers'
|
|
: 'Sent to ' + successCount + ' of ' + results.length + ' workers; ' + failCount + ' could not be reached');
|
|
if (failCount > 0) Pulse.beep(successCount > 0 ? 'info' : 'error');
|
|
}
|
|
|
|
/* -------------------------------------------------------------------
|
|
Cross-page re-run (from Executions page)
|
|
------------------------------------------------------------------- */
|
|
function consumeRerun() {
|
|
let raw;
|
|
try { raw = window.sessionStorage.getItem(RERUN_KEY); } catch (e) { return; }
|
|
if (!raw) return;
|
|
try { window.sessionStorage.removeItem(RERUN_KEY); } catch (e) { /* ignore */ }
|
|
let payload;
|
|
try { payload = JSON.parse(raw); } catch (e) { return; }
|
|
if (!payload) return;
|
|
|
|
const singleRadio = document.getElementById('qc-mode-single');
|
|
if (singleRadio) singleRadio.checked = true;
|
|
applyMode();
|
|
|
|
if (payload.worker_id) {
|
|
const select = document.getElementById('qc-worker');
|
|
const hasWorker = select && _workers.some(w => w.id === payload.worker_id);
|
|
if (hasWorker) {
|
|
select.value = payload.worker_id;
|
|
} else {
|
|
Pulse.toast.warning('Original worker is no longer available. Select a worker to run this command.');
|
|
}
|
|
}
|
|
const commandEl = document.getElementById('qc-command');
|
|
if (commandEl) {
|
|
commandEl.value = payload.command || '';
|
|
commandEl.focus();
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------------------------------
|
|
Data loading / refresh
|
|
------------------------------------------------------------------- */
|
|
async function refresh() {
|
|
await loadWorkers();
|
|
}
|
|
|
|
function init() {
|
|
Pulse.actions.registerAll({
|
|
'qc:mode': () => { applyMode(); savePrefs({ mode: currentMode() }); },
|
|
'qc:templates-open': () => { renderTemplates(); if (window.lt && lt.modal) lt.modal.open('qc-templates-modal'); },
|
|
'qc:template-use': (el) => {
|
|
const idx = Number(el.getAttribute('data-index'));
|
|
const tpl = TEMPLATES[idx];
|
|
if (!tpl) return;
|
|
const commandEl = document.getElementById('qc-command');
|
|
if (commandEl) commandEl.value = tpl.cmd;
|
|
if (window.lt && lt.modal) lt.modal.close('qc-templates-modal');
|
|
},
|
|
'qc:history-open': () => { renderHistory(); if (window.lt && lt.modal) lt.modal.open('qc-history-modal'); },
|
|
'qc:history-use': (el) => {
|
|
const idx = Number(el.getAttribute('data-index'));
|
|
const history = loadHistory();
|
|
const item = history[idx];
|
|
if (!item) return;
|
|
const commandEl = document.getElementById('qc-command');
|
|
if (commandEl) commandEl.value = item.command;
|
|
if (window.lt && lt.modal) lt.modal.close('qc-history-modal');
|
|
},
|
|
'qc:select-all': () => {
|
|
document.querySelectorAll('input[name="qc-worker-cb"]').forEach(cb => { cb.checked = true; });
|
|
},
|
|
'qc:select-online': () => {
|
|
document.querySelectorAll('input[name="qc-worker-cb"]').forEach(cb => {
|
|
cb.checked = cb.getAttribute('data-status') === 'online';
|
|
});
|
|
},
|
|
'qc:clear-all': () => {
|
|
document.querySelectorAll('input[name="qc-worker-cb"]').forEach(cb => { cb.checked = false; });
|
|
},
|
|
'qc:execute': execute,
|
|
});
|
|
|
|
if (window.lt && lt.keys && typeof lt.keys.on === 'function') {
|
|
lt.keys.on('ctrl+enter', () => { execute(); });
|
|
}
|
|
|
|
const saved = loadPrefs().mode;
|
|
const savedRadio = saved && document.querySelector('input[name="qc-exec-mode"][value="' + (saved === 'multi' ? 'multi' : 'single') + '"]');
|
|
if (savedRadio) savedRadio.checked = true;
|
|
applyMode();
|
|
return loadWorkers().then(() => { consumeRerun(); });
|
|
}
|
|
|
|
function onEvent(type, data) {
|
|
if (type === 'worker_update') {
|
|
loadWorkers();
|
|
return true;
|
|
}
|
|
if (type === 'command_result') return onCommandResult(data);
|
|
return false;
|
|
}
|
|
|
|
Pulse.registerPage({ name: 'quick', init, refresh, onEvent });
|
|
})();
|