"use strict"; // End-to-end UI check of chj.system-monitor with the real plugin runtime and preload. // Linux (default): disposable privileged Docker container (image CHJ_USERS_IMAGE, default chj-users-it-debian); // creates and deletes a swap file on a loop-mounted ext4 through the UI forms (sudo dialog). // Windows: CHJ_SMOKE_WINDOWS=1 with CHJ_USERS_WINDOWS_HOST/_USER/_FINGERPRINT and _PASSWORD or _KEY; // sets a manual pagefile (pending restart only) and restores automatic management. Never restarts Windows. // Isolated Linux VM: CHJ_SMOKE_VM=1 with CHJ_VM_HOST/_FINGERPRINT/_KEY and CHJ_VM_SUDO_PASSWORD or _FILE + _LINE; // creates two swap files, sets main/backup priority through the priority dialog, then deletes both. // Run: npx electron scripts/smokeSystemMonitorUi.js [screenshot-dir] const { app, BrowserWindow, ipcMain, protocol } = require("electron"); const assert = require("node:assert/strict"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const { execFileSync, spawnSync } = require("node:child_process"); const { hardenSession } = require("../src/main/bootstrap/createMainWindow"); const { PluginRegistry } = require("../src/main/plugins/pluginRegistry"); const { PluginRuntime } = require("../src/main/plugins/pluginRuntime"); const { SessionManager } = require("../src/main/sessions/sessionManager"); const { PrivilegedExecutor } = require("../src/main/sessions/privilegedExec"); const { VirtualMemoryService } = require("../src/main/system/virtualMemoryService"); const env = process.env; const windows = env.CHJ_SMOKE_WINDOWS === "1"; const linuxVm = env.CHJ_SMOKE_VM === "1"; const vmSudo = !linuxVm ? "" : env.CHJ_VM_SUDO_PASSWORD || fs.readFileSync(env.CHJ_VM_SUDO_PASSWORD_FILE, "utf8").split("\n")[Number(env.CHJ_VM_SUDO_PASSWORD_LINE || 1) - 1].split("=").slice(1).join("=").trim(); const vmShell = (command) => execFileSync("ssh", ["-i", env.CHJ_VM_KEY, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", `UserKnownHostsFile=${path.join(root, "known_hosts")}`, "-o", "StrictHostKeyChecking=yes", `${env.CHJ_VM_USER || "ai"}@${env.CHJ_VM_HOST}`, command], { encoding: "utf8" }); const container = `chj-sysmon-ui-${process.pid}`; const root = fs.mkdtempSync(path.join(os.tmpdir(), "chj-sysmon-ui-")); const shots = process.argv.find((arg, index) => index > 1 && !arg.startsWith("-") && !arg.endsWith(".js")) || null; app.setPath("userData", root); protocol.registerSchemesAsPrivileged([{ scheme: "chj-plugin", privileges: { standard: true, secure: true, supportFetchAPI: true } }]); const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const errors = []; let window; let restoreWindows = async () => {}; const js = (source) => window.webContents.executeJavaScript(source); async function until(source, timeout = 60000) { const started = Date.now(); while (Date.now() - started < timeout) { if (await js(`(() => { try { return (${source}); } catch { return false; } })()`)) return; await delay(100); } throw new Error(`UI condition timed out: ${source}\nstatus: ${await js("document.querySelector('#status').textContent + ' | ' + (document.querySelector('#vmStatus')?.textContent || '')")}`); } async function shot(name) { if (shots) { fs.mkdirSync(shots, { recursive: true }); fs.writeFileSync(path.join(shots, `${name}.png`), (await window.webContents.capturePage()).toPNG()); } } async function confirm() { await until("document.querySelector('#confirmDialog').open"); await js("document.querySelector('#confirmForm').requestSubmit()"); } async function sudo() { await until("document.querySelector('#sudoDialog').open"); await js(`document.querySelector('#sudoPassword').value = ${JSON.stringify(linuxVm ? vmSudo : "AdminPass-1")}; document.querySelector('#sudoForm').requestSubmit();`); } // The sudo dialog appears only when Core reports that a password is needed (once per operation here). async function maybeSudo(doneSource) { for (const started = Date.now(); Date.now() - started < 120000; await delay(100)) { if (await js("document.querySelector('#sudoDialog').open")) { await sudo(); return; } if (await js(`(() => { try { return (${doneSource}); } catch { return false; } })()`)) return; } } async function run() { let profile; let password = ""; if (windows) { profile = { id: "w", label: "Windows", host: env.CHJ_USERS_WINDOWS_HOST, port: 22, username: env.CHJ_USERS_WINDOWS_USER, authMethod: env.CHJ_USERS_WINDOWS_KEY ? "privateKey" : "password", privateKeyPath: env.CHJ_USERS_WINDOWS_KEY }; password = env.CHJ_USERS_WINDOWS_PASSWORD || ""; } else if (linuxVm) { fs.writeFileSync(path.join(root, "known_hosts"), execFileSync("ssh-keyscan", ["-t", "ed25519", env.CHJ_VM_HOST], { encoding: "utf8" })); const seen = execFileSync("ssh-keygen", ["-lf", path.join(root, "known_hosts")], { encoding: "utf8" }); assert.ok(seen.includes(env.CHJ_VM_FINGERPRINT), "VM host key matches the recorded fingerprint"); profile = { id: "vm", label: "Linux VM", host: env.CHJ_VM_HOST, port: 22, username: env.CHJ_VM_USER || "ai", authMethod: "privateKey", privateKeyPath: env.CHJ_VM_KEY }; } else { execFileSync("docker", ["run", "-d", "--rm", "--privileged", "--name", container, "-p", "127.0.0.1::22", env.CHJ_USERS_IMAGE || "chj-users-it-debian"]); await delay(1500); spawnSync("docker", ["exec", container, "sh", "-c", "mkdir -p /swap && truncate -s 3G /img && mkfs.ext4 -q /img && mount -o loop /img /swap && : > /etc/fstab"]); const port = Number(execFileSync("docker", ["port", container, "22/tcp"], { encoding: "utf8" }).trim().split(":").pop()); profile = { id: "l", label: "Linux test", host: "127.0.0.1", port, username: "admin", authMethod: "password" }; password = "AdminPass-1"; } await app.whenReady(); hardenSession(); const hostKeys = new Map(); if (windows) hostKeys.set(profile.port, Buffer.from(`${env.CHJ_USERS_WINDOWS_FINGERPRINT}=`, "base64").toString("hex")); if (linuxVm) hostKeys.set(profile.port, Buffer.from(`${env.CHJ_VM_FINGERPRINT.replace(/^SHA256:/, "")}=`, "base64").toString("hex")); const profileService = { get: () => profile, getHostKey: (_h, p) => hostKeys.get(p) || null, trustHostKey: (_h, p, fp) => hostKeys.set(p, fp), getStoredPassword: () => password, markUsed() {} }; const sessionManager = new SessionManager({ profileService, latencyMonitor: { start: () => () => {} } }); try { await sessionManager.connect({ sessionId: "ui", profileId: profile.id }); } catch (error) { sessionManager.trustPending({ sessionId: "ui", profileId: profile.id, fingerprint: error.fingerprint }); await sessionManager.connect({ sessionId: "ui", profileId: profile.id }); } const virtualMemory = new VirtualMemoryService({ sessionManager, privilegedExecutor: new PrivilegedExecutor({ sessionManager }) }); const original = windows ? await virtualMemory.read("ui") : null; // Restores automatic pagefile management even when an assertion fails. if (linuxVm) restoreWindows = async () => { for (const name of ["/swapfile-chjui", "/swapfile-chjui2"]) { try { await virtualMemory.manage("ui", { action: "delete", path: name, sudoPassword: vmSudo }); } catch {} } }; if (windows) restoreWindows = async () => { if (windows && original?.automatic) { const now = await virtualMemory.read("ui"); if (now.automatic !== true) await virtualMemory.manage("ui", { action: "automatic" }); } }; const registry = new PluginRegistry(root, null, { bundledRoot: path.join(__dirname, "../src/main/firstPartyPlugins") }); const runtime = new PluginRuntime({ BrowserWindow, registry, sessionManager, virtualMemory, preload: path.join(__dirname, "../src/preload/pluginPreload.js"), getMainWindow: () => null, isVaultUnlocked: () => true }); runtime.registerIpc(ipcMain); runtime.open("chj.system-monitor"); window = runtime.windows.get("chj.system-monitor"); window.webContents.on("console-message", (event) => { if (event.level === "error") errors.push(event.message); }); window.setSize(1320, 1000); await until("document.querySelector('#status').textContent.includes('Aktualizováno')"); await delay(5600); await until("document.querySelector('#cpu').textContent.includes('%')", 20000); if (windows) { assert.equal(await js("document.querySelector('#swapLabel').textContent"), "Pagefile"); assert.equal(await js("document.querySelector('#kernelLabel').textContent"), "Sestavení"); assert.equal(await js("document.querySelector('#load').textContent"), "nedostupné", "no fake load average"); } else { assert.equal(await js("document.querySelector('#diskLabel').textContent"), "Disk /"); } await js("document.querySelector('#memorySection').open = true"); await delay(400); assert.ok(await js("document.querySelectorAll('#ramStack i').length >= 4"), "RAM breakdown rendered"); await shot(windows ? "s01-windows-overview" : "s01-linux-overview"); await js("document.querySelector('#memorySection').scrollIntoView()"); await shot(windows ? "s02-windows-memory" : "s02-linux-memory"); await js("document.querySelector('#manageVmButton').click()"); await until("document.querySelector('#vmDialog').open && document.querySelector('#vmContent table')"); await shot(windows ? "s03-windows-manage" : "s03-linux-manage"); if (windows) { await js("document.querySelector('#pfInitialValue').value = '1024'; document.querySelector('#pfMaximumValue').value = '2048'; Array.from(document.querySelectorAll('#vmContent button')).find(b => b.textContent.includes('Uložit')).click();"); await confirm(); await until("document.querySelector('#vmStatus').textContent.toLowerCase().includes('čeká na restart')", 120000); assert.match(await js("document.querySelector('#vmContent').textContent"), /Čeká na restart/); await shot("s04-windows-pending"); if (original.automatic) { await js("Array.from(document.querySelectorAll('#vmContent button')).find(b => b.textContent.includes('automatickou')).click()"); await confirm(); await until("document.querySelector('#vmStatus').textContent.includes('Uloženo')", 120000); const restored = await virtualMemory.read("ui"); assert.equal(restored.automatic, true); assert.equal(restored.restartPending, false, "reverting clears the pending state"); } } else if (linuxVm) { const names = ["/swapfile-chjui", "/swapfile-chjui2"]; const row = (name) => `Array.from(document.querySelectorAll('#vmContent tbody tr')).find(r => r.cells[0].textContent === '${name}')`; for (const name of names) { await js(`document.querySelector('#swapDir').value = '/'; document.querySelector('#swapName').value = '${name.slice(1)}'; document.querySelector('#swapSizeValue').value = '128'; document.querySelector('#swapSizeUnit').value = 'MiB'; document.querySelector('#swapPriority').value = ''; document.querySelector('#swapPersist').checked = true;`); await js("Array.from(document.querySelectorAll('#vmContent button')).find(b => b.textContent.includes('Vytvořit')).click()"); await confirm(); await maybeSudo("document.querySelector('#vmStatus').textContent.includes('Provedeno')"); await until("document.querySelector('#vmStatus').textContent.includes('Provedeno')", 120000); await until(`${row(name)}`); } assert.match(await js(`${row(names[0])}.cells[4].textContent`), /-\d+ \(automatická\)/, "automatic negative priority shown as automatic"); // Main = 100, backup = 10 through the dialog. for (const [name, value] of [[names[0], 100], [names[1], 10]]) { await js(`Array.from(${row(name)}.querySelectorAll('button')).find(b => b.textContent.startsWith('Priorita')).click()`); await until("document.querySelector('#priorityDialog').open"); assert.equal(await js("document.querySelector('#priorityAuto').checked"), true); assert.equal(await js("document.querySelector('#priorityValue').disabled"), true); assert.match(await js("document.querySelector('#priorityFacts').textContent"), /Uložená priorita: automatická/); await js("document.querySelector('#priorityCustom').click(); document.querySelector('#priorityValue').value = '-5'; document.querySelector('#priorityForm').requestSubmit();"); assert.equal(await js("document.querySelector('#priorityError').hidden"), false, "negative custom value is refused"); if (name === names[0]) await shot("s05-linux-priority-dialog"); await js(`document.querySelector('#priorityValue').value = '${value}'; document.querySelector('#priorityNow').checked = true; document.querySelector('#priorityForm').requestSubmit();`); await maybeSudo("document.querySelector('#vmStatus').textContent.includes('Uloženo do /etc/fstab')"); await until("document.querySelector('#vmStatus').textContent.includes('Uloženo do /etc/fstab') && document.querySelector('#vmStatus').textContent.includes('Aktivní priorita je nyní " + value + "')", 120000); } await until(`${row(names[0])}.cells[4].textContent.includes('1. pořadí') && ${row(names[1])}.cells[4].textContent.includes('2. pořadí')`); await shot("s06-linux-priorities"); const swaps = vmShell("cat /proc/swaps"), fstab = vmShell("cat /etc/fstab"); assert.match(swaps, /\/swapfile-chjui\s+file\s+\d+\s+\d+\s+100/); assert.match(swaps, /\/swapfile-chjui2\s+file\s+\d+\s+\d+\s+10\b/); assert.match(fstab, /^\/swapfile-chjui none swap sw,pri=100 0 0 # CH-J chj\.system-monitor$/m); assert.match(fstab, /^\/swapfile-chjui2 none swap sw,pri=10 0 0 # CH-J chj\.system-monitor$/m); // Reopening shows the custom mode with the saved value. await js(`Array.from(${row(names[0])}.querySelectorAll('button')).find(b => b.textContent.startsWith('Priorita')).click()`); await until("document.querySelector('#priorityDialog').open"); assert.equal(await js("document.querySelector('#priorityCustom').checked && document.querySelector('#priorityValue').value"), "100"); await js("document.querySelector('#priorityDialog [data-close]').click()"); for (const name of names) { await js(`${row(name)}.querySelector('button.danger').click()`); await confirm(); await maybeSudo("!document.querySelector('#vmContent').textContent.includes('" + name + " ') && document.querySelector('#vmStatus').textContent.includes('Provedeno')"); await until(`!${row(name)} && document.querySelector('#vmStatus').textContent.includes('Provedeno')`, 120000); } assert.doesNotMatch(vmShell("cat /proc/swaps; cat /etc/fstab"), /swapfile-chjui/); } else { await js("document.querySelector('#swapDir').value = '/swap'; document.querySelector('#swapName').value = 'ui-swap'; document.querySelector('#swapSizeValue').value = '256'; document.querySelector('#swapSizeUnit').value = 'MiB'; document.querySelector('#swapPersist').checked = true;"); await js("Array.from(document.querySelectorAll('#vmContent button')).find(b => b.textContent.includes('Vytvořit')).click()"); await confirm(); await sudo(); await until("document.querySelector('#vmStatus').textContent.includes('Provedeno')", 120000); assert.match(spawnSync("docker", ["exec", container, "cat", "/proc/swaps"], { encoding: "utf8" }).stdout, /\/swap\/ui-swap/); await until("document.querySelector('#vmContent').textContent.includes('/swap/ui-swap')"); await shot("s04-linux-created"); await js("Array.from(document.querySelectorAll('#vmContent tr')).find(r => r.textContent.includes('/swap/ui-swap')).querySelector('button.danger').click()"); await confirm(); await sudo(); await until("document.querySelector('#vmStatus').textContent.includes('Provedeno')", 120000); assert.doesNotMatch(spawnSync("docker", ["exec", container, "cat", "/proc/swaps"], { encoding: "utf8" }).stdout, /ui-swap/); assert.equal(spawnSync("docker", ["exec", container, "cat", "/etc/fstab"], { encoding: "utf8" }).stdout, ""); } assert.deepEqual(errors, [], "no renderer errors"); await sessionManager.disconnectAll(); console.log(`chj.system-monitor ${windows ? "Windows" : linuxVm ? "Linux VM (priorities)" : "Linux"} UI smoke passed`); } function cleanup() { if (!windows && !linuxVm) spawnSync("docker", ["rm", "-f", container]); fs.rmSync(root, { recursive: true, force: true }); } run().then(() => { cleanup(); app.exit(0); }, async (error) => { console.error(error); try { await restoreWindows(); } catch (restoreError) { console.error("Pagefile restore failed", restoreError); } cleanup(); app.exit(1); });