Restore shared configuration links in the Electron app

A shared link (#c=... round-trips with the web build) was unreachable from
the desktop app: the decode/restore code only ran in web mode and there
was no URL intake in the main process. The Electron main process now
accepts a configuration URL from the command line, a second invocation of
a running app, or a macOS open-url event and delivers it over the existing
openSharedConfiguration channel; the renderer restores it through the same
decode/confirm/restore path as the paste dialog, which stays unchanged.

Links generated by earlier builds can also carry parameterPlot:null when
no parameter window was open. Validation now treats a null stanza as no
stanza (web and desktop alike), and new links omit the field instead of
writing a literal null.
This commit is contained in:
salman committed 2026-09-20 19:35:16 +02:00
1 parent 18919d9e0a
commit cd0b1587bd
4 files changed
+215 -24

No files matched your search

+71 -1
View File
@@ -40,6 +40,12 @@ if (forwardedX11 && process.env.DBUS_SESSION_BUS_ADDRESS
const parameterPlotWindows = new Set();
let quickStartWindow = null;
// The main window is tracked module-wide so deep links (a shared-configuration
// URL in the command line, a second invocation, or a macOS open-url event) can
// reach the already-created renderer.
let mainWindow = null;
let pendingSharedConfigurationURL = "";
// Remember the last folder used by the Open/Save MSR dialogs, so a repeated
// open or save starts where the previous one finished instead of the process
// working directory. The remember is a tiny JSON file under userData; if it is
@@ -154,6 +160,23 @@ function showQuickStartWindow(sectionId = "helpRuns") {
}
// Create the Electron shell; fitting logic remains in the shared renderer.
// A configuration link is an http(s)://…/muSRFlow/#c=… (or #cfg=…) URL. Only
// such URLs are accepted from the command line, a second instance, or
// open-url; the HTTP target is never fetched, mirroring the web restore path.
function findSharedConfigurationURL(args) {
if (!Array.isArray(args)) return "";
for (const argument of args) {
const value = String(argument || "");
if (/^https?:\/\//i.test(value) && /#(?:c|cfg)=/.test(value)) {
return value;
}
if (/^#(?:c|cfg)=/.test(value)) {
return value;
}
}
return "";
}
function createWindow () {
const workArea = screen.getPrimaryDisplay().workAreaSize;
let defaultWidth = Math.floor(Math.min(980, workArea.width * 0.5));
@@ -183,6 +206,10 @@ function createWindow () {
sandbox: false
}
})
mainWindow = win;
win.on("closed", function () {
if (mainWindow === win) mainWindow = null;
});
loadRememberedMSRDirectory();
@@ -312,12 +339,55 @@ function createWindow () {
Menu.setApplicationMenu(menu)
win.loadFile('index.html');
// Deep links captured before the window existed (macOS open-url during
// startup) and a startup URL from the command line are sent once the page
// is ready. The renderer decodes and restores them through the same path
// as the Restore Configuration Link menu, never by navigating the HTTP URL.
const startupURL = findSharedConfigurationURL(process.argv);
const deepLink = startupURL || pendingSharedConfigurationURL;
pendingSharedConfigurationURL = "";
if (deepLink) {
win.webContents.once('did-finish-load', function () {
win.webContents.send('openSharedConfiguration', deepLink);
});
}
}
if (relaunchingForForwardedX11) {
app.exit(0);
} else {
app.whenReady().then(createWindow);
// One app instance owns the shared-configuration deep links. A second
// invocation that carries a configuration URL forwards it to the running
// window instead of starting a second copy.
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
app.on('second-instance', function (event, commandLine) {
const url = findSharedConfigurationURL(commandLine);
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
if (url) mainWindow.webContents.send('openSharedConfiguration', url);
}
});
// macOS delivers URLs the app is registered to open through open-url, which
// may fire before the window exists.
app.on('open-url', function (event, url) {
event.preventDefault();
if (!url || !/^https?:\/\//i.test(url) || !/#(?:c|cfg)=/.test(url)) {
return;
}
if (mainWindow) {
mainWindow.webContents.send('openSharedConfiguration', url);
} else {
pendingSharedConfigurationURL = url;
}
});
app.whenReady().then(createWindow);
}
}
app.on('window-all-closed', () => {
+41 -17
View File
@@ -444,16 +444,18 @@ function openElectronSharedConfiguration() {
}, 0);
}
async function restoreElectronSharedConfiguration() {
let dialog = document.getElementById("sharedConfigurationDialog");
let input = document.getElementById("sharedConfigurationURL");
let errorText = document.getElementById("sharedConfigurationError");
let decoded = await decodeElectronSharedConfiguration(input ? input.value : "");
async function restoreSharedConfigurationFromSource(sourceText, errorElement) {
let decoded = await decodeElectronSharedConfiguration(sourceText || "");
if (decoded.error) {
if (errorText) {
errorText.textContent = decoded.error;
errorText.hidden = false;
if (errorElement) {
errorElement.textContent = decoded.error;
errorElement.hidden = false;
}
if (typeof setFitStatus === "function") {
setFitStatus("Could not restore the shared configuration.", {
level: "error",
details: decoded.error
});
}
return false;
}
@@ -480,10 +482,6 @@ async function restoreElectronSharedConfiguration() {
// markMSREditorStaleAfterRestore in muSRFitlib.js). The next
// Generate/Fit/Plot creates a fresh MSR.
if (dialog) {
if (typeof dialog.close === "function") dialog.close();
else dialog.removeAttribute("open");
}
if (typeof openTab === "function") openTab(null, "Runs");
if (typeof setFitStatus === "function") {
setFitStatus("Shared configuration restored.", {
@@ -495,9 +493,9 @@ async function restoreElectronSharedConfiguration() {
} catch (error) {
let message = "Could not restore shared configuration: "
+ (error && error.message ? error.message : String(error));
if (errorText) {
errorText.textContent = message;
errorText.hidden = false;
if (errorElement) {
errorElement.textContent = message;
errorElement.hidden = false;
}
if (typeof setFitStatus === "function") {
setFitStatus("Could not restore shared configuration.", {
@@ -509,6 +507,27 @@ async function restoreElectronSharedConfiguration() {
}
}
async function restoreElectronSharedConfiguration() {
let dialog = document.getElementById("sharedConfigurationDialog");
let input = document.getElementById("sharedConfigurationURL");
let errorText = document.getElementById("sharedConfigurationError");
let restored = await restoreSharedConfigurationFromSource(
input ? input.value : "", errorText || null
);
if (restored && dialog) {
if (typeof dialog.close === "function") dialog.close();
else dialog.removeAttribute("open");
}
return restored;
}
// A deep link arriving through the main process follows exactly the same
// decode/restore path as the paste dialog, minus the dialog itself.
async function restoreElectronSharedURL(url) {
if (!url || typeof url !== "string") return false;
return restoreSharedConfigurationFromSource(url, null);
}
function selectWorkFolder() {
let input = document.getElementById("workPath");
let currentPath = input ? input.value : ".";
@@ -1617,7 +1636,12 @@ function firstLoad() {
openElectronPreferences();
});
electronIpcRenderer.on('openSharedConfiguration', function() {
electronIpcRenderer.on('openSharedConfiguration', function(sharedURL) {
// A deep link (http(s)://.../muSRFlow/#c=... or a bare #c= fragment)
// restores immediately. With no URL the Share menu paste dialog opens.
if (sharedURL && typeof sharedURL === "string") {
return restoreElectronSharedURL(sharedURL);
}
openElectronSharedConfiguration();
});
+8 -4
View File
@@ -140,7 +140,10 @@ function buildSharedConfiguration() {
// cannot reconstruct that ordered detector mapping on another machine.
functionMaps: All.msrFunctionMaps && typeof All.msrFunctionMaps === "object"
? JSON.parse(JSON.stringify(All.msrFunctionMaps)) : {},
parameterPlot: currentParameterPlotSnapshot()
// JSON.stringify drops the undefined value, so a link without an open
// parameter plot simply omits the stanza instead of carrying parameterPlot
// with a null value (which earlier share links emitted).
parameterPlot: currentParameterPlotSnapshot() || undefined
};
}
@@ -184,10 +187,11 @@ function validateSharedConfiguration(config) {
// the sender's plot window. Structural checks reject crafted payloads; the
// plot-side validator (muSRFitParameterPlot.js) performs the full check when
// it is loaded, and the restore step never trusts an unvalidated stanza.
// A null stanza (written by earlier share links when no plot was open) means
// the same as an absent stanza and is accepted.
let parameterPlot = config.parameterPlot;
if (parameterPlot !== undefined
&& (typeof parameterPlot !== "object" || parameterPlot === null
|| Array.isArray(parameterPlot))) {
if (parameterPlot !== undefined && parameterPlot !== null
&& (typeof parameterPlot !== "object" || Array.isArray(parameterPlot))) {
throw new Error("invalid parameter-plot configuration");
}
if (parameterPlot && typeof validateParameterPlotState === "function"
+95 -2
View File
@@ -147,6 +147,28 @@ async function testElectronCodecReadsWebCompatibleLinks() {
incomplete.prefix + incomplete.payload
);
assert.match(incompleteResult.error, /missing the detector definition for map1/);
// Share links written by earlier builds carry parameterPlot:null when no
// parameter plot was open. The decode must treat that as "no plot" instead
// of rejecting the whole link.
const legacyNullPlot = {
v: 1,
controls: { runNumbers: "514" },
component: "",
parameterPlot: null
};
const nullPlot = await lib.encodeElectronSharedConfiguration(legacyNullPlot);
const nullPlotResult = await lib.decodeElectronSharedConfiguration(
nullPlot.prefix + nullPlot.payload
);
assert.strictEqual(nullPlotResult.error, "");
assert.strictEqual(nullPlotResult.consumed, true);
assert.strictEqual(nullPlotResult.config.parameterPlot, null);
// New links omit the stanza entirely when there is no plot.
const noPlot = await lib.encodeElectronSharedConfiguration({ v: 1, controls: {} });
assert.strictEqual(noPlot.prefix, "#c=");
assert.ok(!noPlot.payload.includes("parameterPlot"));
}
function testSharedConfigurationIncludesDetectorMaps() {
@@ -185,6 +207,16 @@ function testElectronMenuAndRendererAreConnected() {
assert.match(html, /id="sharedConfigurationDialog"/);
assert.match(html, /restoreElectronSharedConfiguration\(\)/);
// The Electron main process accepts a configuration URL from the command
// line, a second invocation, or a macOS open-url event, and delivers it to
// the renderer through the same restore channel as the menu item. The app
// never fetches the web deployment for these links.
assert.match(main, /requestSingleInstanceLock\(\)/);
assert.match(main, /'second-instance'/);
assert.match(main, /'open-url'/);
assert.match(main, /findSharedConfigurationURL\(/);
assert.match(main, /send\('openSharedConfiguration', deepLink\)/);
env.sandbox.firstLoad();
assert.strictEqual(typeof env.ipcListeners.openSharedConfiguration, "function");
}
@@ -388,6 +420,63 @@ async function testUserCanCancelOverwritingEditorOwnership() {
assert.strictEqual(lib.getMSRDocumentState("current").dirty, true);
}
async function testElectronSharedURLRestoresThroughListener() {
// A configuration link delivered by the main process (command line, a
// second instance, or macOS open-url) must restore through the same
// decode/restore path as the menu dialog, without opening the dialog.
const env = loadSharedConfigurationHelpers();
const lib = env.sandbox;
const config = { v: 1, controls: { runNumbers: "514" } };
const encoded = await lib.encodeElectronSharedConfiguration(config);
const link = "http://musruser.psi.ch/muSRFlow/" + encoded.prefix + encoded.payload;
const dialog = {
open: false,
showModal: function() { this.open = true; },
close: function() { this.open = false; }
};
const runsRoot = {
contains: function(element) { return element === env.elements.runNumbers; }
};
env.elements.sharedConfigurationDialog = dialog;
env.elements.Runs = runsRoot;
env.elements.runNumbers = { value: "1" };
lib.adjustComps = function() {};
lib.updateTheoryBlock = function() {};
lib.clearStoredT0BgValues = function() {};
lib.cfgParams = async function() {};
lib.prepCFG = function() {};
lib.getCurrentEditorText = function() { return "old MSR text"; };
lib.updateMSREditorSourceTabs = function() {};
lib.openTab = function(event, name) { assert.strictEqual(name, "Runs"); };
let status = null;
lib.setFitStatus = function(message, options) { status = { message, options }; };
lib.window.MSREditor.currentPath = "/tmp/old.msr";
lib.firstLoad();
const result = await env.ipcListeners.openSharedConfiguration(link);
assert.strictEqual(result, true);
assert.strictEqual(env.elements.runNumbers.value, "514");
assert.strictEqual(dialog.open, false);
assert.strictEqual(status.message, "Shared configuration restored.");
// The same listener still opens the paste dialog when no URL is provided.
const menuEnv = loadSharedConfigurationHelpers();
const menuLib = menuEnv.sandbox;
const menuDialog = {
open: false,
showModal: function() { this.open = true; },
close: function() { this.open = false; }
};
menuEnv.elements.sharedConfigurationDialog = menuDialog;
menuEnv.elements.sharedConfigurationURL = {
value: "", focus: function() {}, select: function() {}
};
menuLib.firstLoad();
menuEnv.ipcListeners.openSharedConfiguration();
assert.strictEqual(menuDialog.open, true);
}
// A sandbox that simulates the hardened Electron renderer: require throws for
// Node builtins, only window.electronAPI is available. extraAPI merges into
// window.electronAPI so each test can expose the bridge surface it targets.
@@ -551,10 +640,11 @@ async function testSharedConfigurationEmbedsParameterPlotState() {
const lib = env.sandbox;
const storage = lib.parameterPlotStateStorage();
// No remembered state for the current source => the stanza is absent.
// No remembered state for the current source => the stanza is absent, so
// JSON.stringify drops it from the link instead of carrying a null value.
lib.window.MusrfitJob = { parameterDataPath: "/work/514_par.dat" };
let shared = lib.buildSharedConfiguration();
assert.strictEqual(shared.parameterPlot, null);
assert.strictEqual(shared.parameterPlot, undefined);
// A remembered snapshot for the current source rides along in the link.
const snapshot = {
@@ -643,6 +733,8 @@ function testSharedConfigurationValidatesParameterPlotStanza() {
assert.strictEqual(lib.validateSharedConfiguration(
{ v: 1, controls: {}, parameterPlot: valid }).parameterPlot.mainSourceKey,
"path:/work/514_par.dat");
assert.strictEqual(lib.validateSharedConfiguration(
{ v: 1, controls: {}, parameterPlot: null }).v, 1);
assert.throws(function() {
lib.validateSharedConfiguration({ v: 1, controls: {}, parameterPlot: [] });
@@ -940,6 +1032,7 @@ async function main() {
await testSharedRestoreCannotChangeLocalPreferences();
await testElectronDialogRestoresStateAndMarksEditorStale();
await testUserCanCancelOverwritingEditorOwnership();
await testElectronSharedURLRestoresThroughListener();
await testElectronBridgeDecodeHardenedRenderer();
await testElectronBridgeCopyUsesBridgeClipboard();
await testSharedConfigurationEmbedsParameterPlotState();