Turn the running Fit/Plot button into an Abort that kills hung jobs

musrfit/musrview can hang indefinitely and the only feedback was a disabled
Fit/Plot button. While a job is running (Electron only), the active button now
morphs into an enabled Abort that kills the last launched process: SIGTERM
through the preload bridge, then SIGKILL after a 3s grace period.

- preload: spawnCapture registers children under a caller job token; new
  abortJob(token, signal) kills it (SIGTERM then escalated SIGKILL)
- electron shim: runLocalProcess hands its token to the bridge, exposes
  window.triggerMusrfitAbort, reports signal exits as outcome 'aborted'
- shared lib: setMusrfitActionState morphs label/click and restores the
  original inline handler; finishJobStatus gains a warning-level 'aborted'
  outcome. Web jobs stay disabled (server-side, already time-limited)
This commit is contained in:
salman committed 2026-09-08 17:21:29 +02:00
1 parent 26c654fcfc
commit ccb25fb049
5 files changed
+344 -13

No files matched your search

+69 -2
View File
@@ -41,6 +41,11 @@ function bridgeChildProcess(api) {
return api.spawnSync(command, args || [], options || {});
};
cp.spawnCapture = api.spawnCapture;
if (api.abortJob) {
cp.abortJob = function (token, signal) {
return api.abortJob(token, signal || "SIGTERM");
};
}
return cp;
}
var nodeChildProcess = window.nodeChildProcess
@@ -58,6 +63,39 @@ window.nodePath = nodePath;
window.nodeChildProcess = nodeChildProcess;
window.nodeProcess = nodeProcess;
// The shared action-button state is upgraded for Electron: while a job is
// running, the active Fit/Plot button becomes "Abort" and kills the last
// launched child process through the preload bridge. Web jobs run server-side,
// cannot be killed from the page, and keep the disabled button.
if (window.MusrfitAction) {
window.MusrfitAction.abortSupported = true;
}
// runLocalProcess() records the bridge token of the job it just launched so
// Abort targets exactly the last musrfit/musrview process, and only one.
var electronRunJobToken = "";
var electronRunJobLabel = "";
var electronRunJobLogFile = "";
var electronRunJobAborted = false;
var electronRunJobSeq = 0;
function electronRequestAbort(action) {
if (electronRunJobToken === "" || typeof nodeChildProcess.abortJob !== "function") {
return false;
}
if (electronRunJobAborted) return true;
electronRunJobAborted = true;
if (electronRunJobLogFile) {
appendFitLog(electronRunJobLogFile, "\n# Abort requested by user\n");
}
nodeChildProcess.abortJob(electronRunJobToken, "SIGTERM");
if (typeof setFitStatus === "function") {
setFitStatus("Abort requested; stopping " + (electronRunJobLabel || "the job") + ".");
}
return true;
}
window.triggerMusrfitAbort = electronRequestAbort;
function seriesFilesystemError(code, filePath) {
let error = new Error(code + (filePath ? ": " + filePath : ""));
error.code = code;
@@ -811,14 +849,30 @@ function runLocalProcess(label, command, args, cwd, logFile, options = {}) {
// In the hardened build child_process access lives behind the preload
// bridge, which buffers the streams and invokes onChunk per chunk so the
// live .out log and on-screen output behave exactly as before.
// live .out log and on-screen output behave exactly as before. The token
// lets the Abort action kill this job through the same bridge.
if (typeof nodeChildProcess.spawnCapture === "function") {
let jobToken = "";
if (typeof nodeChildProcess.abortJob === "function") {
jobToken = "musr" + (++electronRunJobSeq);
electronRunJobToken = jobToken;
electronRunJobLabel = label;
electronRunJobLogFile = logFile;
electronRunJobAborted = false;
}
return nodeChildProcess.spawnCapture(command, args, {
cwd: cwd,
env: env
env: env,
jobToken: jobToken
}, function(stream, chunk) {
appendProcessOutput(label, chunk, logFile);
}).then(function(result) {
if (electronRunJobToken === jobToken) {
electronRunJobToken = "";
electronRunJobLabel = "";
electronRunJobLogFile = "";
electronRunJobAborted = false;
}
if (result.error) {
let spawnMessage = label + " failed to start: " + result.error;
appendFitLog(logFile, label + " spawn failed: " + result.error + "\n");
@@ -829,6 +883,17 @@ function runLocalProcess(label, command, args, cwd, logFile, options = {}) {
err.result = result;
return { ok: 0, code: 1, signal: null, error: err };
}
if (result.signal) {
// Terminated by the Abort action (or an external signal). Report it
// distinctly so the run is not mistaken for a failed fit.
let abortMessage = label + " was aborted.";
appendFitLog(logFile, label + " aborted (signal " + result.signal + ")\n");
if (reportStatus && typeof finishJobStatus === "function") {
finishJobStatus(0, 0, abortMessage, "aborted");
}
return { ok: 0, code: result.code, signal: result.signal,
stdout: result.stdout, stderr: result.stderr, outcome: "aborted" };
}
let ok = result.ok === 1;
let code = result.code;
let signal = result.signal || "";
@@ -861,6 +926,8 @@ function runLocalProcess(label, command, args, cwd, logFile, options = {}) {
}
// Legacy streaming path kept for non-bridged environments (test sandboxes).
// No bridge token exists here, so Abort cannot reach this child.
electronRunJobToken = "";
return new Promise(function(resolve) {
let child;
let settled = false;
+45 -8
View File
@@ -895,18 +895,29 @@ function setMusrfitActionState(action = "", phase = "idle") {
let appShell = document.getElementById("appShell");
let fitIsActive = busy && normalizedAction == "fit";
let plotIsActive = busy && normalizedAction == "plot";
// Electron can kill the local process through the preload bridge, so the
// running button becomes an active "Abort". The Electron shim defines
// window.triggerMusrfitAbort at load time (before this library), so its
// presence is the capability signal; web jobs run server-side and the
// button stays disabled instead. The flag exists for tests and clarity.
let abortSupported = typeof window.triggerMusrfitAbort === "function"
|| window.MusrfitAction.abortSupported === true;
let fitAbortable = fitIsActive && normalizedPhase == "running" && abortSupported;
let plotAbortable = plotIsActive && normalizedPhase == "running" && abortSupported;
if (fitButton) {
fitButton.disabled = busy;
fitButton.textContent = "Fit";
fitButton.disabled = busy && !fitAbortable;
fitButton.textContent = fitAbortable ? "Abort" : "Fit";
fitButton.className = "action-btn action-btn-primary" + (fitIsActive ? " is-running" : "");
fitButton.setAttribute("aria-busy", fitIsActive ? "true" : "false");
setMusrfitAbortClick(fitButton, fitAbortable, "fit");
}
if (plotButton) {
plotButton.disabled = busy;
plotButton.textContent = "Plot";
plotButton.disabled = busy && !plotAbortable;
plotButton.textContent = plotAbortable ? "Abort" : "Plot";
plotButton.className = "action-btn action-btn-secondary" + (plotIsActive ? " is-running" : "");
plotButton.setAttribute("aria-busy", plotIsActive ? "true" : "false");
setMusrfitAbortClick(plotButton, plotAbortable, "plot");
}
let phaseMessage = "";
@@ -930,6 +941,31 @@ function setMusrfitActionState(action = "", phase = "idle") {
return window.MusrfitAction;
}
// Swap the running action button's click target to Abort and back. The original
// inline handler (startFit/startPlot) is captured on the first abortable render
// so it can be restored when the job finishes; without an original handler
// (tests, dynamic buttons) a null target simply disables the click.
function setMusrfitAbortClick(button, abortable, action) {
if (!abortable) {
if (button.__musrActionAbortAttached) {
button.__musrActionAbortAttached = false;
button.onclick = button.__musrOriginalClick || null;
}
return;
}
if (button.__musrActionAbortAttached) return;
if (!button.__musrOriginalClick) {
button.__musrOriginalClick = button.onclick;
}
button.__musrActionAbortAttached = true;
button.onclick = function(event) {
if (event && typeof event.preventDefault === "function") event.preventDefault();
if (typeof window.triggerMusrfitAbort === "function") {
window.triggerMusrfitAbort(action);
}
};
}
// musrfit and musrview use the same PRunDataHandler diagnostics when a RUN file
// cannot be resolved. Convert that verbose executable output into one structured
// workflow outcome while retaining every path for the detailed job log.
@@ -2959,7 +2995,8 @@ function beginJobStatus(actionName, fullPath, options) {
function finishJobStatus(ok, code, message, outcome = "") {
let missingData = outcome == "missing-data";
let state = missingData ? "Missing data" : (ok ? "Finished" : "Failed");
let aborted = outcome == "aborted";
let state = missingData ? "Missing data" : (aborted ? "Aborted" : (ok ? "Finished" : "Failed"));
let exitCode = "";
if (code !== undefined && code !== null) {
exitCode = code;
@@ -2968,7 +3005,7 @@ function finishJobStatus(ok, code, message, outcome = "") {
state: state,
message: message ? firstStatusLine(message) : state,
messageDetail: message ? message.toString() : state,
noticeLevel: missingData ? "warning" : (ok ? "success" : "error"),
noticeLevel: missingData ? "warning" : (aborted ? "warning" : (ok ? "success" : "error")),
finishedAt: jobTimestamp(),
exitCode: exitCode,
preparedForRun: false
@@ -2988,8 +3025,8 @@ function finishJobStatus(ok, code, message, outcome = "") {
let summaryText = message ? firstStatusLine(message) : state;
let detailText = message ? message.toString() : state;
if (dialog && title && summary && details) {
dialog.dataset.level = missingData ? "warning" : "error";
title.textContent = missingData ? "Data file not found" : "Action could not be completed";
dialog.dataset.level = missingData ? "warning" : (aborted ? "warning" : "error");
title.textContent = missingData ? "Data file not found" : (aborted ? "Action aborted" : "Action could not be completed");
summary.textContent = summaryText;
details.textContent = detailText;
details.hidden = detailText == summaryText;
+43
View File
@@ -67,6 +67,11 @@ function normalizeSyncResult(result) {
};
}
// Handles for running child processes, keyed by a caller-supplied job token.
// The renderer keeps the token for the last launched job, so an Abort action
// can target exactly that job without ever exposing PIDs into the page.
const runningJobs = {};
const bridge = {
ipc: {
on: function (channel, listener) {
@@ -209,6 +214,15 @@ readFile: function (p, encoding, callback) {
let stdoutText = "";
let stderrText = "";
let settled = false;
const jobKey = options && options.jobToken ? String(options.jobToken) : "";
const unregister = function () {
if (!jobKey) return;
const entry = runningJobs[jobKey];
if (entry) {
if (entry.killTimer) clearTimeout(entry.killTimer);
delete runningJobs[jobKey];
}
};
const emit = function (label, chunk) {
stdoutText += chunk;
if (typeof onChunk === "function") onChunk(label, chunk);
@@ -222,19 +236,48 @@ readFile: function (p, encoding, callback) {
resolve({ ok: 0, code: 1, signal: null, stdout: "", stderr: "", error: err.message || String(err) });
return;
}
if (jobKey) {
runningJobs[jobKey] = { child: child, done: false, killTimer: null, escalated: false };
}
child.stdout.on("data", function (chunk) { emit("stdout", chunk.toString()); });
child.stderr.on("data", function (chunk) { emit("stderr", chunk.toString()); });
child.on("error", function (err) {
if (settled) return;
settled = true;
unregister();
resolve({ ok: 0, code: 1, signal: null, stdout: stdoutText, stderr: stderrText, error: err.message || String(err) });
});
child.on("close", function (code, signal) {
if (settled) return;
settled = true;
unregister();
resolve({ ok: code === 0 ? 1 : 0, code: code, signal: signal, stdout: stdoutText, stderr: stderrText, error: null });
});
});
},
// Kill the last launched job (SIGTERM, then SIGKILL after a grace
// period). Returns { ok: false } when the token is unknown or already
// finished so the renderer can stop expecting that job to abort.
abortJob: function (token, signal) {
const key = String(token == null ? "" : token);
const entry = runningJobs[key];
if (!entry || entry.done) return { ok: false, code: "no-such-job" };
const sig = signal || "SIGTERM";
try {
if (!entry.escalated) {
entry.escalated = true;
entry.child.kill(sig);
entry.killTimer = setTimeout(function () {
const live = runningJobs[key];
if (live && !live.done) {
try { live.child.kill("SIGKILL"); } catch (ignore) {}
}
}, 3000);
}
} catch (err) {
return { ok: false, code: err && err.message ? err.message : String(err) };
}
return { ok: true, code: sig };
}
}
};
+49 -3
View File
@@ -131,6 +131,48 @@ async function testActionLifecycleReleasesControls() {
assert.strictEqual(elements.PlotMSR.disabled, false);
}
async function testAbortButtonMorph() {
sandbox.window.MusrfitAction.abortSupported = true;
let aborted = [];
sandbox.window.triggerMusrfitAbort = function(action) {
aborted.push(action);
};
sandbox.setMusrfitActionState("fit", "running");
assert.strictEqual(sandbox.window.MusrfitAction.busy, true);
assert.strictEqual(elements.FitMSR.disabled, false);
assert.strictEqual(elements.FitMSR.textContent, "Abort");
assert.match(elements.FitMSR.className, /\bis-running\b/);
assert.strictEqual(elements.PlotMSR.disabled, true);
assert.strictEqual(elements.PlotMSR.textContent, "Plot");
assert.strictEqual(elements.musrfitActionActivityText.textContent, "Running musrfit");
if (typeof elements.FitMSR.onclick === "function") {
elements.FitMSR.onclick({ preventDefault: function() {} });
}
assert.deepStrictEqual(aborted, ["fit"]);
sandbox.setMusrfitActionState("plot", "running");
assert.strictEqual(elements.PlotMSR.disabled, false);
assert.strictEqual(elements.PlotMSR.textContent, "Abort");
assert.match(elements.PlotMSR.className, /\bis-running\b/);
assert.strictEqual(elements.FitMSR.disabled, true);
assert.strictEqual(elements.FitMSR.textContent, "Fit");
if (typeof elements.PlotMSR.onclick === "function") {
elements.PlotMSR.onclick({ preventDefault: function() {} });
}
assert.deepStrictEqual(aborted, ["fit", "plot"]);
sandbox.setMusrfitActionState("", "idle");
assert.strictEqual(sandbox.window.MusrfitAction.busy, false);
assert.strictEqual(elements.FitMSR.disabled, false);
assert.strictEqual(elements.FitMSR.textContent, "Fit");
assert.strictEqual(elements.PlotMSR.disabled, false);
assert.strictEqual(elements.PlotMSR.textContent, "Plot");
sandbox.window.MusrfitAction.abortSupported = false;
delete sandbox.window.triggerMusrfitAbort;
}
function testMissingDataDialog() {
sandbox.renderJobStatus = function() {
};
@@ -162,9 +204,13 @@ function testActionMarkup() {
}
testActionControlStates();
testMissingDataDialog();
testActionMarkup();
testDuplicateActionGuard().then(function() {
testAbortButtonMorph().then(function() {
return testMissingDataDialog();
}).then(function() {
return testActionMarkup();
}).then(function() {
return testDuplicateActionGuard();
}).then(function() {
return testActionLifecycleReleasesControls();
}).then(function() {
console.log("Main action state tests passed");
+138
View File
@@ -27,6 +27,7 @@ function toText(value) {
}
function makeBridge() {
const spawnJobs = {};
const bridge = {
ipc: {
on: function (channel, listener) {
@@ -71,6 +72,18 @@ function makeBridge() {
const child = childProcess.spawn(command, args || [], Object.assign({}, options, {
shell: false, stdio: ["ignore", "pipe", "pipe"]
}));
const jobKey = options && options.jobToken ? String(options.jobToken) : "";
const unregister = function () {
if (!jobKey) return;
const entry = spawnJobs[jobKey];
if (entry) {
if (entry.timer) clearTimeout(entry.timer);
delete spawnJobs[jobKey];
}
};
if (jobKey) {
spawnJobs[jobKey] = { child: child, done: false, timer: null, escalated: false };
}
let stdoutText = "";
let stderrText = "";
child.stdout.on("data", function (chunk) {
@@ -84,14 +97,39 @@ function makeBridge() {
if (typeof onChunk === "function") onChunk("stderr", text);
});
child.on("error", function (err) {
unregister();
resolve({ ok: 0, code: 1, signal: null, stdout: stdoutText, stderr: stderrText,
error: err.message });
});
child.on("close", function (code, signal) {
unregister();
resolve({ ok: code === 0 ? 1 : 0, code: code, signal: signal,
stdout: stdoutText, stderr: stderrText, error: null });
});
});
},
// Mirrors the preload bridge: kill the child identified by the job
// token (SIGTERM, then SIGKILL after a grace period).
abortJob: function (token, signal) {
const key = String(token == null ? "" : token);
const entry = spawnJobs[key];
if (!entry || entry.done) return { ok: false, code: "no-such-job" };
const sig = signal || "SIGTERM";
try {
if (!entry.escalated) {
entry.escalated = true;
entry.child.kill(sig);
entry.timer = setTimeout(function () {
const live = spawnJobs[key];
if (live && !live.done) {
try { live.child.kill("SIGKILL"); } catch (ignore) {}
}
}, 3000);
}
} catch (err) {
return { ok: false, code: err.message };
}
return { ok: true, code: sig };
}
}
};
@@ -373,6 +411,98 @@ function testElectronShareCopyUsesBridgeClipboard() {
});
}
// Abort must kill a running child process (SIGTERM), and the bridge entry must
// be gone afterwards so a second abort reports no such job.
function testPreloadAbortJobKillsProcess() {
return new Promise(function(resolve, reject) {
const bridge = makeBridge();
const started = Date.now();
const run = bridge.childProcess.spawnCapture("sleep", ["60"], { jobToken: "aborttest" }, function() {});
let settled = false;
function settle(fn) {
if (settled) return;
settled = true;
fn();
}
setTimeout(function() {
settle(function() {
try {
const first = bridge.childProcess.abortJob("aborttest", "SIGTERM");
assert.strictEqual(first.ok, true);
assert.strictEqual(first.code, "SIGTERM");
} catch (err) {
reject(err);
}
});
}, 150);
run.then(function(result) {
settle(function() {
try {
assert.strictEqual(result.signal, "SIGTERM");
assert.ok(Date.now() - started < 5000, "aborted child should exit before sleep 60 ends");
const late = bridge.childProcess.abortJob("aborttest", "SIGTERM");
assert.strictEqual(late.ok, false);
assert.strictEqual(late.code, "no-such-job");
} catch (err) {
return reject(err);
}
resolve();
});
}).catch(reject);
});
}
// The renderer-level Abort path: window.triggerMusrfitAbort() ends the last
// launched runLocalProcess job through the bridge and reports an "aborted"
// outcome instead of a failed fit.
function testElectronAbortEndsRunningJob() {
return new Promise(function(resolve, reject) {
const bridge = makeBridge();
const { lib } = load(bridge);
lib.updateJobStatus = function() {};
lib.appendJobLog = function() {};
const logFile = path.join(testRoot, "abort-run.out");
fs.writeFileSync(logFile, "");
let captured = null;
lib.finishJobStatus = function(ok, code, message, outcome) {
captured = { ok: ok, code: code, message: message, outcome: outcome };
};
assert.strictEqual(lib.window.MusrfitAction.abortSupported, true);
assert.strictEqual(typeof lib.window.triggerMusrfitAbort, "function");
const run = lib.runLocalProcess("sleep probe", "sleep", ["60"], testRoot, logFile);
let settled = false;
function settle(fn) {
if (settled) return;
settled = true;
fn();
}
setTimeout(function() {
settle(function() {
try {
assert.strictEqual(lib.window.triggerMusrfitAbort("fit"), true);
} catch (err) {
reject(err);
}
});
}, 150);
run.then(function(result) {
settle(function() {
try {
assert.strictEqual(result.outcome, "aborted");
assert.strictEqual(result.signal, "SIGTERM");
assert.strictEqual(captured.outcome, "aborted");
assert.match(String(captured.message), /aborted/);
} catch (err) {
return reject(err);
}
resolve();
});
}).catch(reject);
});
}
// The main process must start the MSR dialogs in the last used folder and
// persist that folder after a successful open or save.
function testMainRemembersMSRDialogDirectory() {
@@ -412,6 +542,14 @@ testElectronShareCopyUsesBridgeClipboard().catch(function(error) {
console.error(error);
process.exit(1);
});
testPreloadAbortJobKillsProcess().catch(function(error) {
console.error(error);
process.exit(1);
});
testElectronAbortEndsRunningJob().catch(function(error) {
console.error(error);
process.exit(1);
});
testMainProcessDialogRouting();
testMainRemembersMSRDialogDirectory();