Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 21 additions & 11 deletions src/main/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -38,14 +38,21 @@ export interface IpcContext {
relaunch: () => void
}

/** for the error when something is refused during disk work: "Kali is having its disk compacted" */
const diskWorkText: Record<DiskWork, string> = {
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
const qemu = () => findQemu(paths, ctx.getSettings().qemuPath)
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))
Expand Down Expand Up @@ -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<string, string>()
const withDiskWork = async <T>(name: string, what: string, fn: () => Promise<T>): Promise<T> => {
// meanwhile. The renderer is told too, so the toolbar can show it and disable what would be refused
const diskWork = new Map<string, DiskWork>()
const withDiskWork = async <T>(name: string, work: DiskWork, fn: () => Promise<T>): Promise<T> => {
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 })

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now sends vm:work before anything checked that name is a VM. All three callers only call byName(name) inside fn, so clone('nope', ...) broadcasts work for a VM that doesn't exist, then a null right after. The renderer survives it (it just adds and drops a key), but name comes straight from IPC and remove checks byName first for the same reason. Calling byName(name) at the top of withDiskWork would cover all three.

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)
})
Expand All @@ -172,15 +182,15 @@ 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)
// keep the config's size in step, it's what the Hardware tab and the next create use
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
Expand Down Expand Up @@ -290,7 +300,7 @@ export function registerIpc(ctx: IpcContext): Backend {
})

ipcMain.handle('states', () => runner.allStates())
ipcMain.handle('profileWork', () => profiles.work())
ipcMain.handle('vmWork', (): Record<string, VmWork> => ({ ...profiles.work(), ...Object.fromEntries(diskWork) }))

// the Summary tab's live screen
ipcMain.handle('preview', async (_e, name: string): Promise<string | null> => {
Expand Down
4 changes: 2 additions & 2 deletions src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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())
}
Expand Down
16 changes: 8 additions & 8 deletions src/renderer/src/App.tsx
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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<Set<string>>(new Set())
// profile saves, launches and deletes, also the ones the Profiles tab of another VM started
const [profileWork, setProfileWork] = useState<Record<string, ProfileWork>>({})
// profile saves, launches and deletes and disk work, also the ones started from another VM's tabs
const [vmWork, setVmWork] = useState<Record<string, VmWork>>({})
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
Expand All @@ -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
Expand Down Expand Up @@ -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<unknown>, failTitle: string) => {
Expand Down Expand Up @@ -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 }
Expand Down
79 changes: 47 additions & 32 deletions src/renderer/src/mockApi.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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<string>()
// VMs in the middle of a live profile save, the toolbar is refused like the real backend does
const profileBusy = new Map<string, ProfileWork>()
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<string, VmWork>()
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 <T,>(name: string, work: VmWork, fn: () => Promise<T>): Promise<T> => {
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']

Expand Down Expand Up @@ -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() }))
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
},
Expand Down
11 changes: 8 additions & 3 deletions src/renderer/src/util.ts
Original file line number Diff line number Diff line change
@@ -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: )?/, '')
Expand Down Expand Up @@ -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<VmWork, string>

export const when = (ms: number) =>
new Date(ms).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })
Expand Down
12 changes: 8 additions & 4 deletions src/shared/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down Expand Up @@ -109,8 +113,8 @@ export interface VmmApi {
autostart(): Promise<AutostartIssue[]>
power(name: string, action: PowerAction): Promise<void>
states(): Promise<VmRuntimeState[]>
/** VMs with a profile save, launch or delete running, by name */
profileWork(): Promise<Record<string, ProfileWork>>
/** VMs with a profile operation or disk work running, by name */
vmWork(): Promise<Record<string, VmWork>>
saveState(name: string): Promise<SaveStateResult>
hasSaveState(name: string): Promise<boolean>
discardSaveState(name: string): Promise<void>
Expand Down Expand Up @@ -158,8 +162,8 @@ export interface VmmApi {
readLog(name: string): Promise<string>
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<string, VmUsage>) => void): () => void
/** something in host() changed, for now the list of ISOs */
Expand Down
Loading