diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 34a0c73..3169998 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -3,7 +3,7 @@ import { existsSync, readFileSync } from 'node:fs' import { cpus, totalmem } from 'node:os' import { isAbsolute } from 'node:path' import { defaultConfig, validPort, type VmConfig } from '@shared/config' -import type { AppSettings, AutostartIssue, DiskInfo, HostInfo, PowerAction, Profile, SaveStateResult, StartResult } from '@shared/ipc' +import type { AppSettings, AutostartIssue, DiskInfo, DiskWork, HostInfo, PowerAction, Profile, SaveStateResult, StartResult, VmWork } from '@shared/ipc' import { agentHibernate } from './agent' import { cloneVm, compactDisk, resizeDisk } from './disks' import { runAutostart } from './autostart' @@ -38,6 +38,13 @@ export interface IpcContext { relaunch: () => void } +/** for the error when something is refused during disk work: "Kali is having its disk compacted" */ +const diskWorkText: Record = { + cloning: 'being cloned', + compacting: 'having its disk compacted', + growing: 'getting a bigger disk' +} + export function registerIpc(ctx: IpcContext): Backend { const { paths, getWindow } = ctx // read on every call, so a QEMU path saved in Settings is used from the next start on @@ -45,7 +52,7 @@ export function registerIpc(ctx: IpcContext): Backend { const runner = new VmRunner(paths, qemu) const guestSetup = new GuestSetupServer() const send = (channel: string, payload?: unknown) => getWindow()?.webContents.send(channel, payload) - const profiles = new Profiles(paths, runner, (name, work) => send('vm:profileWork', { name, work })) + const profiles = new Profiles(paths, runner, (name, work) => send('vm:work', { name, work })) runner.on('state', (s) => send('vm:state', s)) runner.on('crash', (c) => send('vm:crash', c)) @@ -136,28 +143,31 @@ export function registerIpc(ctx: IpcContext): Backend { }) // a full clone or a compact works on the disk for minutes, nothing may start or change the VM - // meanwhile. VM name -> what is going on, for the error message - const diskWork = new Map() - const withDiskWork = async (name: string, what: string, fn: () => Promise): Promise => { + // meanwhile. The renderer is told too, so the toolbar can show it and disable what would be refused + const diskWork = new Map() + const withDiskWork = async (name: string, work: DiskWork, fn: () => Promise): Promise => { + byName(name) // only a real VM gets announced to the renderer notBusy(name) - diskWork.set(name, what) + diskWork.set(name, work) + send('vm:work', { name, work }) try { return await fn() } finally { diskWork.delete(name) + send('vm:work', { name, work: null }) } } // a profile save leaves the VM off for a while before booting it again, disk work needs it off throughout const notBusy = (name: string) => { const work = diskWork.get(name) - if (work) throw new Error(`${name} is ${work}. Wait for it to finish.`) + if (work) throw new Error(`${name} is ${diskWorkText[work]}. Wait for it to finish.`) if (profiles.isBusy(name)) throw new Error(`${name} is busy with a profile. Wait for it to finish.`) } ipcMain.handle('clone', async (_e, name: string, newName: unknown, linked: unknown) => { if (typeof newName !== 'string') throw new Error('Name is required') - return withDiskWork(name, 'being cloned', async () => { + return withDiskWork(name, 'cloning', async () => { const copy = await cloneVm(runner, paths, byName(name), newName, linked === true, listConfigs(paths)) return saveConfig(paths, copy) }) @@ -172,7 +182,7 @@ export function registerIpc(ctx: IpcContext): Backend { return { exists: true, virtualBytes: info.virtualBytes, actualBytes: info.actualBytes, backingFile: info.backingFile, snapshotCount: info.snapshots.length } }) ipcMain.handle('resizeDisk', (_e, name: string, sizeGB: unknown) => - withDiskWork(name, 'getting a bigger disk', async () => { + withDiskWork(name, 'growing', async () => { const cfg = byName(name) const size = Number(sizeGB) await resizeDisk(runner, cfg, size) @@ -180,7 +190,7 @@ export function registerIpc(ctx: IpcContext): Backend { saveConfig(paths, { ...cfg, diskSizeGB: size }, cfg.name) }) ) - ipcMain.handle('compactDisk', (_e, name: string) => withDiskWork(name, 'having its disk compacted', () => compactDisk(runner, byName(name)))) + ipcMain.handle('compactDisk', (_e, name: string) => withDiskWork(name, 'compacting', () => compactDisk(runner, byName(name)))) ipcMain.handle('remove', (_e, name: string) => { byName(name) // only a real VM, the name ends up in file paths @@ -290,7 +300,7 @@ export function registerIpc(ctx: IpcContext): Backend { }) ipcMain.handle('states', () => runner.allStates()) - ipcMain.handle('profileWork', () => profiles.work()) + ipcMain.handle('vmWork', (): Record => ({ ...profiles.work(), ...Object.fromEntries(diskWork) })) // the Summary tab's live screen ipcMain.handle('preview', async (_e, name: string): Promise => { diff --git a/src/preload/index.ts b/src/preload/index.ts index 7adde1a..8df1b85 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -29,7 +29,7 @@ const api: VmmApi = { autostart: () => ipcRenderer.invoke('autostart'), power: (name, action) => ipcRenderer.invoke('power', name, action), states: () => ipcRenderer.invoke('states'), - profileWork: () => ipcRenderer.invoke('profileWork'), + vmWork: () => ipcRenderer.invoke('vmWork'), saveState: (name) => ipcRenderer.invoke('saveState', name), hasSaveState: (name) => ipcRenderer.invoke('hasSaveState', name), discardSaveState: (name) => ipcRenderer.invoke('discardSaveState', name), @@ -50,7 +50,7 @@ const api: VmmApi = { readLog: (name) => ipcRenderer.invoke('readLog', name), onState: (cb) => listen('vm:state', cb), onCrash: (cb) => listen('vm:crash', cb), - onProfileWork: (cb) => listen('vm:profileWork', cb), + onVmWork: (cb) => listen('vm:work', cb), onUsage: (cb) => listen('vm:usage', cb), onHostChanged: (cb) => listen('host:changed', () => cb()) } diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index e2db3ec..16c9ce4 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { flushSync } from 'react-dom' import type { VmConfig } from '@shared/config' -import type { HostInfo, PowerAction, ProfileWork, VmRuntimeState, VmStatus, VmUsage } from '@shared/ipc' +import type { HostInfo, PowerAction, VmRuntimeState, VmStatus, VmUsage, VmWork } from '@shared/ipc' import Sidebar from './components/Sidebar' import Toolbar from './components/Toolbar' import VmDetail from './components/VmDetail' @@ -28,8 +28,8 @@ export default function App() { const [unsaved, setUnsaved] = useState(false) // VMs that are hibernating: still running for a few seconds, but saving again would fail const [hibernating, setHibernating] = useState>(new Set()) - // profile saves, launches and deletes, also the ones the Profiles tab of another VM started - const [profileWork, setProfileWork] = useState>({}) + // profile saves, launches and deletes and disk work, also the ones started from another VM's tabs + const [vmWork, setVmWork] = useState>({}) const [setupFor, setSetupFor] = useState<{ vm: VmConfig; reason: string } | null>(null) const [dragging, setDragging] = useState(false) const dragDepth = useRef(0) // dragenter/dragleave fire for every child, count them @@ -55,9 +55,9 @@ export default function App() { if (s.status === 'off') setUsage(({ [s.name]: _gone, ...rest }) => rest) if (s.status === 'off') setHibernating((cur) => (cur.has(s.name) ? new Set([...cur].filter((n) => n !== s.name)) : cur)) }) - window.vmm.profileWork().then(setProfileWork) - const offWork = window.vmm.onProfileWork(({ name, work }) => - setProfileWork(({ [name]: _done, ...rest }) => (work ? { ...rest, [name]: work } : rest)) + window.vmm.vmWork().then(setVmWork) + const offWork = window.vmm.onVmWork(({ name, work }) => + setVmWork(({ [name]: _done, ...rest }) => (work ? { ...rest, [name]: work } : rest)) ) const offCrash = window.vmm.onCrash((c) => toasts.push('error', `${c.name} failed to start`, c.message)) // an ISO was added to or removed from the ISOs folder @@ -92,7 +92,7 @@ export default function App() { const current = useMemo(() => vms.find((v) => v.name === selected) ?? null, [vms, selected]) const status: VmStatus = current ? states[current.name] ?? 'off' : 'off' - const work = current && profileWork[current.name] ? workLabel[profileWork[current.name]] : null + const work = current && vmWork[current.name] ? workLabel[vmWork[current.name]] : null const latestUsage = useMemo(() => Object.fromEntries(Object.entries(usage).map(([n, h]) => [n, h[h.length - 1]])), [usage]) const guard = async (fn: () => Promise, failTitle: string) => { @@ -204,7 +204,7 @@ export default function App() { // ---- keyboard shortcuts ---- // the listener is added once and reads the latest values from here - // a profile operation refuses Power on, Resume and Delete just like busy + // a profile operation or disk work refuses Power on, Resume and Delete just like busy const held = busy || work !== null const keys = useRef({ current, status, busy: held, vms, query, onStart, onDelete, onNew }) keys.current = { current, status, busy: held, vms, query, onStart, onDelete, onNew } diff --git a/src/renderer/src/mockApi.ts b/src/renderer/src/mockApi.ts index 626e5d8..fa48434 100644 --- a/src/renderer/src/mockApi.ts +++ b/src/renderer/src/mockApi.ts @@ -1,7 +1,7 @@ // Fake backend so the UI can run in a normal browser (npm run dev:web). // Handy for working on layout without booting real VMs. import { defaultConfig, type VmConfig } from '@shared/config' -import type { AppSettings, Profile, ProfileWork, VmmApi, VmRuntimeState, VmUsage } from '@shared/ipc' +import type { AppSettings, Profile, VmmApi, VmRuntimeState, VmUsage, VmWork } from '@shared/ipc' // a gray "desktop" so the preview and profile thumbnails have something to show function fakeScreen(label: string): string { @@ -34,16 +34,25 @@ export function installMockApi(): void { const running = (name: string) => (states[name]?.status ?? 'off') !== 'off' // the first live save of each VM pretends the guest agent is missing, so the setup dialog can be tried const agentReady = new Set() - // VMs in the middle of a live profile save, the toolbar is refused like the real backend does - const profileBusy = new Map() - const workListeners = new Set<(w: { name: string; work: ProfileWork | null }) => void>() - const setWork = (name: string, work: ProfileWork | null) => { - if (work) profileBusy.set(name, work) - else profileBusy.delete(name) + // VMs in the middle of a live profile save or disk work, the toolbar is refused like the real backend does + const busy = new Map() + const workListeners = new Set<(w: { name: string; work: VmWork | null }) => void>() + const setWork = (name: string, work: VmWork | null) => { + if (work) busy.set(name, work) + else busy.delete(name) workListeners.forEach((cb) => cb({ name, work })) } const notBusy = (name: string) => { - if (profileBusy.has(name)) throw new Error(`${name} is busy with a profile. Wait for it to finish.`) + if (busy.has(name)) throw new Error(`${name} is busy. Wait for it to finish.`) + } + const withWork = async (name: string, work: VmWork, fn: () => Promise): Promise => { + notBusy(name) + setWork(name, work) + try { + return await fn() + } finally { + setWork(name, null) + } } const isos = ['C:\\Users\\you\\VMs\\ISOs\\kali-linux-2026.2-installer-amd64.iso', 'C:\\Users\\you\\VMs\\ISOs\\Parrot-home-7.3_amd64.iso'] @@ -78,6 +87,7 @@ export function installMockApi(): void { }, autostart: async () => [], start: async (name, opts) => { + notBusy(name) const resumed = Boolean(opts?.resume && saved.delete(name)) emit({ name, status: 'starting', pid: 1234, startedAt: Date.now() }) later(900, () => emit({ name, status: 'running', pid: 1234, startedAt: Date.now() })) @@ -92,7 +102,7 @@ export function installMockApi(): void { if (action === 'kill' || action === 'shutdown') later(400, () => emit({ name, status: 'off', pid: null, startedAt: null })) }, states: async () => Object.values(states), - profileWork: async () => Object.fromEntries(profileBusy), + vmWork: async () => Object.fromEntries(busy), saveState: async (name) => { notBusy(name) // the mock pretends to be WHPX: the guest hibernates and powers off by itself @@ -143,33 +153,38 @@ export function installMockApi(): void { guestSetupCommand: async () => 'curl -sL 10.0.2.2:7777/s | sudo bash', // a browser doesn't hand out real paths, pretend the file came from Downloads pathForFile: (file) => `C:\\Users\\you\\Downloads\\${file.name}`, - clone: async (name, newName, linked) => { - await new Promise((r) => setTimeout(r, linked ? 300 : 1500)) // a full copy takes a while - const src = vms.find((v) => v.name === name) - if (!src) throw new Error(`No VM called "${name}"`) - if (running(name)) throw new Error(`Power off ${name} before you clone it.`) - const n = newName.trim() - if (vms.some((v) => v.name.toLowerCase() === n.toLowerCase())) throw new Error(`A VM called "${n}" already exists`) - const copy = { ...src, name: n, diskPath: `${disks}\\${n}.qcow2`, autostart: false, resumeLast: false } - vms = [...vms, copy] - return copy - }, + clone: (name, newName, linked) => + withWork(name, 'cloning', async () => { + await new Promise((r) => setTimeout(r, linked ? 300 : 1500)) // a full copy takes a while + const src = vms.find((v) => v.name === name) + if (!src) throw new Error(`No VM called "${name}"`) + if (running(name)) throw new Error(`Power off ${name} before you clone it.`) + const n = newName.trim() + if (vms.some((v) => v.name.toLowerCase() === n.toLowerCase())) throw new Error(`A VM called "${n}" already exists`) + const copy = { ...src, name: n, diskPath: `${disks}\\${n}.qcow2`, autostart: false, resumeLast: false } + vms = [...vms, copy] + return copy + }), diskInfo: async (name) => { const v = vms.find((x) => x.name === name) const size = (v?.diskSizeGB ?? 64) * 1024 ** 3 return { exists: true, virtualBytes: size, actualBytes: Math.round(size * 0.31), backingFile: null, snapshotCount: profiles[name]?.length ?? 0 } }, - resizeDisk: async (name, sizeGB) => { - if (running(name)) throw new Error(`Power off ${name} before you resize its disk.`) - const v = vms.find((x) => x.name === name) - if (v && sizeGB < v.diskSizeGB) throw new Error(`The disk is already ${v.diskSizeGB} GB. It can only grow.`) - vms = vms.map((x) => (x.name === name ? { ...x, diskSizeGB: sizeGB } : x)) - }, - compactDisk: async (name) => { - if (running(name)) throw new Error(`Power off ${name} before you compact its disk.`) - await new Promise((r) => setTimeout(r, 1200)) - return { before: 31 * 1024 ** 3, after: 22 * 1024 ** 3 } - }, + resizeDisk: (name, sizeGB) => + withWork(name, 'growing', async () => { + if (running(name)) throw new Error(`Power off ${name} before you resize its disk.`) + const v = vms.find((x) => x.name === name) + if (v && sizeGB < v.diskSizeGB) throw new Error(`The disk is already ${v.diskSizeGB} GB. It can only grow.`) + await new Promise((r) => setTimeout(r, 800)) + vms = vms.map((x) => (x.name === name ? { ...x, diskSizeGB: sizeGB } : x)) + }), + // long enough to look at the toolbar while it runs + compactDisk: (name) => + withWork(name, 'compacting', async () => { + if (running(name)) throw new Error(`Power off ${name} before you compact its disk.`) + await new Promise((r) => setTimeout(r, 4000)) + return { before: 31 * 1024 ** 3, after: 22 * 1024 ** 3 } + }), // a browser has no file picker that hands out paths pickFile: async () => null, pickFolder: async () => null, @@ -198,7 +213,7 @@ export function installMockApi(): void { return () => stateListeners.delete(cb) }, onCrash: () => () => undefined, - onProfileWork: (cb) => { + onVmWork: (cb) => { workListeners.add(cb) return () => workListeners.delete(cb) }, diff --git a/src/renderer/src/util.ts b/src/renderer/src/util.ts index 84c4370..3536196 100644 --- a/src/renderer/src/util.ts +++ b/src/renderer/src/util.ts @@ -1,3 +1,5 @@ +import type { VmWork } from '@shared/ipc' + /** Electron wraps errors from ipcMain.handle, strip that so users see the real message. */ export const errText = (e: unknown) => String(e instanceof Error ? e.message : e).replace(/^Error invoking remote method '[^']+': (Error: )?/, '') @@ -26,12 +28,15 @@ export const statusLabel = { paused: 'Paused' } as const -/** shown instead of the status while a profile operation runs */ +/** shown instead of the status while a profile operation or disk work runs */ export const workLabel = { saving: 'Saving profile', launching: 'Launching profile', - removing: 'Deleting profile' -} as const + removing: 'Deleting profile', + cloning: 'Cloning', + compacting: 'Compacting disk', + growing: 'Growing disk' +} as const satisfies Record export const when = (ms: number) => new Date(ms).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts index 365b8b2..43ba8f6 100644 --- a/src/shared/ipc.ts +++ b/src/shared/ipc.ts @@ -11,6 +11,10 @@ export interface VmRuntimeState { /** a profile operation running on a VM. Everything but Force off waits for it */ export type ProfileWork = 'saving' | 'launching' | 'removing' +/** a clone, compact or grow working on a VM's disk. Nothing may start or change the VM meanwhile */ +export type DiskWork = 'cloning' | 'compacting' | 'growing' +/** anything long running on a VM that the toolbar has to wait for */ +export type VmWork = ProfileWork | DiskWork export interface HostInfo { /** this app's version, from package.json */ @@ -109,8 +113,8 @@ export interface VmmApi { autostart(): Promise power(name: string, action: PowerAction): Promise states(): Promise - /** VMs with a profile save, launch or delete running, by name */ - profileWork(): Promise> + /** VMs with a profile operation or disk work running, by name */ + vmWork(): Promise> saveState(name: string): Promise hasSaveState(name: string): Promise discardSaveState(name: string): Promise @@ -158,8 +162,8 @@ export interface VmmApi { readLog(name: string): Promise onState(cb: (s: VmRuntimeState) => void): () => void onCrash(cb: (c: { name: string; message: string }) => void): () => void - /** a VM started (work) or finished (null) a profile operation */ - onProfileWork(cb: (w: { name: string; work: ProfileWork | null }) => void): () => void + /** a VM started (work) or finished (null) a profile operation or disk work */ + onVmWork(cb: (w: { name: string; work: VmWork | null }) => void): () => void /** every 2 s while VMs run: CPU and memory of each running VM, by name */ onUsage(cb: (u: Record) => void): () => void /** something in host() changed, for now the list of ISOs */