From c4439480bd9c7e4d277da369ada764434ee26123 Mon Sep 17 00:00:00 2001 From: Sucukdeluxe <259325684+Sucukdeluxe@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:12:21 +0200 Subject: [PATCH] Expand MCP controls and add cached system resource telemetry --- README.md | 6 ++ lib/mcp-app.js | 49 ++++++++-- lib/mcp-tools.js | 24 ++++- lib/system-metrics.js | 147 ++++++++++++++++++++++++++++++ main.js | 14 +-- scripts/verify-public-release.mjs | 1 + 6 files changed, 224 insertions(+), 17 deletions(-) create mode 100644 lib/system-metrics.js diff --git a/README.md b/README.md index 8538ff4..2e1f707 100644 --- a/README.md +++ b/README.md @@ -328,6 +328,12 @@ The update first saves its resume intent, stops new admission and waits for curr `mhu_performance_get` is read-only and returns bounded in-memory samples of main-thread timer delay, renderer round trips, CPU usage, process memory, asynchronous file-I/O waits and upload-slot occupancy. It does not launch host commands. A slow network request, provider wait or asynchronous disk operation is not itself a main-thread freeze. Long timer gaps are reported as measurement gaps, not proven freezes. Historical samples cover only the current process and their bounded retention window. +`mhu_system_metrics` provides separate system-wide CPU and RAM measurements, process CPU/RAM, Windows physical-disk read/write throughput, IOPS, activity, queue lengths, cumulative byte counters and volume capacity. Sampling runs every ten seconds while MCP is enabled. Windows storage counters are collected asynchronously through a fixed, hidden, timeout-limited system query; the tool itself only reads the cache. Use `limit` (1–60) for recent samples. Large responses are truncated with an explicit flag. Initial rates are `null` until two valid samples exist; failed queries retain the last storage sample with `available: false` and `stale: true`. Cumulative byte totals are decimal strings to preserve integer precision. Storage metrics cover the whole machine, not just uploader I/O; the `_Total` activity counter is an aggregate, not the busiest disk. + +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. + +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. ### Diagnostic artifacts and file transfer diff --git a/lib/mcp-app.js b/lib/mcp-app.js index 7e6f390..b69f798 100644 --- a/lib/mcp-app.js +++ b/lib/mcp-app.js @@ -1,9 +1,11 @@ const { randomUUID } = require('node:crypto'); +const path = require('node:path'); const { McpAccessError, resolveGrantedFile } = require('./mcp-access'); const { createMcpFiles } = require('./mcp-files'); const { createMcpTransfers } = require('./mcp-transfers'); const { createMcpDiagnostics } = require('./mcp-diagnostics'); const { createMcpSanitizer } = require('./mcp-security'); +const { MCP_TOOLS, requiresMcpConfirmation } = require('./mcp-tools'); const { redactLogText, collectSecretValues } = require('./support-bundle'); function page(items, args) { @@ -13,7 +15,7 @@ function page(items, args) { } function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, ...args) => invoke(channel, ...args), renderer, collectors, getGrants, trashFile, canWrite, - getCapabilities, getProtectedPaths, getInstallationId, getDiagnosticSources, getRuntimeDiagnostics = () => null, getPerformance = () => null, updates }) { + getCapabilities, getProtectedPaths, getInstallationId, getDiagnosticSources, getRuntimeDiagnostics = () => null, getPerformance = () => null, getSystemMetrics = () => null, updates }) { const transfers = createMcpTransfers({ getGrants, getCapabilities, getProtectedPaths, getInstallationId }); const sanitize = createMcpSanitizer(loadConfig); const guard = context => { @@ -48,16 +50,33 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, }; const saveGlobal = async (patch, context) => { canWrite(); guard(context); - await invoke('save-global-settings', { ...loadConfig().globalSettings, ...patch }); + const current = loadConfig().globalSettings; + await invoke('save-global-settings', { ...current, ...patch, ...(patch.scramble ? { scramble: { ...current.scramble, ...patch.scramble } } : {}) }); await refresh(context); return { saved: true }; }; + const automationAction = async (channel, code, context) => { + canWrite(); guard(context); + const result = await invoke(channel); + if (result?.error || result?.monitorError) throw new McpAccessError(code); + return result; + }; const handlers = { ...createMcpFiles({ getGrants, trashFile }), ...transfers.handlers, ...createMcpDiagnostics({ getSources: getDiagnosticSources, redact: text => sanitize(redactLogText(text, collectSecretValues(loadConfig()))) }), mhu_app_info: () => invoke('get-app-info'), + mhu_capabilities: () => { + const permissions = getCapabilities?.() || []; + const settings = loadConfig().globalSettings; + return { permissions, tools: MCP_TOOLS.filter(tool => tool.requiredScopes.every(scope => permissions.includes(scope))).map(tool => ({ + name: tool.name, readOnly: tool.annotations.readOnlyHint, requiredScopes: tool.requiredScopes, + localConfirmation: tool.destructive || requiresMcpConfirmation(tool.name, {}, settings), + conditionalConfirmation: tool.name === 'mhu_settings_update' + })), 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_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), mhu_queue_job_log: async args => page(await invoke('get-job-log', args.jobId), args), @@ -69,8 +88,8 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, return renderer('queue-add', { paths: files, hosters: args.hosters }, context); }, mhu_queue_start: (args, context) => renderer('queue-start', args, context), - mhu_queue_pause: () => invoke('automation:pause-after-active'), - mhu_queue_resume: async (args, context) => { guard(context); return invoke('automation:resume'); }, + mhu_queue_pause: (args, context) => automationAction('automation:pause-after-active', 'AUTOMATION_PAUSE_FAILED', context), + mhu_queue_resume: (args, context) => automationAction('automation:resume', 'AUTOMATION_RESUME_FAILED', context), mhu_queue_retry: (args, context) => renderer('queue-retry', args, context), mhu_queue_cancel: (args, context) => renderer('queue-cancel', args, context), mhu_queue_remove: (args, context) => renderer('queue-remove', args, context), @@ -110,7 +129,11 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, mhu_accounts_remove: (args, context) => saveAccount(args.accountId, {}, context, true), mhu_accounts_reset_failure: args => { const account = find(args.accountId); return invoke('reset-session-failed-account', { hoster: account.hoster, accountId: args.accountId }); }, mhu_settings_get: () => { const config = loadConfig(); const settings = { ...config.globalSettings }; delete settings.pendingQueue; delete settings.uploadRecovery; return { globalSettings: settings, hosterSettings: config.hosterSettings }; }, - mhu_settings_update: (args, context) => saveGlobal(args, context), + mhu_settings_update: async (args, context) => { + const result = await saveGlobal(args, context); + if (Object.hasOwn(args, 'shutdownAfterFinish')) await invoke('set-shutdown-after-finish', args.shutdownAfterFinish); + return result; + }, mhu_hoster_settings_update: async ({ hoster, ...patch }, context) => { canWrite(); guard(context); const current = loadConfig().hosterSettings; @@ -119,6 +142,8 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, return { saved: true }; }, mhu_automation_status: () => invoke('automation:get-status'), + mhu_automation_pause: (args, context) => automationAction('automation:pause-after-active', 'AUTOMATION_PAUSE_FAILED', context), + mhu_automation_resume: (args, context) => automationAction('automation:resume', 'AUTOMATION_RESUME_FAILED', context), mhu_automation_update: async ({ rootId, ...patch }, context) => { const folder = await resolveGrantedFile(getGrants(), rootId, ''); if (!folder.stat.isDirectory()) throw new McpAccessError('NOT_A_DIRECTORY'); @@ -128,9 +153,13 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, }, mhu_automation_start: async (args, context) => { const settings = loadConfig().globalSettings.folderMonitor; - if (!getGrants().some(grant => grant.path === settings.folderPath)) throw new McpAccessError('PATH_NOT_GRANTED'); + if (settings.paused === true) throw new McpAccessError('AUTOMATION_PAUSED'); + const normalize = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value); + if (!settings.folderPath || !getGrants().some(grant => normalize(grant.path) === normalize(settings.folderPath))) throw new McpAccessError('PATH_NOT_GRANTED'); await saveGlobal({ folderMonitor: { ...settings, enabled: true } }, context); guard(context); - return invoke('folder-monitor:start', { ...settings, enabled: true }); + const result = await invoke('folder-monitor:start', { ...settings, enabled: true }); + if (result?.error) throw new McpAccessError('AUTOMATION_START_FAILED'); + return result; }, mhu_automation_stop: async (args, context) => { await saveGlobal({ folderMonitor: { ...loadConfig().globalSettings.folderMonitor, enabled: false } }, context); return invoke('folder-monitor:stop'); }, mhu_automation_scan: () => invoke('folder-monitor:test-scan'), @@ -163,6 +192,12 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, mhu_update_status: (args, context) => updates.status(args, context), mhu_app_restart: () => invoke('app:restart'), mhu_app_quit: () => invoke('app:quit'), + mhu_shutdown_cancel: async (args, context) => { + canWrite(); guard(context); + await invoke('cancel-shutdown'); + await saveGlobal({ shutdownAfterFinish: 'nothing' }, context); + return { cancelled: true, shutdownAfterFinish: 'nothing' }; + }, mhu_secrets_read: args => { const { password, apiKey } = find(args.accountId); return { accountId: args.accountId, password: password || '', apiKey: apiKey || '' }; } }; Object.defineProperty(handlers, 'dispose', { value: () => transfers.dispose() }); diff --git a/lib/mcp-tools.js b/lib/mcp-tools.js index 5b1091b..296ded7 100644 --- a/lib/mcp-tools.js +++ b/lib/mcp-tools.js @@ -17,7 +17,9 @@ const file = { rootId: id, relativePath: text() }; 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', {}, []], + ['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']], @@ -44,12 +46,15 @@ const definitions = [ language: enumeration(['de', 'en']), globalMaxSpeedKbs: integer(0, 100000000), parallelUploadCount: integer(0, 100), autoRetryRounds: integer(0, 5), autoRetryDelayMin: integer(1, 1440), autoHealthCheckEnabled: boolean, resumeQueueOnLaunch: boolean, autoStartRestoredQueue: boolean, removeFromQueueOnDone: boolean, - logMode: enumeration(['single', 'daily', 'session']), logVerbose: boolean + logMode: enumeration(['single', 'daily', 'session']), logVerbose: boolean, + scaleParallelUploads: boolean, historyRetention: retention, + deleteSourceAfterSuccessfulUpload: boolean, shutdownAfterFinish: enumeration(['nothing', 'sleep', 'shutdown', 'restart']), + scramble: object({ active: boolean, prefix: text(200), suffix: text(200), chars: enumeration(['letters', 'numbers', 'both']), length: integer(0, 200) }) }, []], ['hoster_settings_update', 'Update one hoster transfer configuration.', 'settings', { hoster, retries: integer(0, 20), parallelCount: integer(1, 100), maxSpeedKbs: integer(0, 100000000), restartBelowKbs: integer(0, 100000000), timeIntervalSec: integer(0, 86400), maxSizeMb: integer(0, 100000000), - rotateAccounts: boolean, logToFile: boolean + rotateAccounts: boolean, logToFile: boolean, sizeMemoEnabled: boolean }, ['hoster']], ['automation_status', 'Read folder-monitor and automatic retry state.', 'read', {}, []], ['automation_update', 'Configure monitoring for an explicitly granted directory.', 'settings', { @@ -58,6 +63,8 @@ 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_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', {}, []], ['automation_reconcile', 'Reconcile the monitored directory with the queue.', 'control', {}, []], @@ -99,6 +106,7 @@ const definitions = [ ['update_status', 'Read an owned persistent update job, including progress and post-restart version verification.', 'read', { jobId: id }, []], ['app_restart', 'Restart the application after persisting its state.', 'lifecycle', {}, [], true], ['app_quit', 'Close the application after persisting its state.', 'lifecycle', {}, [], true], + ['shutdown_cancel', 'Cancel a pending automatic shutdown/restart/sleep countdown and persist the disabled completion action.', 'control', {}, []], ['secrets_read', 'Explicitly reveal credentials for one account; disabled by default.', 'secrets.read', account, ['accountId']] ]; @@ -107,7 +115,7 @@ const MCP_TOOLS = Object.freeze(definitions.map(([name, description, scope, prop name: 'mhu_' + name, description, scope: capabilities[scope] || scope, destructive, inputSchema: object(properties, required), requiredScopes: [...new Set([capabilities[scope] || scope, ...(['queue_add', 'automation_update'].includes(name) ? ['files'] : []), ...(name === 'files_delete' ? ['control'] : []), ...(name.startsWith('files_transfer_') ? ['read'] : [])])], annotations: { readOnlyHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope) && !['files_transfer_open', 'files_transfer_close'].includes(name), destructiveHint: destructive, - idempotentHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope) && name !== 'files_transfer_open', openWorldHint: /^(?:queue_(?:start|retry|resume)|accounts_(?:check|otp|request_otp)|automation_(?:start|reconcile)|cloud_|backup_|update_)/.test(name) } + idempotentHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope) && name !== 'files_transfer_open', openWorldHint: /^(?:queue_(?:start|retry|resume)|accounts_(?:check|otp|request_otp)|automation_(?:start|resume|reconcile)|cloud_|backup_|update_)/.test(name) } }))); function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit = () => {}, getCapabilities, requiresConfirmation = () => false }) { @@ -160,4 +168,12 @@ function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit return { list: () => MCP_TOOLS.filter(tool => typeof handlers[tool.name] === 'function'), call }; } -module.exports = { MCP_TOOLS, createMcpToolAdapter }; +function requiresMcpConfirmation(name, args, settings) { + if (name === 'mhu_settings_update') return args.deleteSourceAfterSuccessfulUpload === true + || (Object.hasOwn(args, 'shutdownAfterFinish') && args.shutdownAfterFinish !== 'nothing') + || (Object.hasOwn(args, 'historyRetention') && args.historyRetention !== 'all'); + if (!['mhu_queue_start', 'mhu_queue_retry', 'mhu_automation_start', 'mhu_automation_reconcile'].includes(name)) return false; + return settings.deleteSourceAfterSuccessfulUpload === true || !['nothing', undefined, null].includes(settings.shutdownAfterFinish); +} + +module.exports = { MCP_TOOLS, createMcpToolAdapter, requiresMcpConfirmation }; diff --git a/lib/system-metrics.js b/lib/system-metrics.js new file mode 100644 index 0000000..42ca785 --- /dev/null +++ b/lib/system-metrics.js @@ -0,0 +1,147 @@ +const os = require('node:os'); +const { execFile } = require('node:child_process'); +const { promisify } = require('node:util'); + +const WINDOWS_PROBE = "$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; $d=@(Get-CimInstance Win32_PerfRawData_PerfDisk_PhysicalDisk | ForEach-Object { @{ Name=$_.Name; Timestamp_PerfTime=[string]$_.Timestamp_PerfTime; Frequency_PerfTime=[string]$_.Frequency_PerfTime; Timestamp_Sys100NS=[string]$_.Timestamp_Sys100NS; PercentIdleTime=[string]$_.PercentIdleTime; DiskReadBytesPersec=[string]$_.DiskReadBytesPersec; DiskWriteBytesPersec=[string]$_.DiskWriteBytesPersec; DiskReadsPersec=[string]$_.DiskReadsPersec; DiskWritesPersec=[string]$_.DiskWritesPersec; CurrentDiskQueueLength=[string]$_.CurrentDiskQueueLength } }); $v=@(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' | ForEach-Object { @{ DeviceID=$_.DeviceID; Size=[string]$_.Size; FreeSpace=[string]$_.FreeSpace } }); @{disks=$d;volumes=$v} | ConvertTo-Json -Depth 4 -Compress"; + +async function readWindowsCounters({ runner = promisify(execFile), signal } = {}) { + const { stdout } = await runner('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', + ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', WINDOWS_PROBE], + { windowsHide: true, shell: false, timeout: 8000, maxBuffer: 1024 * 1024, encoding: 'utf8', signal }); + const value = JSON.parse(stdout.replace(/^\uFEFF/, '')); + if (!Array.isArray(value.disks) || !Array.isArray(value.volumes) || value.disks.length > 256 || value.volumes.length > 256) throw Error('INVALID_METRICS'); + return value; +} + +function counter(value) { + return /^\d{1,24}$/.test(String(value)) ? BigInt(value) : null; +} + +function delta(current, previous) { + const a = counter(current), b = counter(previous); + return a !== null && b !== null && a >= b ? Number(a - b) : null; +} + +function diskSample(current, previous) { + const ticks = delta(current.Timestamp_PerfTime, previous?.Timestamp_PerfTime); + const frequency = Number(current.Frequency_PerfTime); + const seconds = ticks > 0 && frequency > 0 ? ticks / frequency : null; + const rate = key => { + const difference = delta(current[key], previous?.[key]); + return seconds && difference !== null ? difference / seconds : null; + }; + const idle = delta(current.PercentIdleTime, previous?.PercentIdleTime); + const time = delta(current.Timestamp_Sys100NS, previous?.Timestamp_Sys100NS); + const read = rate('DiskReadBytesPersec'), write = rate('DiskWriteBytesPersec'); + const readTotal = counter(current.DiskReadBytesPersec), writeTotal = counter(current.DiskWriteBytesPersec); + return { + id: String(current.Name).slice(0, 256), intervalMs: seconds ? seconds * 1000 : null, + readBytesPerSecond: read, writeBytesPerSecond: write, totalBytesPerSecond: read !== null && write !== null ? read + write : null, + readOperationsPerSecond: rate('DiskReadsPersec'), writeOperationsPerSecond: rate('DiskWritesPersec'), + readBytesTotal: readTotal?.toString() ?? null, writeBytesTotal: writeTotal?.toString() ?? null, + totalBytes: readTotal !== null && writeTotal !== null ? (readTotal + writeTotal).toString() : null, + busyPercent: time > 0 && idle !== null ? Math.max(0, Math.min(100, (1 - idle / time) * 100)) : null, + queueLength: counter(current.CurrentDiskQueueLength) !== null ? Number(current.CurrentDiskQueueLength) : null + }; +} + +class SystemMetrics { + constructor(options = {}) { + this.os = options.os || os; + this.now = options.now || Date.now; + this.processCpu = options.processCpu || process.cpuUsage; + this.processMemory = options.processMemory || process.memoryUsage; + this.shouldCollect = options.shouldCollect || (() => true); + this.readDisks = options.readDisks || (process.platform === 'win32' ? readWindowsCounters : null); + this.limit = Math.max(1, Math.min(60, options.limit || 60)); + this.samples = []; + this.previous = null; + this.previousDisks = new Map(); + this.storage = { available: false, sampledAt: null, disks: [], volumes: [] }; + this.stopped = false; + } + + start() { + if (this.timer) return; + this.stopped = false; + void this.sample(); + this.timer = setInterval(() => { void this.sample(); }, 10000); + this.timer.unref?.(); + } + + stop() { + this.stopped = true; + clearInterval(this.timer); + this.timer = null; + this.controller?.abort(); + } + + sample() { + if (this.pending) return this.pending; + if (this.stopped || !this.shouldCollect()) return Promise.resolve(); + this.pending = this.capture().finally(() => { this.pending = null; }); + return this.pending; + } + + async capture() { + const startedAt = this.now(); + this.controller = new AbortController(); + let available = false; + try { + if (this.readDisks) { + const raw = await this.readDisks({ signal: this.controller.signal }); + if (this.stopped) return; + const disks = raw.disks.map(disk => diskSample(disk, this.previousDisks.get(disk.Name))); + this.previousDisks = new Map(raw.disks.map(disk => [disk.Name, disk])); + const volumes = raw.volumes.map(volume => { + const total = counter(volume.Size), free = counter(volume.FreeSpace); + const valid = total !== null && free !== null && free <= total; + return { id: String(volume.DeviceID).slice(0, 16), totalBytes: valid ? Number(total) : null, freeBytes: valid ? Number(free) : null, + usedBytes: valid ? Number(total - free) : null, usedPercent: valid && total > 0n ? Number(total - free) / Number(total) * 100 : null }; + }); + this.storage = { sampledAt: this.now(), disks, volumes }; + available = true; + } + } catch {} + if (this.stopped) return; + const now = this.now(), cpus = this.os.cpus(); + const totals = cpus.reduce((sum, cpu) => { + sum.idle += cpu.times.idle; + sum.total += Object.values(cpu.times).reduce((a, b) => a + b, 0); + return sum; + }, { idle: 0, total: 0 }); + const cpu = this.processCpu(), memory = this.processMemory(); + const elapsed = this.previous ? now - this.previous.at : null; + const totalDelta = this.previous && totals.total - this.previous.totals.total; + const cpuDelta = this.previous && cpu.user + cpu.system - this.previous.cpu.user - this.previous.cpu.system; + const totalMemory = this.os.totalmem(), freeMemory = this.os.freemem(); + const sample = { + at: now, intervalMs: elapsed, collectionDurationMs: now - startedAt, + system: { logicalCpuCount: cpus.length, cpuPercent: totalDelta > 0 ? Math.max(0, Math.min(100, 100 * (1 - (totals.idle - this.previous.totals.idle) / totalDelta))) : null, + memory: { totalBytes: totalMemory, freeBytes: freeMemory, usedBytes: totalMemory - freeMemory, usedPercent: totalMemory > 0 ? (totalMemory - freeMemory) / totalMemory * 100 : null }, uptimeSeconds: this.os.uptime() }, + process: { cpuPercentOneCore: elapsed > 0 && cpuDelta >= 0 ? cpuDelta / (elapsed * 10) : null, rssBytes: memory.rss, heapUsedBytes: memory.heapUsed ?? null, heapTotalBytes: memory.heapTotal ?? null, externalBytes: memory.external ?? null }, + storage: { ...this.storage, available, stale: !available, error: available ? null : this.readDisks ? 'STORAGE_METRICS_UNAVAILABLE' : 'STORAGE_METRICS_UNSUPPORTED' } + }; + this.previous = { at: now, totals, cpu }; + this.samples.push(sample); + if (this.samples.length > this.limit) this.samples.shift(); + } + + snapshot({ limit = 1 } = {}) { + const now = this.now(), latest = this.samples.at(-1) || null; + const requested = Math.max(1, Math.min(60, limit)); + const samples = []; + let bytes = 0; + for (const sample of this.samples.slice(-requested).reverse()) { + bytes += Buffer.byteLength(JSON.stringify(sample)); + if (bytes > 384 * 1024) break; + samples.unshift(sample); + } + return { at: now, intervalMs: 10000, collecting: !!this.pending, stale: !latest || now - latest.at > 30000, + ageMs: latest ? now - latest.at : null, latest, samples, returnedSamples: samples.length, + truncated: samples.length < Math.min(requested, this.samples.length), + notes: ['System CPU is normalized to 0–100%; process CPU uses one logical core as 100%.', 'Storage counters cover the whole system, not only this application. Byte totals are cumulative provider counters encoded as decimal strings.', 'Null rates require another valid sample. Missing or stale samples are not evidence of a freeze.'] }; + } +} + +module.exports = { SystemMetrics, diskSample, readWindowsCounters }; diff --git a/main.js b/main.js index 6602341..b948455 100644 --- a/main.js +++ b/main.js @@ -50,8 +50,11 @@ const { inspectImportEntries, inspectReadableImportPath } = require('./lib/impor const { normalizeAutomationSettings, automationCompletionKey, createAutomationCompletionWriter, isPathWithinAutomationFolder, normalizeAutomationCompletion } = require('./lib/automation-control'); const { McpService } = require('./lib/mcp-service'); const { createMcpApp } = require('./lib/mcp-app'); +const { requiresMcpConfirmation } = require('./lib/mcp-tools'); const { McpAccessError } = require('./lib/mcp-access'); const { runtimePerformance } = require('./lib/performance-monitor'); +const { SystemMetrics } = require('./lib/system-metrics'); +const systemMetrics = new SystemMetrics({ shouldCollect: () => mcpService?.active === true }); runtimePerformance.observeSyncFileOperations(fs); const { McpUpdate } = require('./lib/mcp-update'); const mcpLocalHandlers = new Map(); @@ -2009,6 +2012,7 @@ app.whenReady().then(async () => { createTray(); runtimePerformance.start({ version: app.getVersion(), getTransfers: () => uploadManager?.getDiagnostics() || null, pingRenderer: id => closeHandshakeReady && safeSend('performance:ping', id) }); + systemMetrics.start(); startupDiagnostics.write('window-load-dispatched'); void cloudLogSync.start(); void startMcpService(); @@ -2059,6 +2063,7 @@ app.on('before-quit', (event) => { app.on('will-quit', () => { if (quitTeardownStarted) return; quitTeardownStarted = true; + systemMetrics.stop(); void mcpService?.stop(); folderMonitorRendererReadyGeneration = null; if (updateCheckInterval) clearInterval(updateCheckInterval); @@ -4147,7 +4152,7 @@ async function startMcpService() { 'automation:pause-after-active', 'automation:resume', 'reset-session-failed-account', 'folder-monitor:stop', 'folder-monitor:start', 'folder-monitor:test-scan', 'folder-monitor:reconcile', 'get-history', 'prune-history', 'clear-history', 'cloud-log:status', 'cloud-log:configure', 'cloud-log:backfill', 'online-backup:list-managed', 'online-backup:create-managed', 'online-backup:delete-managed', 'online-backup:restore', 'app:check-updates', 'app:install-update', 'app:restart', 'app:quit', - 'get-job-log', 'get-session-failed-account-states']); + 'get-job-log', 'get-session-failed-account-states', 'set-shutdown-after-finish', 'cancel-shutdown']); const invoke = async (channel, ...args) => { if (!allowed.has(channel) || !mcpLocalHandlers.has(channel) || !mainWindow || mainWindow.isDestroyed()) throw new McpAccessError('ACTION_UNAVAILABLE'); return mcpLocalHandlers.get(channel)({ sender: mainWindow.webContents, senderFrame: mainWindow.webContents.mainFrame }, ...args); @@ -4161,6 +4166,7 @@ async function startMcpService() { const handlers = createMcpApp({ loadConfig: () => configStore.load(), invoke, invokeGuarded, renderer: mcpRendererAction, collectors: createAppCollectors(), updates: mcpUpdate, getPerformance: () => runtimePerformance.snapshot(), + getSystemMetrics: args => systemMetrics.snapshot(args), getGrants: () => mcpService?.store.value.grants || [], trashFile: file => require('electron').shell.trashItem(file), canWrite: assertConfigWriteAllowed, getCapabilities: () => mcpService?.capabilities() || [], getProtectedPaths: () => [app.getPath('userData'), configStore.filePath, configStore.historyPath, configStore.automationCompletionPath], @@ -4181,11 +4187,7 @@ async function startMcpService() { safeSend('mcp:status', status); void mcpUpdate.recover({ rendererReady: closeHandshakeReady, connected: status.connection === 'online' }); }, - requiresConfirmation: name => { - if (!['mhu_queue_start', 'mhu_queue_retry', 'mhu_automation_start', 'mhu_automation_reconcile'].includes(name)) return false; - const settings = configStore.load().globalSettings; - return settings.deleteSourceAfterSuccessfulUpload === true || !['nothing', undefined, null].includes(settings.shutdownAfterFinish); - }, + requiresConfirmation: (name, args) => requiresMcpConfirmation(name, args, configStore.load().globalSettings), audit: event => logInfo(`mcp ${JSON.stringify({ time: new Date().toISOString(), ...event })}`) }); await mcpService.start(); diff --git a/scripts/verify-public-release.mjs b/scripts/verify-public-release.mjs index 266954e..cb9a2c7 100644 --- a/scripts/verify-public-release.mjs +++ b/scripts/verify-public-release.mjs @@ -51,6 +51,7 @@ const sourceFiles = [ 'lib/mcp-transfers.js', 'lib/mcp-update.js', 'lib/performance-monitor.js', + 'lib/system-metrics.js', 'lib/upload-file-io.js', 'lib/online-backup.js', 'lib/online-backup-keyring.js',