🐛 fix: config race conditions, quit safety, update data loss

- Config write serialization via _writeQueue prevents concurrent
  read-modify-write races between settings/queue/history saves
- Cancel active uploads on app quit (prevents zombie processes)
- Persist queue before update install (prevents queue loss)
- Sync IPC save in beforeunload (guarantees save before close)
- Fix double configStore.load() call
- Guard against status regression in handleProgress (done→uploading)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Administrator 2026-03-21 10:20:07 +01:00
parent 9ea9212637
commit 7ba2c63d51
4 changed files with 53 additions and 22 deletions

View File

@ -94,6 +94,7 @@ class ConfigStore {
? app.getPath('userData') ? app.getPath('userData')
: path.join(__dirname, '..'); : path.join(__dirname, '..');
this.filePath = path.join(dir, 'electron-config.json'); this.filePath = path.join(dir, 'electron-config.json');
this._writeQueue = Promise.resolve(); // Serializes all writes to prevent race conditions
// Migrate config from old location if current doesn't exist // Migrate config from old location if current doesn't exist
if (!fs.existsSync(this.filePath) && app && app.isPackaged) { if (!fs.existsSync(this.filePath) && app && app.isPackaged) {
@ -208,12 +209,19 @@ class ConfigStore {
} }
} }
_enqueueWrite(fn) {
this._writeQueue = this._writeQueue.then(fn, fn);
return this._writeQueue;
}
save(config) { save(config) {
return this._enqueueWrite(() => {
const current = this.load(); const current = this.load();
if (config.hosters) current.hosters = config.hosters; if (config.hosters) current.hosters = config.hosters;
if (config.hosterSettings) current.hosterSettings = config.hosterSettings; if (config.hosterSettings) current.hosterSettings = config.hosterSettings;
if (config.globalSettings) current.globalSettings = config.globalSettings; if (config.globalSettings) current.globalSettings = config.globalSettings;
return this._atomicWrite(JSON.stringify(current, null, 2)); return this._atomicWrite(JSON.stringify(current, null, 2));
});
} }
loadHistory() { loadHistory() {
@ -242,18 +250,22 @@ class ConfigStore {
} }
appendHistory(entry) { appendHistory(entry) {
return this._enqueueWrite(() => {
const config = this.load(); const config = this.load();
config.history.push(entry); config.history.push(entry);
if (config.history.length > MAX_HISTORY) { if (config.history.length > MAX_HISTORY) {
config.history = config.history.slice(-MAX_HISTORY); config.history = config.history.slice(-MAX_HISTORY);
} }
return this._atomicWrite(JSON.stringify(config, null, 2)); return this._atomicWrite(JSON.stringify(config, null, 2));
});
} }
clearHistory() { clearHistory() {
return this._enqueueWrite(() => {
const config = this.load(); const config = this.load();
config.history = []; config.history = [];
return this._atomicWrite(JSON.stringify(config, null, 2)); return this._atomicWrite(JSON.stringify(config, null, 2));
});
} }
} }

14
main.js
View File

@ -502,7 +502,8 @@ app.whenReady().then(() => {
// Auto-start remote server if enabled // Auto-start remote server if enabled
try { try {
const remoteConfig = configStore.load().globalSettings && configStore.load().globalSettings.remote; const _remCfg = configStore.load();
const remoteConfig = _remCfg.globalSettings && _remCfg.globalSettings.remote;
if (remoteConfig && remoteConfig.enabled) { if (remoteConfig && remoteConfig.enabled) {
startRemoteServer().catch(err => { startRemoteServer().catch(err => {
debugLog(`remote-server auto-start failed: ${err.message}`); debugLog(`remote-server auto-start failed: ${err.message}`);
@ -540,6 +541,7 @@ app.on('window-all-closed', () => {
}); });
app.on('before-quit', () => { app.on('before-quit', () => {
if (uploadManager) try { uploadManager.cancel(); } catch {}
try { folderMonitor.stop(); } catch {} try { folderMonitor.stop(); } catch {}
try { try {
if (remoteServer) { remoteServer.stop(); remoteServer = null; } if (remoteServer) { remoteServer.stop(); remoteServer = null; }
@ -874,6 +876,16 @@ ipcMain.handle('save-global-settings', async (_event, globalSettings) => {
return true; return true;
}); });
// Synchronous save for beforeunload — blocks renderer until write completes
ipcMain.on('save-global-settings-sync', (event, globalSettings) => {
try {
const current = configStore.load();
current.globalSettings = globalSettings;
fs.writeFileSync(configStore.filePath, JSON.stringify(current, null, 2));
} catch {}
event.returnValue = true;
});
// --- Folder Monitor --- // --- Folder Monitor ---
function startFolderMonitor(settings) { function startFolderMonitor(settings) {
try { try {

View File

@ -14,6 +14,7 @@ contextBridge.exposeInMainWorld('api', {
// Global settings // Global settings
getGlobalSettings: () => ipcRenderer.invoke('get-global-settings'), getGlobalSettings: () => ipcRenderer.invoke('get-global-settings'),
saveGlobalSettings: (settings) => ipcRenderer.invoke('save-global-settings', settings), saveGlobalSettings: (settings) => ipcRenderer.invoke('save-global-settings', settings),
saveGlobalSettingsSync: (settings) => ipcRenderer.sendSync('save-global-settings-sync', settings),
// Always on top // Always on top
setAlwaysOnTop: (value) => ipcRenderer.invoke('set-always-on-top', value), setAlwaysOnTop: (value) => ipcRenderer.invoke('set-always-on-top', value),

View File

@ -1487,6 +1487,9 @@ function handleProgress(data) {
indexJob(job); indexJob(job);
} }
// Don't regress from terminal states (stale callbacks can arrive after completion)
if (job.status === 'done' || job.status === 'skipped') return;
// Update job state // Update job state
job.status = data.status; job.status = data.status;
job.bytesUploaded = data.bytesUploaded || 0; job.bytesUploaded = data.bytesUploaded || 0;
@ -3041,14 +3044,16 @@ function sortHistoryRows(rows) {
}); });
} }
// Flush pending queue state on window close // Flush pending queue state on window close (sync IPC — blocks until save completes)
window.addEventListener('beforeunload', () => { window.addEventListener('beforeunload', () => {
if (queuePersistTimer) {
clearTimeout(queuePersistTimer); clearTimeout(queuePersistTimer);
queuePersistTimer = null; queuePersistTimer = null;
// Synchronous-ish: fire and forget since window is closing const globalSettings = {
persistQueueStateNow().catch(() => {}); ...(config.globalSettings || {}),
} pendingQueue: buildPersistedQueueState()
};
config.globalSettings = globalSettings;
window.api.saveGlobalSettingsSync(globalSettings);
}); });
// --- Setup Listeners --- // --- Setup Listeners ---
@ -3252,6 +3257,7 @@ function showUpdateBanner(info) {
document.getElementById('installUpdateBtn').onclick = async () => { document.getElementById('installUpdateBtn').onclick = async () => {
msg.textContent = 'Update wird heruntergeladen...'; msg.textContent = 'Update wird heruntergeladen...';
document.getElementById('installUpdateBtn').disabled = true; document.getElementById('installUpdateBtn').disabled = true;
await persistQueueStateNow().catch(() => {}); // Save queue before update restart
await window.api.installUpdate(); await window.api.installUpdate();
}; };
document.getElementById('dismissUpdateBtn').onclick = () => { banner.style.display = 'none'; }; document.getElementById('dismissUpdateBtn').onclick = () => { banner.style.display = 'none'; };