diff --git a/README.md b/README.md index 2e1f707..0f58b4a 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ The automatic queue limit counts preview, queued, server-selection, uploading, a New matching files are collected after they have remained stable for the configured delay. The optional one-time existing-file scan, live watcher events, interval scans, and reconnect scans use the same filtering and admission path. Reconciliation checks the complete folder at the selected interval. A missing folder keeps its configuration; after it becomes reachable again, exactly one reconnect scan runs before normal interval scans continue. If no hosts are preselected, the application asks for destinations instead of starting a batch automatically. -**Finish and pause** saves the pause before allowing active uploads to finish. While paused, no watcher, reconciliation, queued upload start, automatic start, or active-batch injection can proceed. Manual files can still be imported as preview jobs. The pause survives an application restart. **Resume** explicitly removes it, restarts monitoring, and performs one reconciliation without automatically starting existing preview jobs. +**Pause automation** immediately aborts active uploads and blocks new work, including while the pause is still being saved. Paused transfers restart from the beginning on **Resume**; completed uploads are kept. While paused, no watcher, reconciliation, queued upload start, automatic start, or active-batch injection can proceed. Manual files can still be imported as preview jobs. The pause survives an application restart. Resume restarts paused jobs and reconciles the monitored folder without automatically starting unrelated preview jobs. The official updater separately lets active uploads finish before installing. For automation decisions, **already processed** describes current evidence only: exact paths in the current queue, successful history results, and successful entries in the application's upload log. It is not a permanent file registry. A basename-only match is accepted only when it identifies one candidate unambiguously; same-named files from different folders remain eligible unless exact current evidence identifies them. @@ -332,6 +332,10 @@ The update first saves its resume intent, stops new admission and waits for curr Use `mhu_capabilities` to inspect effective permissions and available actions before controlling an installation. `mhu_automation_pause` and `mhu_automation_resume` explicitly control the shared upload/automation pause; their queue equivalents remain supported. Resuming does not enable a disabled monitor. `mhu_automation_start` enables configured monitoring and returns `AUTOMATION_PAUSED` if the shared pause must first be resumed. Failed lifecycle operations return an MCP error, not a successful response containing an error string. A read-only status check never changes the pause state. +Pausing aborts active transfers immediately and prevents new uploads before waiting for settings to reach disk. Resuming waits for these aborted transfers to settle, then restarts the paused files from the beginning. Completed uploads and explicitly cancelled files are not restarted. The same behavior applies to the interface and MCP. + +Upload file reads share a bounded pool of four concurrent reads. `mhu_io_limits_get` reports its active, waiting and maximum read counts; `mhu_io_limits_update` accepts `readConcurrency` from 1 to 32. This changes only the current process, does not abort uploads and returns to the default after restart. It is separate from upload concurrency and does not limit other applications' disk activity. + Structured settings updates also support upload parallelism scaling, partial filename-scrambling settings, history retention and hoster size-limit memory. Enabling automatic source deletion, a completion power action or limited history retention requires exact local confirmation. `mhu_shutdown_cancel` cancels the pending completion action immediately, then saves `nothing` as the policy. This does not authorize immediate system shutdown or unrestricted operating-system control. The upload scheduler no longer reserves a global transfer slot while waiting for a hoster's configured start interval. Per-hoster spacing remains enforced at admission. Upload file metadata and chunk reads use asynchronous I/O. These changes do not reduce configured parallelism or change successful-upload confirmation requirements. Synthetic benchmark results demonstrate the targeted scheduling case only; server-specific throughput and freeze improvements require measurements after installing the new version. diff --git a/lib/config-store.js b/lib/config-store.js index a317527..e3cdecf 100644 --- a/lib/config-store.js +++ b/lib/config-store.js @@ -535,12 +535,22 @@ class ConfigStore { _enqueueWrite(fn, options = {}) { if (this._writesQuiesced && !options.allowDuringQuiesce) return Promise.reject(this._quiescedWriteError()); + const previous = this._lastQueuedWrite; + if (options.coalesceKey && previous?.key === options.coalesceKey && !previous.started) { + previous.fn = fn; + return previous.operation; + } + const queued = { key: options.coalesceKey, fn, started: false, operation: null }; + this._lastQueuedWrite = queued; this._wqDepth++; const execute = async () => { + queued.started = true; + if (this._lastQueuedWrite === queued) this._lastQueuedWrite = null; if (!options.skipRefresh) await this._refreshConfigFromDisk(); - return fn(); + return queued.fn(); }; const operation = this._writeQueue.then(execute, execute); + queued.operation = operation; this._pendingWriteOperations.add(operation); this._writeQueue = operation.then( () => { this._wqDepth--; }, @@ -613,7 +623,7 @@ class ConfigStore { }; await this._guardHosters(current, false); return this._commit(current); - }, options); + }, { ...options, coalesceKey: 'pending-queue' }); } saveFolderMonitorRuntimeState(folderMonitor, options = {}) { diff --git a/lib/mcp-app.js b/lib/mcp-app.js index b69f798..d3409b6 100644 --- a/lib/mcp-app.js +++ b/lib/mcp-app.js @@ -1,4 +1,5 @@ const { randomUUID } = require('node:crypto'); +const { getUploadReadSnapshot, setUploadReadLimit } = require('./upload-file-io'); const path = require('node:path'); const { McpAccessError, resolveGrantedFile } = require('./mcp-access'); const { createMcpFiles } = require('./mcp-files'); @@ -59,6 +60,7 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, canWrite(); guard(context); const result = await invoke(channel); if (result?.error || result?.monitorError) throw new McpAccessError(code); + if (channel === 'automation:resume') await renderer('automation-resume', {}, context); return result; }; const handlers = { @@ -76,6 +78,11 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, })), boundaries: ['Permissions and directory grants can only be changed locally.', 'Destructive actions require an exact local confirmation; MCP cannot approve it.', 'No arbitrary shell, SQL, mouse/keyboard or screen control.', 'Paused automation is resumed with mhu_automation_resume. A disabled monitor requires mhu_automation_start.'] }; }, mhu_performance_get: () => getPerformance(), + mhu_io_limits_get: () => getUploadReadSnapshot(), + mhu_io_limits_update: ({ readConcurrency }, context) => { + canWrite(); guard(context); + return setUploadReadLimit(readConcurrency); + }, mhu_system_metrics: args => getSystemMetrics(args), mhu_app_state: async (args, context) => ({ ...(await renderer('state', {}, context)), automation: await invoke('automation:get-status') }), mhu_queue_list: (args, context) => renderer('queue-list', args, context), diff --git a/lib/mcp-tools.js b/lib/mcp-tools.js index 296ded7..9a8126d 100644 --- a/lib/mcp-tools.js +++ b/lib/mcp-tools.js @@ -19,13 +19,15 @@ const definitions = [ ['app_info', 'Read application version and runtime information.', 'read', {}, []], ['capabilities', 'Read effective permissions, the supported action catalog and local security boundaries. This cannot grant permissions or approve actions.', 'read', {}, []], ['performance_get', 'Read bounded in-memory main-thread, renderer, CPU, memory, I/O and transfer-slot measurements. Missing samples do not prove a freeze.', 'read', {}, []], + ['io_limits_get', 'Read active, waiting and maximum concurrent upload file reads.', 'read', {}, []], + ['io_limits_update', 'Adjust bounded upload file-read concurrency in memory. Does not abort transfers or persist settings; default returns after restart.', 'control', { readConcurrency: integer(1, 32) }, ['readConcurrency']], ['system_metrics', 'Read cached system CPU, RAM, disk activity, read/write throughput, cumulative byte counters and volume capacity. No shell commands. Samples every 10 seconds; null or stale values are not freeze evidence.', 'read', { limit: integer(1, 60) }, []], ['app_state', 'Read live transfer and automation summary.', 'read', {}, []], ['queue_list', 'Read a bounded page of upload jobs.', 'read', { ...page, status: text(40) }, []], ['queue_job_log', 'Read a bounded, secret-filtered log for one upload job.', 'read', { jobId: id, ...page }, ['jobId']], ['queue_add', 'Add files from a granted directory to the upload queue.', 'control', { rootId: id, paths: array(text(), 1000), hosters: array(hoster, 5) }, ['rootId', 'paths', 'hosters']], ['queue_start', 'Start eligible queued uploads.', 'control', jobIds, []], - ['queue_pause', 'Pause new uploads after current transfers.', 'control', {}, []], + ['queue_pause', 'Immediately abort active uploads and pause new work. Paused files restart from the beginning on resume.', 'control', {}, []], ['queue_resume', 'Resume the shared upload and automation pause.', 'control', {}, []], ['queue_retry', 'Retry selected failed jobs.', 'control', jobIds, ['jobIds']], ['queue_cancel', 'Cancel selected running or queued jobs.', 'control', jobIds, ['jobIds']], @@ -63,7 +65,7 @@ const definitions = [ queueLimitJobs: integer(0, 100000), reconcileIntervalMinutes: integer(1, 1440) }, ['rootId'], true], ['automation_start', 'Start configured folder monitoring.', 'control', {}, []], - ['automation_pause', 'Pause the shared upload queue and folder automation after active transfers. Does not disable the configured monitor.', 'control', {}, []], + ['automation_pause', 'Immediately abort active uploads and pause the shared queue and folder automation. Resume restarts paused files from the beginning. Does not disable the configured monitor.', 'control', {}, []], ['automation_resume', 'Resume the shared upload queue and configured folder automation. Use this for paused=true, not automation_start. Does not enable a disabled monitor.', 'control', {}, []], ['automation_stop', 'Stop folder monitoring without removing queued jobs.', 'control', {}, []], ['automation_scan', 'Run a read-only folder monitoring test scan.', 'read', {}, []], diff --git a/lib/upload-file-io.js b/lib/upload-file-io.js index 271daa3..e59e330 100644 --- a/lib/upload-file-io.js +++ b/lib/upload-file-io.js @@ -1,23 +1,48 @@ const fs = require('node:fs'); const { runtimePerformance } = require('./performance-monitor'); +const Semaphore = require('./semaphore'); const statUploadFile = file => runtimePerformance.measure('file.stat', () => fs.promises.stat(file)); -async function* readUploadFile(file, signal) { - signal?.throwIfAborted(); - const stream = fs.createReadStream(file, { highWaterMark: 1024 * 1024, ...(signal ? { signal } : {}) }); - const iterator = stream[Symbol.asyncIterator](); - try { - for (;;) { - const result = await runtimePerformance.measure('file.read', () => iterator.next()); - if (result.done) break; +function createUploadFileReader({ limit = 4, open = file => fs.promises.open(file, 'r') } = {}) { + const slots = new Semaphore(limit); + const admitted = async (signal, action) => { + await runtimePerformance.measure('file.read.wait', () => slots.acquire(signal)); + try { signal?.throwIfAborted(); - yield result.value; + return await action(); + } finally { + slots.release(); } - } finally { - stream.destroy(); - await iterator.return?.(); - } + }; + return { + snapshot: () => ({ limit: slots.limit, active: slots.active, waiting: slots.pending }), + updateLimit(value) { + if (!Number.isInteger(value) || value < 1 || value > 32) throw new Error('Ungültiges Lese-Limit.'); + slots.updateLimit(value); + return this.snapshot(); + }, + async *read(file, signal) { + signal?.throwIfAborted(); + const handle = await admitted(signal, () => open(file)); + try { + for (;;) { + const buffer = Buffer.allocUnsafe(1024 * 1024); + const result = await admitted(signal, () => runtimePerformance.measure('file.read', () => handle.read(buffer, 0, buffer.length, null))); + signal?.throwIfAborted(); + if (!result.bytesRead) break; + yield buffer.subarray(0, result.bytesRead); + } + } finally { + await handle.close(); + } + } + }; } -module.exports = { statUploadFile, readUploadFile }; +const uploadFileReader = createUploadFileReader(); +const readUploadFile = (file, signal) => uploadFileReader.read(file, signal); +const getUploadReadSnapshot = () => uploadFileReader.snapshot(); +const setUploadReadLimit = value => uploadFileReader.updateLimit(value); + +module.exports = { statUploadFile, readUploadFile, getUploadReadSnapshot, setUploadReadLimit, createUploadFileReader }; diff --git a/lib/upload-manager.js b/lib/upload-manager.js index 8ec9f35..3ee7b80 100644 --- a/lib/upload-manager.js +++ b/lib/upload-manager.js @@ -11,6 +11,7 @@ const ClouddropUploader = require('./clouddrop-upload'); const Semaphore = require('./semaphore'); const Throttle = require('./throttle'); const { runtimePerformance } = require('./performance-monitor'); +const { getUploadReadSnapshot } = require('./upload-file-io'); const { probeFileHead } = require('./file-probe'); const { normalizeFailureDetails } = require('./upload-diagnostics'); const { classifyAccountFailure, selectFallbackAccount } = require('./account-rotation'); @@ -126,7 +127,7 @@ class UploadManager extends EventEmitter { } let pending = 0; for (const sem of Object.values(this.semaphores)) pending += (sem && sem.pending) || 0; - return { activeByHoster, transientErrors: this._transientErrorTotal, pending, active: this.activeJobs.size, + return { activeByHoster, transientErrors: this._transientErrorTotal, pending, active: this.activeJobs.size, diskReads: getUploadReadSnapshot(), globalSlots: this.globalSemaphore ? { active: this.globalSemaphore.active, pending: this.globalSemaphore.pending, limit: this.globalSemaphore.limit } : null, hosterSlots: Object.fromEntries(Object.entries(this.semaphores).map(([hoster, sem]) => [hoster, { active: sem.active, pending: sem.pending, limit: sem.limit }])), sessionBytes: this.sessionBytes, transferredBytes: this.transferredBytes, batchStartedAt: this.startTime, @@ -526,6 +527,7 @@ class UploadManager extends EventEmitter { let finalAttempt = 0; const recordFinalResult = (status, payload = {}) => { + if (status === 'aborted' && jobAbortController.signal.reason === 'automation-pause' && !this.cancelledJobIds.has(jobId) && !batchSignal.aborted) payload = { ...payload, error: 'Warteschlange angehalten' }; if (finalResultRecorded) return; finalResultRecorded = true; finalStatus = status; @@ -550,6 +552,7 @@ class UploadManager extends EventEmitter { }; const emitFinalStatus = (status, payload = {}) => { + if (status === 'aborted' && jobAbortController.signal.reason === 'automation-pause' && !this.cancelledJobIds.has(jobId) && !batchSignal.aborted) payload = { ...payload, error: 'Warteschlange angehalten' }; if (status === 'aborted' && this.abortController.signal.aborted) return; this._emitProgress(uploadId, fileName, task.hoster, { accountId: task.accountId, jobId, @@ -1575,8 +1578,27 @@ class UploadManager extends EventEmitter { if (!this.queueAdmissionAbortController.signal.aborted) this.queueAdmissionAbortController.abort(); } + pauseImmediately() { + this.finishAfterActive(); + for (const controller of this.jobAbortControllers.values()) { + if (!controller.signal.aborted) controller.abort('automation-pause'); + } + } + async resumeAfterActive() { const stoppedController = this.queueAdmissionAbortController; + const pausedJobs = new Set([...this.jobAbortControllers].filter(([, controller]) => controller.signal.reason === 'automation-pause').map(([jobId]) => jobId)); + if (pausedJobs.size) { + await new Promise(resolve => { + const settled = ({ jobId }) => { + pausedJobs.delete(jobId); + if (pausedJobs.size) return; + this.off('job-settled', settled); + resolve(); + }; + this.on('job-settled', settled); + }); + } await this._waitForQueueAdmissionIdle(); if (this.queueAdmissionAbortController === stoppedController && stoppedController.signal.aborted) { this.queueAdmissionAbortController = new AbortController(); diff --git a/main.js b/main.js index 31454b1..1ace7ee 100644 --- a/main.js +++ b/main.js @@ -199,9 +199,9 @@ const mcpUpdate = new McpUpdate({ restore: async snapshot => { mcpUpdateResuming = true; try { - if (snapshot?.wasUploading && !configStore.load().globalSettings?.folderMonitor?.paused) await internalUpdateRenderer('update-resume', snapshot); + if (snapshot?.wasUploading && !isAutomationPaused()) await internalUpdateRenderer('update-resume', snapshot); const settings = configStore.load().globalSettings?.folderMonitor; - if (snapshot?.monitorRunning && settings?.enabled && !settings.paused) await startFolderMonitor(settings); + if (snapshot?.monitorRunning && settings?.enabled && !isAutomationPaused()) await startFolderMonitor(settings); } finally { mcpUpdateResuming = false; } } }); @@ -2387,7 +2387,7 @@ ipcMain.handle('select-files', async () => { // Debug self-test: runs a minimal upload in the main process to verify events work ipcMain.handle('debug-test-upload', async () => { - if (configStore.load().globalSettings?.folderMonitor?.paused === true) { + if (isAutomationPaused()) { return { error: 'Automatik ist pausiert' }; } const testFile = path.join(__dirname, 'test-self-check.txt'); @@ -2500,7 +2500,7 @@ function preparedUploadStartGate(manager) { if (mcpUpdate.blocksTransfers() && !mcpUpdateResuming) return 'MCP-Update wird vorbereitet'; if (uploadManager !== manager) return 'Upload-Start wurde verworfen'; if (closeFlushRequested) return 'Die Anwendung wird gerade beendet'; - if (configStore.load().globalSettings?.folderMonitor?.paused === true) return 'Automatik ist pausiert'; + if (isAutomationPaused()) return 'Automatik ist pausiert'; return ''; } @@ -2575,7 +2575,7 @@ function startPreparedUploadBatch({ manager, tasks, producerTracker, recovery, i ipcMain.handle('start-upload', async (_event, payload) => { if (mcpUpdate.blocksTransfers() && !mcpUpdateResuming) return { error: 'MCP-Update wird vorbereitet' }; - if (configStore.load().globalSettings?.folderMonitor?.paused === true) { + if (isAutomationPaused()) { return { error: 'Automatik ist pausiert' }; } if (closeFlushRequested) return { error: 'Die Anwendung wird gerade beendet' }; @@ -2623,7 +2623,7 @@ ipcMain.handle('start-upload', async (_event, payload) => { if (tasks.length === 0) { await appendUploadPlanAudit(batchPlan, 'start'); - if (configStore.load().globalSettings?.folderMonitor?.paused === true) { + if (isAutomationPaused()) { return { error: 'Automatik ist pausiert' }; } const skippedSummary = stats.mergeSkippedIntoSummary({ @@ -2650,7 +2650,7 @@ ipcMain.handle('start-upload', async (_event, payload) => { await registerAutomationCompletionJobs(_thisManager, jobs); await appendUploadPlanAudit(batchPlan, 'start'); - if (configStore.load().globalSettings?.folderMonitor?.paused === true) { + if (isAutomationPaused()) { if (uploadManager === _thisManager) { uploadManager = null; globalThis._mhuUploadManagerRef = null; } return { error: 'Automatik ist pausiert' }; } @@ -2703,7 +2703,7 @@ ipcMain.handle('start-upload', async (_event, payload) => { } return { error: `Quelldatei-Schutz konnte nicht vorbereitet werden: ${error.message}` }; } - if (configStore.load().globalSettings?.folderMonitor?.paused === true) { + if (isAutomationPaused()) { if (uploadManager === _thisManager) { uploadManager = null; globalThis._mhuUploadManagerRef = null; } try { await configStore.saveUploadRecovery(null); } catch (error) { debugLog(`upload recovery state could not be cleared after automation pause: ${error.message}`); } return { error: 'Automatik ist pausiert' }; @@ -2989,7 +2989,7 @@ ipcMain.handle('cancel-selected-jobs', async (_event, jobIds) => { ipcMain.handle('add-jobs-to-batch', async (_event, payload) => { if (mcpUpdate.blocksTransfers() && !mcpUpdateResuming) return { error: 'MCP-Update wird vorbereitet' }; - if (configStore.load().globalSettings?.folderMonitor?.paused === true) { + if (isAutomationPaused()) { return { error: 'Automatik ist pausiert' }; } if (closeFlushRequested) return { error: 'Die Anwendung wird gerade beendet' }; @@ -3013,7 +3013,7 @@ ipcMain.handle('add-jobs-to-batch', async (_event, payload) => { const sourceCleanupFingerprints = batchManager.sourceFileCleanup ? await batchManager.sourceFileCleanup.registerGroups(sourceCleanupGroups) : {}; - if (configStore.load().globalSettings?.folderMonitor?.paused === true) { + if (isAutomationPaused()) { return { error: 'Automatik ist pausiert' }; } if (uploadManager !== batchManager || !batchManager.running) { @@ -3822,6 +3822,12 @@ function _sweepOrphanConfigTmps() { } const automationLifecycleQueue = []; +let automationPauseIntent = null; + +function isAutomationPaused() { + return automationPauseIntent !== null || configStore.load().globalSettings?.folderMonitor?.paused === true; +} + let automationLifecycleRunning = false; let automationLifecycleGeneration = 0; let automationStatusSuppressionDepth = 0; @@ -3867,8 +3873,8 @@ function automationStatusSnapshot() { ...folderMonitor.status(), enabled: settings.enabled === true, configured: String(settings.folderPath || '').trim().length > 0, - paused: settings.paused === true, - pausedAt: settings.pausedAt ?? null, + paused: isAutomationPaused(), + pausedAt: automationPauseIntent?.pausedAt ?? settings.pausedAt ?? null, queueLimitJobs: normalized.queueLimitJobs, reconcileIntervalMinutes: normalized.reconcileIntervalMinutes }); @@ -3954,11 +3960,11 @@ async function startFolderMonitor(settings, options = {}) { ...settings, queueLimitJobs: normalized.queueLimitJobs, reconcileIntervalMinutes: normalized.reconcileIntervalMinutes, - paused: persisted.paused === true, - pausedAt: persisted.paused === true ? (persisted.pausedAt ?? null) : null + paused: isAutomationPaused(), + pausedAt: isAutomationPaused() ? (automationPauseIntent?.pausedAt ?? persisted.pausedAt ?? null) : null }; bindFolderMonitorEvents(effectiveSettings); - if (persisted.paused === true) { + if (isAutomationPaused()) { folderMonitor.configure(effectiveSettings); debugLog(`folder-monitor configured while paused: ${effectiveSettings.folderPath}`); return { includesExisting: false, paused: true }; @@ -4014,25 +4020,28 @@ ipcMain.handle('automation:record-completions', async (_event, entries) => { return true; }); -ipcMain.handle('automation:pause-after-active', () => enqueueAutomationLifecycle(async generation => { - let monitorError = ''; - await withAutomationStatusSuppressed(async () => { - const latest = configStore.load(); - const settings = latest.globalSettings?.folderMonitor || {}; - await configStore.saveFolderMonitorRuntimeState({ ...settings, paused: true, pausedAt: Date.now() }); - invalidateFolderMonitorLifecycle(); - try { - await folderMonitor.pause(); - } catch { - monitorError = 'Ordnerüberwachung konnte nicht pausiert werden'; - } finally { - if (uploadManager) uploadManager.finishAfterActive(); - } +ipcMain.handle('automation:pause-after-active', () => { + assertConfigWriteAllowed(); + const intent = { pausedAt: Date.now() }; + automationPauseIntent = intent; + if (uploadManager) uploadManager.pauseImmediately(); + invalidateFolderMonitorLifecycle(); + const stopped = folderMonitor.pause().then(() => '', () => 'Ordnerüberwachung konnte nicht pausiert werden'); + publishAutomationStatus(); + return enqueueAutomationLifecycle(async generation => { + let monitorError = ''; + await withAutomationStatusSuppressed(async () => { + const latest = configStore.load(); + const settings = latest.globalSettings?.folderMonitor || {}; + await configStore.saveFolderMonitorRuntimeState({ ...settings, paused: true, pausedAt: intent.pausedAt }); + monitorError = await stopped; + }); + return publishAutomationStatus(monitorError ? { monitorError } : null, generation); }); - return publishAutomationStatus(monitorError ? { monitorError } : null, generation); -})); +}); ipcMain.handle('automation:resume', () => enqueueAutomationLifecycle(async generation => { + const pauseIntent = automationPauseIntent; let result; await withAutomationStatusSuppressed(async () => { const latest = configStore.load(); @@ -4042,20 +4051,25 @@ ipcMain.handle('automation:resume', () => enqueueAutomationLifecycle(async gener ...settings, queueLimitJobs: normalized.queueLimitJobs, reconcileIntervalMinutes: normalized.reconcileIntervalMinutes, - paused: settings.paused === true, - pausedAt: settings.pausedAt ?? null + paused: isAutomationPaused(), + pausedAt: pauseIntent?.pausedAt ?? settings.pausedAt ?? null }; const resumedSettings = { ...pausedSettings, paused: false, pausedAt: null }; try { if (resumedSettings.enabled && resumedSettings.folderPath) { await resumeFolderMonitor(resumedSettings); } + if (automationPauseIntent !== pauseIntent) throw new Error('Resume superseded by pause'); await configStore.saveFolderMonitorRuntimeState(resumedSettings); + if (automationPauseIntent !== pauseIntent) throw new Error('Resume superseded by pause'); + automationPauseIntent = null; if (uploadManager) await uploadManager.resumeAfterActive(); + if (automationPauseIntent !== null) throw new Error('Resume superseded by pause'); if (resumedSettings.enabled && resumedSettings.folderPath) { await folderMonitor.scan({ emitFiles: true, trigger: 'resume' }); } } catch { + if (automationPauseIntent === null && pausedSettings.paused) automationPauseIntent = { pausedAt: pausedSettings.pausedAt }; if (uploadManager) uploadManager.finishAfterActive(); stopFolderMonitor(); if (pausedSettings.enabled && pausedSettings.folderPath) { @@ -4076,7 +4090,7 @@ ipcMain.handle('folder-monitor:test-scan', () => { }); ipcMain.handle('folder-monitor:reconcile', () => { - if (configStore.load().globalSettings?.folderMonitor?.paused === true) { + if (isAutomationPaused()) { return { error: 'Automatik ist pausiert' }; } return folderMonitor.scan({ emitFiles: true, trigger: 'manual' }); diff --git a/package-lock.json b/package-lock.json index 3c0506d..ede4ce0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "multi-hoster-uploader", - "version": "2.1.74", + "version": "2.1.75", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "multi-hoster-uploader", - "version": "2.1.74", + "version": "2.1.75", "dependencies": { "chokidar": "^4.0.3", "undici": "7.29.1", diff --git a/package.json b/package.json index 35d3afd..50e1033 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "multi-hoster-uploader", - "version": "2.1.74", + "version": "2.1.75", "description": "Upload files to doodstream, voe, vidmoly, byse simultaneously", "main": "main.js", "scripts": { diff --git a/renderer/app.js b/renderer/app.js index bc6432f..c12e187 100644 --- a/renderer/app.js +++ b/renderer/app.js @@ -1166,7 +1166,7 @@ function renderAutomationStatusSnapshot(snapshot) { const pauseNotice = document.getElementById('automationPauseNotice'); if (pauseNotice) { pauseNotice.hidden = !snapshot.paused; - pauseNotice.textContent = snapshot.paused ? `${localizeUiText('Automatik pausiert seit')} ${formatAutomationDateTime(snapshot.pausedAt)}. ${localizeUiText('Fortsetzen aktiviert die Ordnerüberwachung und die Warteschlange. Aktive Uploads werden beim Pausieren noch abgeschlossen.')}` : ''; + pauseNotice.textContent = snapshot.paused ? `${localizeUiText('Automatik pausiert seit')} ${formatAutomationDateTime(snapshot.pausedAt)}. ${localizeUiText('Laufende Uploads werden sofort abgebrochen. Beim Fortsetzen starten diese Dateien von vorn; abgeschlossene Uploads bleiben erhalten.')}` : ''; } return snapshot; } @@ -1200,7 +1200,7 @@ function syncAutomationPauseResumeButton(snapshot) { if (settingsButton) { settingsButton.textContent = localized; settingsButton.disabled = automationPauseResumeBusy || snapshot.statusAvailable !== true; - settingsButton.title = localizeUiText('Fortsetzen aktiviert die Ordnerüberwachung und die Warteschlange. Aktive Uploads werden beim Pausieren noch abgeschlossen.'); + settingsButton.title = localizeUiText('Laufende Uploads werden sofort abgebrochen. Beim Fortsetzen starten diese Dateien von vorn; abgeschlossene Uploads bleiben erhalten.'); } } @@ -1384,6 +1384,25 @@ async function runAutomationTestOverlay() { } } +let automationJobResumePromise = null; + +async function resumeAutomationPausedJobs(guard) { + if (automationJobResumePromise) return automationJobResumePromise; + const operation = (async () => { + if (guard) await guard(); + const jobs = queueJobs.filter(job => job.automationPaused === true && ( + job.status === 'queued' || (job.status === 'aborted' && job.error === 'Warteschlange angehalten') + )); + if (!jobs.length) return { started: false }; + return startSelectedUpload(jobs, guard ? { guard } : undefined); + })(); + automationJobResumePromise = operation; + try { return await operation; } + finally { if (automationJobResumePromise === operation) automationJobResumePromise = null; } +} + +window.resumeAutomationPausedJobs = resumeAutomationPausedJobs; + async function toggleAutomationPauseResume() { if (automationPauseResumeBusy) return; const snapshot = createAutomationStatusSnapshot(); @@ -1402,14 +1421,7 @@ async function toggleAutomationPauseResume() { if (result?.error) throw new Error(result.error); applyAutomationRuntimeStatus({ ...result, paused: resume ? false : true }); if (resume) { - const resumableJobs = queueJobs.filter(job => job.automationPaused === true && ( - job.status === 'queued' - || (job.status === 'aborted' && job.error === 'Warteschlange angehalten') - )); - if (resumableJobs.length > 0) { - if (uploading) await startSelectedUpload(resumableJobs); - else await startSelectedUpload(resumableJobs); - } + await resumeAutomationPausedJobs(); } else { for (const job of queueJobs) { if (pausingJobIds.has(job.id) && ['queued', 'getting-server', 'uploading', 'retrying'].includes(job.status)) { @@ -2777,6 +2789,8 @@ function updateUploadView(options = {}) { queueActions.style.display = 'flex'; if (options.rebuildPreview !== false && !uploading && selectedFiles.length > 0) { buildQueuePreview(); + } else { + renderQueueTable(); } } updateQueueActionButtons(); diff --git a/renderer/i18n.js b/renderer/i18n.js index 9cf1ef1..e3658fe 100644 --- a/renderer/i18n.js +++ b/renderer/i18n.js @@ -410,7 +410,7 @@ ['Upload-Log konnte nicht gelesen werden', 'Upload log could not be read'], ['Abschlussnachweis konnte nicht gelesen werden', 'Completion records could not be read'], ['Fehlerdetails enthalten geschützte Daten.', 'Error details contain protected data.'], - ['Fortsetzen aktiviert die Ordnerüberwachung und die Warteschlange. Aktive Uploads werden beim Pausieren noch abgeschlossen.', 'Resuming enables folder monitoring and the queue. Active uploads are allowed to finish when pausing.'], + ['Laufende Uploads werden sofort abgebrochen. Beim Fortsetzen starten diese Dateien von vorn; abgeschlossene Uploads bleiben erhalten.', 'Active uploads are aborted immediately. On resume, these files restart from the beginning; completed uploads are kept.'], ['Automatik und Warteschlange pausiert. Fortsetzen ist unter Einstellungen → Automatik jederzeit möglich.', 'Automation and queue paused. Resume at any time under Settings → Automation.'], ['Die Tageszähler zählen Prüfungen und Aufnahmen. Wiederholte Abgleiche derselben Datei werden erneut gezählt.', 'Daily counters count checks and admissions. Repeated checks of the same file are counted again.'], ['Bereits hochgeladen laut Abschlussnachweis', 'Already uploaded according to completion records'], @@ -764,6 +764,7 @@ ['Ungültige URL (muss mit http(s):// beginnen)', 'Invalid URL (must start with http(s)://)'], ['Backup-Datei ist zu groß oder ungültig', 'The backup file is too large or invalid'], ['Ungültiges Backup-Format', 'Invalid backup format'], + ['Ungültiges Lese-Limit.', 'Invalid read concurrency limit.'], ['Keine gültige .mhu Backup-Datei', 'Not a valid .mhu backup file'], ['Falsches Passwort oder beschädigte Datei', 'Incorrect password or damaged file'], ['Dieses Backup wurde mit einem Passwort verschlüsselt', 'This backup was encrypted with a password'], diff --git a/renderer/mcp.js b/renderer/mcp.js index f31406e..3752cbf 100644 --- a/renderer/mcp.js +++ b/renderer/mcp.js @@ -21,6 +21,7 @@ const handlers = { state: async () => ({ source: 'live', stale: false, uploading, queueCount: queueJobs.length, selectedFileCount: selectedFiles.length, selectedHosters: getSelectedHosters(), counts: queueJobs.reduce((out, job) => { out[job.status] = (out[job.status] || 0) + 1; return out; }, {}) }), refresh, + 'automation-resume': (_args, guard) => window.resumeAutomationPausedJobs(guard), 'update-park': async () => { cancelStartupQueueAutoStart(); _cancelAutoRetry(true);