diff --git a/CHANGELOG.md b/CHANGELOG.md
index bca49a5..45bb95e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -86,6 +86,12 @@ release path documented in [`TODO.md`](TODO.md).
selection and actual RUN/ADDRUN entries in the MSR.
### Bundled ROOT + musrfit runtime
+- Linux Preferences now offers **Check tools** and confirmed offline runtime
+ installation from `runtime-download.json`. Installs verify the archive and
+ extracted tools in a private user directory, support cancellation, and retain
+ existing system/user installations. A successful **Install and use** selects
+ the private tools and their matching ROOT environment; merely installing
+ files does not override host tool selection. Windows WSL behavior is unchanged.
- Linux release commands now produce a standalone `.tar.gz` runtime download,
SHA-256 sidecar, and versioned JSON download descriptor. The builder validates
a private snapshot and publishes complete, content-addressed bundles under
diff --git a/TODO.md b/TODO.md
index d82adbb..44695d9 100644
--- a/TODO.md
+++ b/TODO.md
@@ -447,6 +447,11 @@ These defense-in-depth tasks are intentionally deferred until after the stable
`1.0.0` workflow release. Pre-1.0 changes should remain focused on reliable fit,
plot, editor, synchronization, and result-collection behavior.
+- [ ] Review the existing Electron/undici advisories reported by `npm audit` and
+ test dependency upgrades separately from runtime-installation workflow
+ changes. The new archive extractor is pinned; unrelated upgrades were not
+ applied during the offline installer work.
+
- [ ] Validate shared-configuration links against a strict schema before they
mutate GUI state. Restrict control and parameter identifiers, value types,
model names, constraint sizes, and detector-map definitions.
diff --git a/ZGUI.css b/ZGUI.css
index 6fc9e13..5b67181 100644
--- a/ZGUI.css
+++ b/ZGUI.css
@@ -2397,6 +2397,17 @@ button:not(.tablinks):not(.action-btn):not(.editor-source-tab):not(.status-state
width: 100%;
}
+.runtime-setup-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+#localRuntimeStatus {
+ white-space: pre-line;
+ overflow-wrap: anywhere;
+}
+
.preferences-hint {
display: block;
color: var(--mu-green-muted);
diff --git a/docs/DESKTOP_DEPLOYMENT.md b/docs/DESKTOP_DEPLOYMENT.md
index 6eaf3fc..fb2cf96 100644
--- a/docs/DESKTOP_DEPLOYMENT.md
+++ b/docs/DESKTOP_DEPLOYMENT.md
@@ -125,8 +125,11 @@ The plain runtime download can also be checked with its SHA-256 sidecar and
extracted into a fresh user-writable directory, without administrator access or
FUSE. Set `MUSRFLOW_RUNTIME_ROOT` to the extracted `runtime/` directory. See the
[runtime packaging guide](../packaging/runtime/README.md#download-archive) for
-the archive layout and descriptor format. Optional in-app download/installation
-will build on this format; the application does not download runtimes yet.
+the archive layout and descriptor format. On Linux, **File -> Preferences ->
+Install runtime...** installs a downloaded bundle after confirmation and selects
+its verified tools. **Check tools** tests the saved tool selection. In-app online
+downloads and missing-tool startup prompts will follow separately; no runtime
+is downloaded automatically.
## Configuration link scheme
diff --git a/index.html b/index.html
index 318e46e..2e025e7 100644
--- a/index.html
+++ b/index.html
@@ -767,6 +767,14 @@ pairs of a multi-run (global) fit.">
Directory holding musrfit, musrview, msr2data and dump_header
+
+
+ Check tools
+ Install runtime...
+ Cancel installation
+
+
Use an existing installation, or install a local runtime download bundle.
+
musrfit threads
diff --git a/local-runtime.js b/local-runtime.js
new file mode 100644
index 0000000..47cbf24
--- /dev/null
+++ b/local-runtime.js
@@ -0,0 +1,258 @@
+// Copyright (C) 2026 Zaher Salman
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+// Main-process offline runtime installation. New files are verified in a private
+// staging directory; neither system tools nor previously installed trees change.
+const fs = require('fs');
+const path = require('path');
+const os = require('os');
+const { createHash, randomUUID } = require('crypto');
+const { execFile } = require('child_process');
+const { promisify, isDeepStrictEqual } = require('util');
+const { Transform } = require('stream');
+const { pipeline } = require('stream/promises');
+const tar = require('tar');
+
+const execute = promisify(execFile);
+const TOOLS = ['musrfit', 'musrview', 'msr2data', 'dump_header', 'musrt0'];
+const FILES = TOOLS.concat('root-config').map(function(name) {
+ return 'bin/' + name;
+}).concat(['lib/libCore.so', 'lib/libPMusr.so']);
+
+async function hashFile(filename, signal) {
+ const hash = createHash('sha256');
+ for await (const chunk of fs.createReadStream(filename, { signal: signal })) {
+ hash.update(chunk);
+ }
+ return hash.digest('hex');
+}
+
+class LocalRuntime {
+ constructor(options) {
+ this.directory = path.resolve(options.directory);
+ this.platform = options.platform || process.platform;
+ this.arch = options.arch || process.arch;
+ this.timeout = options.timeout || 5000;
+ }
+
+ async checkTools(input, signal) {
+ const results = [];
+ for (const name of TOOLS) {
+ const command = input.commands && input.commands[name];
+ if (typeof command !== 'string' || path.basename(command) !== name) {
+ results.push({ name: name, ok: false, error: 'No executable selected.' });
+ continue;
+ }
+ try {
+ const result = await execute(command, ['--version'], {
+ env: input.env || process.env, cwd: os.tmpdir(), timeout: this.timeout,
+ maxBuffer: 1024 * 1024, killSignal: 'SIGKILL', signal: signal
+ });
+ const version = result.stdout.match(/version:\s*([^,\s]+)/i);
+ results.push({ name: name, command: command, ok: true,
+ version: version ? version[1] : 'available', output: result.stdout });
+ } catch (error) {
+ if (signal && signal.aborted) throw error;
+ results.push({ name: name, command: command, ok: false,
+ error: error.killed ? 'Version check timed out.' : (error.stderr || error.message).trim() });
+ }
+ }
+ return { ok: results.every(function(result) { return result.ok; }), tools: results };
+ }
+
+ async inspectBundle(descriptorPath) {
+ if (this.platform !== 'linux' || !['x64', 'arm64'].includes(this.arch)) {
+ throw new Error('Native runtime installation currently supports Linux x64/arm64 only.');
+ }
+ const source = await fs.promises.realpath(descriptorPath);
+ const stat = await fs.promises.stat(source);
+ if (!stat.isFile() || stat.size > 1024 * 1024) throw new Error('Invalid runtime download descriptor.');
+ const descriptor = JSON.parse(await fs.promises.readFile(source, 'utf8'));
+ const runtime = descriptor.runtime;
+ const artifact = descriptor.artifact;
+ if (descriptor.schemaVersion !== 1 || descriptor.kind !== 'musrflow-runtime-download'
+ || !runtime || runtime.schemaVersion !== 1 || runtime.platform !== this.platform || runtime.arch !== this.arch
+ || !runtime.root || !runtime.musrfit || typeof runtime.root.version !== 'string'
+ || typeof runtime.musrfit.version !== 'string' || typeof runtime.runtimeId !== 'string'
+ || !runtime.files || Array.isArray(runtime.files)
+ || FILES.some(function(name) { return typeof runtime.files[name] !== 'string' || !/^[0-9a-f]{64}$/.test(runtime.files[name]); })
+ || !artifact || artifact.format !== 'tar.gz' || artifact.rootDirectory !== 'runtime'
+ || typeof artifact.filename !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]*\.tar\.gz$/.test(artifact.filename)
+ || typeof artifact.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(artifact.sha256)
+ || !Number.isSafeInteger(artifact.size) || artifact.size <= 0 || artifact.size > 8 * 1024 ** 3) {
+ throw new Error('The runtime descriptor is invalid or does not match this computer (' + this.platform + '/' + this.arch + ').');
+ }
+ const archive = path.join(path.dirname(source), artifact.filename);
+ const archiveStat = await fs.promises.lstat(archive);
+ if (!archiveStat.isFile() || archiveStat.size !== artifact.size) {
+ throw new Error('The archive is missing or has the wrong size. Keep it beside runtime-download.json.');
+ }
+ return { descriptor: descriptor, archive: archive,
+ destination: path.join(this.directory, artifact.sha256, 'runtime') };
+ }
+
+ async verifyInstalled(root, runtime, signal) {
+ const manifest = JSON.parse(await fs.promises.readFile(path.join(root, 'runtime-manifest.json'), 'utf8'));
+ if (!isDeepStrictEqual(manifest, runtime)) throw new Error('The extracted runtime manifest does not match the download.');
+ for (const relative of FILES) {
+ if (signal) signal.throwIfAborted();
+ const filename = path.join(root, relative);
+ const resolved = await fs.promises.realpath(filename);
+ if (!resolved.startsWith(root + path.sep)) throw new Error('Runtime file points outside its installation: ' + relative);
+ if (!(await fs.promises.stat(resolved)).isFile()) throw new Error('Runtime file is not a regular file: ' + relative);
+ if (await hashFile(filename, signal) !== runtime.files[relative]) {
+ throw new Error('Runtime file verification failed: ' + relative);
+ }
+ if (relative.startsWith('bin/')) await fs.promises.access(filename, fs.constants.X_OK);
+ if (relative.startsWith('lib/')) {
+ const handle = await fs.promises.open(filename, 'r');
+ try {
+ const header = Buffer.alloc(20);
+ await handle.read(header, 0, 20, 0);
+ if (header.toString('hex', 0, 4) !== '7f454c46' || header[4] !== 2 || header[5] !== 1
+ || header.readUInt16LE(18) !== (this.arch === 'x64' ? 62 : 183)) {
+ throw new Error('Runtime library architecture does not match this computer.');
+ }
+ } finally {
+ await handle.close();
+ }
+ }
+ }
+ const startupPath = path.join(root, 'musrfit_startup.xml');
+ const startup = await fs.promises.stat(startupPath);
+ if (!startup.isFile() || startup.size === 0) throw new Error('Runtime startup XML is missing or empty.');
+ await fs.promises.access(startupPath, fs.constants.R_OK);
+ const commands = {};
+ for (const name of TOOLS) commands[name] = path.join(root, 'bin', name);
+ const env = Object.assign({}, process.env, { ROOTSYS: root, MUSRFITPATH: root,
+ LD_LIBRARY_PATH: path.join(root, 'lib'), PATH: path.join(root, 'bin') + ':/usr/bin:/bin' });
+ delete env.LD_PRELOAD;
+ const result = await this.checkTools({ commands: commands, env: env }, signal);
+ const failed = result.tools.find(function(tool) { return !tool.ok; });
+ if (failed) throw new Error(failed.name + ' cannot start: ' + failed.error);
+ for (const tool of result.tools) {
+ const reportedRoot = tool.output.match(/ROOT version:\s*([^,\s]+)/);
+ if (tool.version !== runtime.musrfit.version || !reportedRoot
+ || reportedRoot[1].replace('/', '.') !== runtime.root.version
+ || (runtime.musrfit.revision && !tool.output.includes(runtime.musrfit.revision))) {
+ throw new Error(tool.name + ' reports a different runtime version.');
+ }
+ }
+ return root;
+ }
+
+ async install(plan, signal, onProgress) {
+ const descriptor = plan.descriptor;
+ const artifact = descriptor.artifact;
+ let lastPhase = '';
+ let lastUpdate = 0;
+ const progress = function(state) {
+ if (state.phase !== lastPhase || Date.now() - lastUpdate > 150) {
+ lastPhase = state.phase;
+ lastUpdate = Date.now();
+ if (onProgress) onProgress(state);
+ }
+ };
+ signal.throwIfAborted();
+ await fs.promises.mkdir(this.directory, { recursive: true, mode: 0o700 });
+ const stage = await fs.promises.mkdtemp(path.join(this.directory, '.install-'));
+ try {
+ progress({ phase: 'Verifying runtime archive' });
+ const archive = path.join(stage, 'runtime.tar.gz');
+ const digest = createHash('sha256');
+ let bytes = 0;
+ const verifier = new Transform({ transform: function(chunk, encoding, callback) {
+ bytes += chunk.length;
+ if (bytes > artifact.size) return callback(new Error('The runtime archive changed during installation.'));
+ digest.update(chunk);
+ progress({ phase: 'Verifying runtime archive', received: bytes, total: artifact.size });
+ callback(null, chunk);
+ } });
+ await pipeline(fs.createReadStream(plan.archive), verifier,
+ fs.createWriteStream(archive, { flags: 'wx' }), { signal: signal });
+ if (bytes !== artifact.size || digest.digest('hex') !== artifact.sha256) {
+ throw new Error('Runtime archive SHA-256 verification failed. Nothing was installed.');
+ }
+
+ progress({ phase: 'Checking archive contents' });
+ const entries = new Set();
+ const links = new Set();
+ let unpackedBytes = 0;
+ let invalid = '';
+ await tar.t({ file: archive, strict: true, filter: function(rawName, entry) {
+ const name = entry.path.replace(/\/$/, '');
+ if (!name.startsWith('runtime/') && name !== 'runtime') invalid = 'Unexpected archive root.';
+ if (/[\\\x00-\x1f]/.test(name) || name.split('/').some(function(part) { return !part || part === '.' || part === '..'; })
+ || entries.has(name) || !['File', 'Directory', 'SymbolicLink'].includes(entry.type)) {
+ invalid = 'Unsafe or duplicate runtime archive entry.';
+ }
+ entries.add(name);
+ if (entry.type === 'SymbolicLink') {
+ const target = path.posix.normalize(path.posix.join(path.posix.dirname(name), entry.linkpath));
+ if (/[\\\x00-\x1f]/.test(entry.linkpath) || path.posix.isAbsolute(entry.linkpath)
+ || (target !== 'runtime' && !target.startsWith('runtime/'))) invalid = 'Unsafe runtime library link.';
+ links.add(name);
+ }
+ unpackedBytes += entry.size;
+ if (!Number.isSafeInteger(unpackedBytes) || unpackedBytes > 8 * 1024 ** 3 || entries.size > 200000) {
+ invalid = 'Runtime archive expands beyond the supported size.';
+ }
+ if (invalid || signal.aborted) {
+ this.abort(new Error(invalid || 'Runtime installation cancelled.'));
+ return false;
+ }
+ return true;
+ } });
+ signal.throwIfAborted();
+ if (invalid) throw new Error(invalid);
+ for (const name of entries) {
+ const parts = name.split('/');
+ parts.pop();
+ while (parts.length) {
+ if (links.has(parts.join('/'))) throw new Error('Runtime archive writes through a symbolic link.');
+ parts.pop();
+ }
+ }
+ const available = await fs.promises.statfs(stage);
+ if (available.bavail * available.bsize < unpackedBytes + 16 * 1024 * 1024) {
+ throw new Error('Not enough free disk space to install the runtime.');
+ }
+ progress({ phase: 'Extracting runtime' });
+ signal.throwIfAborted();
+ const extracted = path.join(stage, 'extracted');
+ await fs.promises.mkdir(extracted);
+ // Let queued writes finish before removing staging on cancellation;
+ // later entries are skipped and nothing is activated afterwards.
+ await tar.x({ file: archive, cwd: extracted, strict: true,
+ preserveOwner: false, chmod: true, processUmask: 0o022,
+ filter: function(name, entry) {
+ entry.mode &= 0o777;
+ return !signal.aborted;
+ }
+ });
+ signal.throwIfAborted();
+ progress({ phase: 'Checking installed tools' });
+ const root = path.join(extracted, 'runtime');
+ await this.verifyInstalled(root, descriptor.runtime, signal);
+ signal.throwIfAborted();
+ let destination = path.dirname(plan.destination);
+ if (fs.existsSync(destination)) {
+ try {
+ await this.verifyInstalled(path.join(destination, 'runtime'), descriptor.runtime, signal);
+ return { ok: true, root: path.join(destination, 'runtime'), reused: true };
+ } catch (error) {
+ signal.throwIfAborted();
+ // Keep a damaged/older tree intact; a fresh sibling permits
+ // repair without changing files a running musrview may use.
+ destination += '-' + randomUUID();
+ }
+ }
+ await fs.promises.rename(extracted, destination);
+ return { ok: true, root: path.join(destination, 'runtime'), reused: false };
+ } finally {
+ await fs.promises.rm(stage, { recursive: true, force: true });
+ }
+ }
+}
+
+module.exports = { LocalRuntime, TOOLS };
diff --git a/main.js b/main.js
index 38eaaa9..498324c 100644
--- a/main.js
+++ b/main.js
@@ -7,8 +7,11 @@ const fs = require('fs');
const childProcess = require('child_process');
const wslRuntime = require('./wsl-runtime');
const { RunDataDownloader } = require('./run-data-download');
+const { LocalRuntime } = require('./local-runtime');
let runDataDownloader = null;
let runDataJob = null;
+let localRuntime = null;
+let localRuntimeJob = null;
// An SSH-forwarded X display belongs to the remote client, but pc13280 also
// exposes the user's persistent local desktop D-Bus session. Electron otherwise
@@ -404,6 +407,10 @@ if (relaunchingForForwardedX11) {
directory: path.join(app.getPath('userData'), 'run-data'),
fetch: net.fetch.bind(net)
});
+ localRuntime = new LocalRuntime({ directory: path.join(app.getPath('userData'), 'runtimes') });
+ // The renderer only treats a configured tools directory inside this
+ // private tree as managed. Existing host tool selection is unchanged.
+ process.env.MUSRFLOW_MANAGED_RUNTIME_DIRECTORY = localRuntime.directory;
createWindow();
setupWslRuntime();
});
@@ -465,6 +472,59 @@ ipcMain.handle("ensureWslRuntime", function () {
return setupWslRuntime();
});
+ipcMain.handle('checkLocalRuntime', async function(event, input) {
+ if (!mainWindow || event.sender !== mainWindow.webContents) throw new Error('Invalid runtime window.');
+ return localRuntime.checkTools(input || {});
+});
+
+ipcMain.handle('installLocalRuntime', async function(event, token) {
+ if (!mainWindow || event.sender !== mainWindow.webContents) throw new Error('Invalid runtime window.');
+ if (process.platform !== 'linux') return { ok: false, message: 'Offline runtime installation currently supports Linux only.' };
+ if (localRuntimeJob) return { ok: false, message: 'A runtime installation is already running.' };
+ if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/.test(token)) {
+ return { ok: false, message: 'Invalid runtime installation request.' };
+ }
+ const controller = new AbortController();
+ localRuntimeJob = { token: token, controller: controller };
+ try {
+ const selection = await dialog.showOpenDialog(mainWindow, {
+ title: 'Select runtime-download.json', properties: ['openFile'],
+ filters: [{ name: 'Runtime download descriptor', extensions: ['json'] }]
+ });
+ if (selection.canceled || !selection.filePaths.length) return { ok: false, cancelled: true };
+ controller.signal.throwIfAborted();
+ const plan = await localRuntime.inspectBundle(selection.filePaths[0]);
+ controller.signal.throwIfAborted();
+ const confirmation = await dialog.showMessageBox(mainWindow, {
+ type: 'question', title: 'Install muSRFlow runtime',
+ message: 'Install this runtime and use it for future fits and plots?',
+ detail: 'Install only bundles from a trusted source: they contain executable programs.\n\n'
+ + 'ROOT ' + plan.descriptor.runtime.root.version + ' / musrfit ' + plan.descriptor.runtime.musrfit.version
+ + '\nArchive: ' + (plan.descriptor.artifact.size / 1000000).toFixed(1) + ' MB'
+ + '\nSource: ' + selection.filePaths[0] + '\nInstall to: ' + plan.destination
+ + '\n\nSystem installations and your startup XML files will not be changed.',
+ buttons: ['Install and use', 'Cancel'], defaultId: 1, cancelId: 1
+ });
+ if (confirmation.response !== 0) return { ok: false, cancelled: true };
+ return await localRuntime.install(plan, controller.signal, function(state) {
+ if (!event.sender.isDestroyed()) {
+ event.sender.send('localRuntimeProgress', Object.assign({ token: token }, state));
+ }
+ });
+ } catch (error) {
+ return { ok: false, cancelled: controller.signal.aborted, message: error.message || String(error) };
+ } finally {
+ localRuntimeJob = null;
+ }
+});
+
+ipcMain.handle('cancelLocalRuntime', function(event, token) {
+ if (!mainWindow || event.sender !== mainWindow.webContents) throw new Error('Invalid runtime window.');
+ if (!localRuntimeJob || localRuntimeJob.token !== token) return false;
+ localRuntimeJob.controller.abort();
+ return true;
+});
+
ipcMain.handle('runDataConfiguration', async function(event) {
if (event.sender !== mainWindow.webContents) throw new Error('Invalid download window.');
return { directory: runDataDownloader.directory, files: await runDataDownloader.localFiles() };
diff --git a/muSRFitelec.js b/muSRFitelec.js
index 664fac6..0f00191 100644
--- a/muSRFitelec.js
+++ b/muSRFitelec.js
@@ -81,6 +81,9 @@ var electronRunJobSeq = 0;
var electronRunDataFiles = [];
var electronRunDataReady = null;
var electronRunDataToken = '';
+var electronRuntimeInstalling = false;
+var electronRuntimeChecking = false;
+var electronRuntimeToken = '';
function electronRequestAbort(action) {
if (electronRunDataToken && window.electronAPI && window.electronAPI.runData) {
@@ -957,6 +960,114 @@ function openElectronPreferences() {
} else {
preferences.setAttribute("open", "");
}
+ let runtimeControls = document.getElementById("localRuntimeControls");
+ if (runtimeControls) {
+ runtimeControls.hidden = nodeProcess.platform !== "linux" || !window.electronAPI || !window.electronAPI.localRuntime;
+ if (!runtimeControls.hidden && !electronRuntimeInstalling) checkElectronRuntime();
+ }
+}
+
+function showElectronRuntimeStatus(message) {
+ let status = document.getElementById("localRuntimeStatus");
+ if (status) status.textContent = message;
+ if (electronRuntimeInstalling && typeof setFitStatus === "function") setFitStatus(message);
+ let check = document.getElementById("runtimeCheck");
+ let install = document.getElementById("runtimeInstall");
+ let cancel = document.getElementById("runtimeCancel");
+ if (check) check.disabled = electronRuntimeInstalling || electronRuntimeChecking;
+ if (install) install.disabled = electronRuntimeInstalling || electronRuntimeChecking;
+ if (cancel) cancel.hidden = !electronRuntimeInstalling;
+}
+
+async function checkElectronRuntime() {
+ let api = window.electronAPI && window.electronAPI.localRuntime;
+ if (!api || electronRuntimeInstalling || electronRuntimeChecking) return;
+ electronRuntimeChecking = true;
+ showElectronRuntimeStatus("Checking the active musrfit tools...");
+ try {
+ let commands = {};
+ for (let name of ["musrfit", "musrview", "msr2data", "dump_header", "musrt0"]) {
+ commands[name] = resolveLocalCommand(name);
+ }
+ let result = await api.check({ commands: commands, env: buildToolEnvironment() });
+ let text = "Some active tools cannot start:";
+ if (result.ok) {
+ let first = result.tools[0];
+ let root = first.output && first.output.match(/ROOT version:\s*([^,\s]+)/);
+ text = "musrfit " + first.version + (root ? " / ROOT " + root[1] : "")
+ + "; all five tools are available.\n" + nodePath.dirname(first.command);
+ } else {
+ for (let tool of result.tools) {
+ if (!tool.ok) text += "\n" + tool.name + ": " + tool.error;
+ }
+ }
+ showElectronRuntimeStatus(text);
+ } catch (error) {
+ showElectronRuntimeStatus("Could not check musrfit tools: " + error.message);
+ } finally {
+ electronRuntimeChecking = false;
+ let status = document.getElementById("localRuntimeStatus");
+ showElectronRuntimeStatus(status ? status.textContent : "");
+ }
+}
+
+async function installElectronRuntime() {
+ let api = window.electronAPI && window.electronAPI.localRuntime;
+ if (!api || electronRuntimeInstalling || electronRuntimeChecking) return;
+ if (window.MusrfitAction && window.MusrfitAction.busy) {
+ showElectronRuntimeStatus("Finish the current fit or plot before installing a runtime.");
+ return;
+ }
+ electronRuntimeInstalling = true;
+ electronRuntimeToken = "runtime-" + Date.now();
+ showElectronRuntimeStatus("Choose runtime-download.json from a downloaded runtime bundle.");
+ for (let id of ["FitMSR", "PlotMSR"]) {
+ let button = document.getElementById(id);
+ if (button) button.disabled = true;
+ }
+ let unsubscribe = api.onProgress(function(state) {
+ if (state.token !== electronRuntimeToken) return;
+ let message = state.phase + "...";
+ if (state.total) message += " " + (state.received / 1000000).toFixed(1) + " / " + (state.total / 1000000).toFixed(1) + " MB";
+ showElectronRuntimeStatus(message);
+ });
+ try {
+ let result = await api.install(electronRuntimeToken);
+ if (result.ok) {
+ let binDir = nodePath.join(result.root, "bin");
+ setConfiguredBinDir(binDir, true);
+ // Installation is a separate, explicitly confirmed action. Cancelling
+ // unrelated Preferences edits afterwards must not appear to undo it.
+ let preferences = document.getElementById("preferencesDialog");
+ let selected = getConfiguredBinDir() === binDir;
+ if (preferences && selected) preferences.dataset.originalBinDir = binDir;
+ if (selected && typeof reloadLocalPortableRunNaming === "function") reloadLocalPortableRunNaming();
+ showElectronRuntimeStatus(selected
+ ? "Runtime installed and selected:\n" + result.root
+ : "Runtime installed, but the binaries preference could not be saved:\n" + result.root);
+ } else {
+ showElectronRuntimeStatus(result.cancelled ? "Runtime installation cancelled. Previous tools were kept."
+ : "Runtime installation failed: " + result.message);
+ }
+ } catch (error) {
+ showElectronRuntimeStatus("Runtime installation failed: " + error.message);
+ } finally {
+ unsubscribe();
+ electronRuntimeToken = "";
+ electronRuntimeInstalling = false;
+ wslRuntimeGateMessage = "";
+ let status = document.getElementById("localRuntimeStatus");
+ showElectronRuntimeStatus(status ? status.textContent : "");
+ if (typeof setMusrfitActionState === "function") setMusrfitActionState("", "idle");
+ }
+}
+
+function cancelElectronRuntimeInstall() {
+ let api = window.electronAPI && window.electronAPI.localRuntime;
+ if (api && electronRuntimeToken) {
+ api.cancel(electronRuntimeToken);
+ showElectronRuntimeStatus("Cancelling runtime installation...");
+ }
}
function closeElectronPreferences() {
@@ -1225,6 +1336,16 @@ function systemRuntimeBinDir() {
// spawned tools: a runtime bundled inside the app wins, then a separately
// installed one.
function activeRuntimeRoot() {
+ // Only an explicitly selected private runtime changes the tool environment.
+ // Merely installing one must not shadow a working host installation.
+ let managed = nodeProcess.env && nodeProcess.env.MUSRFLOW_MANAGED_RUNTIME_DIRECTORY;
+ let configured = typeof getConfiguredBinDir === "function" ? getConfiguredBinDir() : "";
+ if (managed && configured && nodePath.basename(configured) === "bin") {
+ let root = nodePath.dirname(nodePath.resolve(configured));
+ if (root.startsWith(nodePath.resolve(managed) + "/")
+ && fileExists(nodePath.join(root, "runtime-manifest.json"))
+ && fileExists(nodePath.join(root, "lib", "libCore.so"))) return root;
+ }
let bundled = bundledRuntimeRoot();
if (bundled !== "") return bundled;
return systemRuntimeRoot();
@@ -1315,6 +1436,10 @@ function hasConfiguredNativeTools() {
}
function wslRuntimeGateReady() {
+ if (electronRuntimeInstalling) {
+ wslRuntimeGateMessage = "Wait for the runtime installation to finish or cancel it.";
+ return Promise.resolve(false);
+ }
if (!isWslRuntimeHost()) return Promise.resolve(true);
let api = window.electronAPI && window.electronAPI.wslRuntime;
let unsubscribe = function () {};
@@ -2249,7 +2374,7 @@ function loadLocalPortableRunNaming() {
let home = nodeProcess.env.HOME || "";
if (home) candidates.push(nodePath.join(home, ".musrfit", "musrfit_startup.xml"));
candidates.push(nodePath.join(nodeProcess.cwd(), "musrfit_startup.xml"));
- let runtimeRoots = [bundledRuntimeRoot(), systemRuntimeRoot()];
+ let runtimeRoots = Array.from(new Set([activeRuntimeRoot(), bundledRuntimeRoot(), systemRuntimeRoot()]));
for (let i = 0; i < runtimeRoots.length; i++) {
if (runtimeRoots[i] !== "") {
// Final fallbacks: the startup XML shipped with the bundled runtime
diff --git a/package-lock.json b/package-lock.json
index a610d2e..e31dc7e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -9,7 +9,8 @@
"version": "1.0.0-rc.5",
"license": "GPL-3.0-or-later",
"dependencies": {
- "plotly.js-dist": "^3.5.1"
+ "plotly.js-dist": "^3.5.1",
+ "tar": "7.5.22"
},
"devDependencies": {
"electron": "^44.0.0"
@@ -46,6 +47,18 @@
"undici": "^7.24.4"
}
},
+ "node_modules/@isaacs/fs-minipass": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
+ "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",
+ "license": "ISC",
+ "dependencies": {
+ "minipass": "^7.0.4"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
"node_modules/@types/node": {
"version": "24.13.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",
@@ -56,6 +69,15 @@
"undici-types": "~7.18.0"
}
},
+ "node_modules/chownr": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",
+ "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -113,6 +135,27 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/minipass": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
+ "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ }
+ },
+ "node_modules/minizlib": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz",
+ "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==",
+ "license": "MIT",
+ "dependencies": {
+ "minipass": "^7.1.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -162,6 +205,22 @@
"node": ">= 8.0"
}
},
+ "node_modules/tar": {
+ "version": "7.5.22",
+ "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz",
+ "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==",
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "@isaacs/fs-minipass": "^4.0.0",
+ "chownr": "^3.0.0",
+ "minipass": "^7.1.2",
+ "minizlib": "^3.1.0",
+ "yallist": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/undici": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",
@@ -179,6 +238,15 @@
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
"dev": true,
"license": "MIT"
+ },
+ "node_modules/yallist": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
+ "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==",
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=18"
+ }
}
},
"dependencies": {
@@ -203,6 +271,14 @@
"undici": "^7.24.4"
}
},
+ "@isaacs/fs-minipass": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
+ "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",
+ "requires": {
+ "minipass": "^7.0.4"
+ }
+ },
"@types/node": {
"version": "24.13.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",
@@ -212,6 +288,11 @@
"undici-types": "~7.18.0"
}
},
+ "chownr": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",
+ "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g=="
+ },
"debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -244,6 +325,19 @@
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"dev": true
},
+ "minipass": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
+ "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="
+ },
+ "minizlib": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz",
+ "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==",
+ "requires": {
+ "minipass": "^7.1.2"
+ }
+ },
"ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -276,6 +370,18 @@
"debug": "^4.1.0"
}
},
+ "tar": {
+ "version": "7.5.22",
+ "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz",
+ "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==",
+ "requires": {
+ "@isaacs/fs-minipass": "^4.0.0",
+ "chownr": "^3.0.0",
+ "minipass": "^7.1.2",
+ "minizlib": "^3.1.0",
+ "yallist": "^5.0.0"
+ }
+ },
"undici": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",
@@ -288,6 +394,11 @@
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
"dev": true
+ },
+ "yallist": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
+ "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw=="
}
}
}
diff --git a/package.json b/package.json
index 4e6bf0b..a375386 100644
--- a/package.json
+++ b/package.json
@@ -16,7 +16,7 @@
"checksums:md5": "sh -c 'd=dist; [ -d \"$d\" ] || exit 0; for f in \"$d\"/*; do [ -f \"$f\" ] || continue; case \"$f\" in *.rpm|*.AppImage) base=$(basename \"$f\"); (cd \"$d\" && md5sum \"$base\" > \"$base.md5\");; esac; done'",
"checksums:sha256": "sh -c 'd=dist; [ -d \"$d\" ] || exit 0; for f in \"$d\"/*; do [ -f \"$f\" ] || continue; case \"$f\" in *.rpm|*.AppImage) base=$(basename \"$f\"); (cd \"$d\" && sha256sum \"$base\" > \"$base.sha256\");; esac; done'",
"checksums": "npm run checksums:md5 && npm run checksums:sha256",
- "test:electron": "node tests/log-highlighting.test.js && node tests/action-state.test.js && node tests/electron-missing-data.test.js && node tests/electron-run-data.test.js && node tests/electron-msr-title.test.js && node tests/electron-musrfit-threads.test.js && node tests/electron-t0-prompt-peak.test.js && node tests/window-layering.test.js && node tests/msr-generation.test.js && node tests/root-plot-clean.test.js && node tests/parameter-plot.test.js && node tests/help-window.test.js && node tests/release-packaging.test.js && node tests/runtime-validation.test.js && node tests/addrun.test.js && node tests/fit-statistic.test.js && node tests/series-fit-planner.test.js && node tests/series-fit-result.test.js && node tests/series-fit-inventory.test.js && node tests/series-fit-msr-preparation.test.js && node tests/series-artifact-contract.test.js && node tests/series-global-merge.test.js && node tests/series-fit-staging.test.js && node tests/series-fit-runner.test.js && node tests/series-runner-adapters.test.js && node tests/series-fit-routing.test.js && node tests/series-action-chips.test.js && node tests/singlehist-parity.test.js && node tests/url-parameters.test.js && node tests/run-naming.test.js && node tests/electron-portable-naming.test.js && node tests/shared-configuration.test.js && node tests/session-persistence.test.js && node tests/reference-fixtures.test.js && node tests/electron-bridge.test.js && node tests/electron-bundled-runtime.test.js && node tests/wsl-runtime.test.js"
+ "test:electron": "node tests/log-highlighting.test.js && node tests/action-state.test.js && node tests/electron-missing-data.test.js && node tests/electron-run-data.test.js && node tests/electron-msr-title.test.js && node tests/electron-musrfit-threads.test.js && node tests/electron-t0-prompt-peak.test.js && node tests/window-layering.test.js && node tests/msr-generation.test.js && node tests/root-plot-clean.test.js && node tests/parameter-plot.test.js && node tests/help-window.test.js && node tests/release-packaging.test.js && node tests/runtime-validation.test.js && node tests/local-runtime.test.js && node tests/addrun.test.js && node tests/fit-statistic.test.js && node tests/series-fit-planner.test.js && node tests/series-fit-result.test.js && node tests/series-fit-inventory.test.js && node tests/series-fit-msr-preparation.test.js && node tests/series-artifact-contract.test.js && node tests/series-global-merge.test.js && node tests/series-fit-staging.test.js && node tests/series-fit-runner.test.js && node tests/series-runner-adapters.test.js && node tests/series-fit-routing.test.js && node tests/series-action-chips.test.js && node tests/singlehist-parity.test.js && node tests/url-parameters.test.js && node tests/run-naming.test.js && node tests/electron-portable-naming.test.js && node tests/shared-configuration.test.js && node tests/session-persistence.test.js && node tests/reference-fixtures.test.js && node tests/electron-bridge.test.js && node tests/electron-bundled-runtime.test.js && node tests/wsl-runtime.test.js"
},
"repository": {
"type": "git",
@@ -36,7 +36,8 @@
"electron": "^44.0.0"
},
"dependencies": {
- "plotly.js-dist": "^3.5.1"
+ "plotly.js-dist": "^3.5.1",
+ "tar": "7.5.22"
},
"build": {
"appId": "ch.psi.lmu.musrflow",
@@ -55,6 +56,7 @@
"muSRFitelec.js",
"wsl-runtime.js",
"run-data-download.js",
+ "local-runtime.js",
"muSRFitRoot.js",
"muSRFitParameterPlot.js",
"muSRFitParameterPlotElec.js",
diff --git a/packaging/runtime/README.md b/packaging/runtime/README.md
index bbbf239..a4fb186 100644
--- a/packaging/runtime/README.md
+++ b/packaging/runtime/README.md
@@ -130,8 +130,8 @@ dist/runtime-downloads/musrflow-runtime-linux-x64-/
`rootDirectory`, byte `size`, and the full archive `sha256`. The filename is
relative to this descriptor, so the bundle can be published unchanged on a
trusted HTTPS release server without embedding build-machine paths or URLs.
-This descriptor prepares optional desktop downloads; no automatic download or
-installation UI is enabled yet.
+The Linux desktop can install this bundle locally through Preferences. Online
+runtime downloads are not enabled yet; no default release-server URL is assumed.
The archive contains one top-level `runtime/` directory, including the startup
XML, manifest, ROOT headers/fonts/configuration, and relative library links.
@@ -157,6 +157,34 @@ This bundles the scientific toolchain, not the operating system. A compatible
Linux installation and the normal desktop/display services are still needed.
Windows continues using its WSL2 rootfs; native macOS delivery is a separate step.
+### Offline desktop installation
+
+On Linux, open **File -> Preferences**. **Check tools** tests the currently saved
+tool selection using bounded `--version` calls. It does not require a manifest
+for an ordinary host installation, and does not change that installation.
+
+**Install runtime...** opens a native file chooser for `runtime-download.json`.
+Keep its matching archive alongside it. A confirmation shows the versions,
+archive size, source, and private installation directory. Install only bundles
+from a trusted source, since they contain executable programs.
+
+After **Install and use**, the main process verifies the entire archive hash,
+checks its entries and disk-space requirements, extracts into private staging,
+verifies the manifest/core files, and starts the required tools before keeping
+the new tree under Electron's per-user `runtimes/` directory. No Python, system
+tar, FUSE, administrator privileges, or network connection are required for this
+installation path. Progress and cancellation are available in Preferences, and
+Fit/Plot stay disabled until the operation finishes.
+
+The verified `bin/` directory becomes the saved binaries preference only after
+success. Merely having private runtimes on disk does not shadow a host setup;
+its ROOT environment is used only when that private tree is explicitly selected.
+System tools and user startup XML files are not rewritten. Failed or cancelled
+installs retain the previous selection. Existing valid trees can be reused;
+repair installs keep a damaged tree intact and use a fresh sibling. Cancelling
+other Preferences edits after a successful install does not undo the separately
+confirmed installation/selection.
+
## Notes / open items
- The manylinux_2_28 base (AlmaLinux 8, glibc 2.28) is used because ROOT 6.38
diff --git a/preload.js b/preload.js
index 88a0a99..4348828 100644
--- a/preload.js
+++ b/preload.js
@@ -192,6 +192,24 @@ readFile: function (p, encoding, callback) {
}
},
+ localRuntime: {
+ check: function (input) {
+ return ipcRenderer.invoke('checkLocalRuntime', input);
+ },
+ install: function (token) {
+ return ipcRenderer.invoke('installLocalRuntime', token);
+ },
+ cancel: function (token) {
+ return ipcRenderer.invoke('cancelLocalRuntime', token);
+ },
+ onProgress: function (listener) {
+ if (typeof listener !== 'function') return function () {};
+ const wrapped = function (event, state) { listener(state); };
+ ipcRenderer.on('localRuntimeProgress', wrapped);
+ return function () { ipcRenderer.removeListener('localRuntimeProgress', wrapped); };
+ }
+ },
+
// Windows bundled-runtime lifecycle. The main process imports the shipped
// WSL2 rootfs on first run; the renderer can subscribe for progress, read
// the current status, or force a retry after a failed import.
diff --git a/tests/electron-bundled-runtime.test.js b/tests/electron-bundled-runtime.test.js
index 39bb31c..5b3fa16 100644
--- a/tests/electron-bundled-runtime.test.js
+++ b/tests/electron-bundled-runtime.test.js
@@ -336,6 +336,72 @@ async function testRuntimeGateInertOffWindows() {
}
async function main() {
+ // A private installation is inert until its bin directory is explicitly
+ // selected. Its own ROOT environment must then outrank unrelated runtimes.
+ const managedDirectory = path.join(testRoot, 'private-runtimes');
+ const managedRoot = path.join(managedDirectory, 'test-release', 'runtime');
+ fs.mkdirSync(path.join(managedRoot, 'bin'), { recursive: true });
+ fs.mkdirSync(path.join(managedRoot, 'lib'));
+ fs.writeFileSync(path.join(managedRoot, 'bin', 'musrfit'), '');
+ fs.writeFileSync(path.join(managedRoot, 'lib', 'libCore.so'), '');
+ fs.writeFileSync(path.join(managedRoot, 'runtime-manifest.json'), '{}');
+ fs.writeFileSync(path.join(managedRoot, 'musrfit_startup.xml'), ' ');
+ const managed = buildSandbox(resourcesPath, { MUSRFLOW_MANAGED_RUNTIME_DIRECTORY: managedDirectory });
+ loadLibraries(managed);
+ assert.strictEqual(managed.activeRuntimeRoot(), runtimeRoot);
+ managed.window.localStorage.setItem('musrflow.binDir', path.join(managedRoot, 'bin'));
+ assert.strictEqual(managed.activeRuntimeRoot(), managedRoot);
+ assert.strictEqual(managed.resolveLocalCommand('musrfit'), path.join(managedRoot, 'bin', 'musrfit'));
+ assert.strictEqual(managed.buildToolEnvironment().ROOTSYS, managedRoot);
+ assert(managed.buildToolEnvironment().LD_LIBRARY_PATH.startsWith(path.join(managedRoot, 'lib')));
+ assert.strictEqual(managed.loadLocalPortableRunNaming(), path.join(managedRoot, 'musrfit_startup.xml'));
+ managed.window.localStorage.setItem('musrflow.binDir', '/an/explicit/host/bin');
+ assert.strictEqual(managed.activeRuntimeRoot(), runtimeRoot);
+
+ // Preferences keep their draft semantics. Installing/using a runtime is a
+ // separately confirmed action, so Cancel must preserve that chosen runtime.
+ const elements = {};
+ for (const id of ['localRuntimeStatus', 'runtimeCheck', 'runtimeInstall', 'runtimeCancel', 'FitMSR', 'PlotMSR', 'binDir']) {
+ elements[id] = { textContent: '', disabled: false, hidden: false, value: '' };
+ }
+ elements.preferencesDialog = { dataset: {}, close: function() {} };
+ managed.document.getElementById = function(id) {
+ return elements[id] || null;
+ };
+ managed.setFitStatus = function() {};
+ managed.reloadLocalPortableRunNaming = function() {};
+ managed.setMusrfitActionState = function() {
+ elements.FitMSR.disabled = false;
+ elements.PlotMSR.disabled = false;
+ };
+ let finishInstall;
+ let cancelled = 0;
+ managed.window.electronAPI = { localRuntime: {
+ install: function() {
+ return new Promise(function(resolve) { finishInstall = resolve; });
+ },
+ cancel: function() { cancelled++; },
+ onProgress: function() { return function() {}; }
+ } };
+ const firstInstall = managed.installElectronRuntime();
+ assert.strictEqual(elements.FitMSR.disabled, true);
+ assert.strictEqual(elements.PlotMSR.disabled, true);
+ assert.strictEqual(await managed.wslRuntimeGateReady(), false);
+ managed.cancelElectronRuntimeInstall();
+ finishInstall({ ok: false, cancelled: true });
+ await firstInstall;
+ assert.strictEqual(cancelled, 1);
+ assert.strictEqual(managed.getConfiguredBinDir(), '/an/explicit/host/bin');
+ assert(elements.localRuntimeStatus.textContent.includes('Previous tools were kept'));
+ const secondInstall = managed.installElectronRuntime();
+ finishInstall({ ok: true, root: managedRoot });
+ await secondInstall;
+ assert.strictEqual(managed.getConfiguredBinDir(), path.join(managedRoot, 'bin'));
+ assert.strictEqual(elements.preferencesDialog.dataset.originalBinDir, path.join(managedRoot, 'bin'));
+ managed.cancelElectronPreferences();
+ assert.strictEqual(elements.binDir.value, path.join(managedRoot, 'bin'));
+ assert.strictEqual(elements.FitMSR.disabled, false);
+ assert.strictEqual(elements.PlotMSR.disabled, false);
await testRuntimeGateOnWindows();
await testRuntimeGateFailureAndRetry();
await testRuntimeGateFallsBackToConfiguredTools();
diff --git a/tests/local-runtime.test.js b/tests/local-runtime.test.js
new file mode 100644
index 0000000..636aa13
--- /dev/null
+++ b/tests/local-runtime.test.js
@@ -0,0 +1,153 @@
+// Copyright (C) 2026 Zaher Salman
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+const assert = require('assert');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { createHash } = require('crypto');
+const tar = require('tar');
+const { LocalRuntime, TOOLS } = require('../local-runtime');
+
+if (process.platform !== 'linux' || !['x64', 'arm64'].includes(process.arch)) {
+ console.log('Linux runtime installation tests skipped on ' + process.platform);
+ process.exit(0);
+}
+
+const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'musrflow-install-test-'));
+const source = path.join(temporary, 'bundle');
+const prefix = path.join(source, 'runtime');
+const directory = path.join(temporary, 'personal runtimes');
+const installer = new LocalRuntime({ directory: directory });
+
+async function makeBundle(extraEntries = []) {
+ const archive = path.join(source, 'runtime.tar.gz');
+ await tar.c({ cwd: source, file: archive, gzip: true, portable: true }, ['runtime'].concat(extraEntries));
+ const bytes = fs.readFileSync(archive);
+ const descriptor = {
+ schemaVersion: 1, kind: 'musrflow-runtime-download',
+ runtime: JSON.parse(fs.readFileSync(path.join(prefix, 'runtime-manifest.json'), 'utf8')),
+ artifact: { filename: 'runtime.tar.gz', format: 'tar.gz', rootDirectory: 'runtime',
+ size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') }
+ };
+ fs.writeFileSync(path.join(source, 'runtime-download.json'), JSON.stringify(descriptor));
+ return installer.inspectBundle(path.join(source, 'runtime-download.json'));
+}
+
+async function run() {
+ fs.mkdirSync(path.join(prefix, 'bin'), { recursive: true });
+ fs.mkdirSync(path.join(prefix, 'lib'));
+ const header = Buffer.alloc(64);
+ Buffer.from([127, 69, 76, 70, 2, 1, 1]).copy(header);
+ header.writeUInt16LE(process.arch === 'x64' ? 62 : 183, 18);
+ fs.writeFileSync(path.join(prefix, 'lib/libCore.so'), header);
+ fs.writeFileSync(path.join(prefix, 'lib/libPMusr.so'), header);
+ fs.symlinkSync('libCore.so', path.join(prefix, 'lib/libAlias.so'));
+ const manifest = { schemaVersion: 1, platform: 'linux', arch: process.arch, runtimeId: 'test-runtime',
+ root: { version: '6.38.00' }, musrfit: { version: '1.12.1', revision: '708f777b' }, files: {} };
+ for (const name of TOOLS.concat('root-config')) {
+ const output = name === 'root-config' ? '6.38.00' : name
+ + ' version: 1.12.1, git-rev: test - 708f777b (Release), ROOT version: 6.38.00';
+ fs.writeFileSync(path.join(prefix, 'bin', name), '#!/bin/sh\necho "' + output + '"\n', { mode: 0o755 });
+ manifest.files['bin/' + name] = createHash('sha256').update(fs.readFileSync(path.join(prefix, 'bin', name))).digest('hex');
+ }
+ for (const name of ['lib/libCore.so', 'lib/libPMusr.so']) {
+ manifest.files[name] = createHash('sha256').update(header).digest('hex');
+ }
+ fs.writeFileSync(path.join(prefix, 'runtime-manifest.json'), JSON.stringify(manifest));
+ fs.writeFileSync(path.join(prefix, 'musrfit_startup.xml'), 'unchanged ');
+ const commands = {};
+ for (const name of TOOLS) commands[name] = path.join(prefix, 'bin', name);
+ const checked = await installer.checkTools({ commands: commands });
+ assert.strictEqual(checked.ok, true);
+ const viewPath = path.join(prefix, 'bin/musrview');
+ const originalView = fs.readFileSync(viewPath);
+ fs.writeFileSync(viewPath, '#!/bin/sh\nexec sleep 30\n');
+ const bounded = new LocalRuntime({ directory: directory, timeout: 100 });
+ const timedOut = await bounded.checkTools({ commands: commands });
+ assert.strictEqual(timedOut.ok, false);
+ assert(timedOut.tools.find(function(tool) { return tool.name === 'musrview'; }).error.includes('timed out'));
+ fs.writeFileSync(viewPath, originalView);
+ const missing = await installer.checkTools({ commands: Object.assign({}, commands, { musrview: '/absent/musrview' }) });
+ assert.strictEqual(missing.ok, false);
+ assert(missing.tools.find(function(tool) { return tool.name === 'musrview'; }).error);
+ // Host checks do not require a muSRFlow manifest or a root-config executable.
+ fs.renameSync(path.join(prefix, 'runtime-manifest.json'), path.join(prefix, 'saved-manifest.json'));
+ assert.strictEqual((await installer.checkTools({ commands: commands })).ok, true);
+ fs.renameSync(path.join(prefix, 'saved-manifest.json'), path.join(prefix, 'runtime-manifest.json'));
+
+ let plan = await makeBundle();
+ const descriptorPath = path.join(source, 'runtime-download.json');
+ const original = fs.readFileSync(descriptorPath, 'utf8');
+ for (const replacement of [
+ Object.assign({}, plan.descriptor, { runtime: Object.assign({}, manifest, { platform: 'darwin' }) }),
+ Object.assign({}, plan.descriptor, { runtime: Object.assign({}, manifest, { arch: process.arch === 'x64' ? 'arm64' : 'x64' }) }),
+ Object.assign({}, plan.descriptor, { artifact: Object.assign({}, plan.descriptor.artifact, { filename: '../runtime.tar.gz' }) }),
+ Object.assign({}, plan.descriptor, { artifact: Object.assign({}, plan.descriptor.artifact, { size: 1 }) })
+ ]) {
+ fs.writeFileSync(descriptorPath, JSON.stringify(replacement));
+ await assert.rejects(installer.inspectBundle(descriptorPath));
+ }
+ fs.writeFileSync(descriptorPath, original);
+ const archiveBytes = fs.readFileSync(plan.archive);
+ const altered = Buffer.from(archiveBytes);
+ altered[altered.length - 1] ^= 1;
+ fs.writeFileSync(plan.archive, altered);
+ await assert.rejects(installer.install(plan, new AbortController().signal), /SHA-256/);
+ assert.deepStrictEqual(fs.readdirSync(directory), []);
+ fs.writeFileSync(plan.archive, archiveBytes);
+
+ const statfs = fs.promises.statfs;
+ fs.promises.statfs = async function() { return { bavail: 0, bsize: 4096 }; };
+ try {
+ await assert.rejects(installer.install(plan, new AbortController().signal), /free disk space/);
+ assert.deepStrictEqual(fs.readdirSync(directory), []);
+ } finally {
+ fs.promises.statfs = statfs;
+ }
+
+ const phases = [];
+ const installed = await installer.install(plan, new AbortController().signal, function(state) {
+ phases.push(state.phase);
+ });
+ assert.strictEqual(installed.ok, true);
+ assert(installed.root.startsWith(directory + path.sep));
+ assert.strictEqual(fs.readlinkSync(path.join(installed.root, 'lib/libAlias.so')), 'libCore.so');
+ assert.strictEqual(fs.statSync(path.join(installed.root, 'bin/musrfit')).mode & 0o111, 0o111);
+ assert.strictEqual(fs.readFileSync(path.join(prefix, 'musrfit_startup.xml'), 'utf8'), 'unchanged ');
+ assert(phases.includes('Extracting runtime'));
+ const reused = await installer.install(plan, new AbortController().signal);
+ assert.strictEqual(reused.reused, true);
+ assert.strictEqual(reused.root, installed.root);
+
+ for (const phase of ['Verifying runtime archive', 'Extracting runtime']) {
+ const controller = new AbortController();
+ await assert.rejects(installer.install(plan, controller.signal, function(state) {
+ if (state.phase === phase) controller.abort();
+ }));
+ assert.strictEqual(fs.readdirSync(directory).some(function(name) { return name.startsWith('.install-'); }), false);
+ await installer.verifyInstalled(installed.root, manifest);
+ }
+ fs.appendFileSync(path.join(installed.root, 'bin/musrfit'), '# local damage\n');
+ const repaired = await installer.install(plan, new AbortController().signal);
+ assert.notStrictEqual(repaired.root, installed.root);
+ assert(fs.readFileSync(path.join(installed.root, 'bin/musrfit'), 'utf8').includes('local damage'));
+ await installer.verifyInstalled(repaired.root, manifest);
+
+ fs.symlinkSync('../../outside-file', path.join(prefix, 'lib', 'escape'));
+ plan = await makeBundle();
+ await assert.rejects(installer.install(plan, new AbortController().signal), /Unsafe runtime library link/);
+ assert.strictEqual(fs.existsSync(path.join(directory, 'outside-file')), false);
+ fs.unlinkSync(path.join(prefix, 'lib', 'escape'));
+ plan = await makeBundle(['runtime/bin/musrfit']);
+ await assert.rejects(installer.install(plan, new AbortController().signal), /duplicate/);
+ assert.strictEqual(fs.readdirSync(directory).some(function(name) { return name.startsWith('.install-'); }), false);
+ console.log('Local runtime detection, installation, cancellation, and repair tests passed');
+}
+
+run().catch(function(error) {
+ console.error(error);
+ process.exitCode = 1;
+}).finally(function() {
+ fs.rmSync(temporary, { recursive: true, force: true });
+});
diff --git a/tests/release-packaging.test.js b/tests/release-packaging.test.js
index ac3407a..56e63c1 100644
--- a/tests/release-packaging.test.js
+++ b/tests/release-packaging.test.js
@@ -29,6 +29,8 @@ assert(main.includes('Author: Zaher Salman'), 'About dialog should report the au
assert(main.includes('Copyright (C) 2026 Zaher Salman'), 'About dialog should report copyright');
assert.strictEqual(pkg.build.linux.icon, 'assets/musrflow-icon.png');
assert(pkg.build.files.includes('assets/**/*'));
+assert(pkg.build.files.includes('local-runtime.js'));
+assert.strictEqual(pkg.dependencies.tar, '7.5.22');
assert(fs.existsSync(path.join(root, 'assets', 'musrflow-icon.png')));
assert(fs.existsSync(path.join(root, 'assets', 'musrflow-favicon.png')));