diff --git a/src/main/ipc.ts b/src/main/ipc.ts index b0a75ea..e37e60d 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -44,9 +44,9 @@ export function registerIpc(ctx: IpcContext): Backend { const qemu = () => findQemu(paths, ctx.getSettings().qemuPath) const runner = new VmRunner(paths, qemu) const guestSetup = new GuestSetupServer() - const profiles = new Profiles(paths, runner) - const send = (channel: string, payload?: unknown) => getWindow()?.webContents.send(channel, payload) + const profiles = new Profiles(paths, runner, (name, work) => send('vm:profileWork', { name, work })) + runner.on('state', (s) => send('vm:state', s)) runner.on('crash', (c) => send('vm:crash', c)) @@ -285,6 +285,7 @@ export function registerIpc(ctx: IpcContext): Backend { }) ipcMain.handle('states', () => runner.allStates()) + ipcMain.handle('profileWork', () => profiles.work()) // the Summary tab's live screen ipcMain.handle('preview', async (_e, name: string): Promise => { diff --git a/src/main/profiles.ts b/src/main/profiles.ts index d737ac1..a0cd7cc 100644 --- a/src/main/profiles.ts +++ b/src/main/profiles.ts @@ -1,7 +1,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import type { VmConfig } from '@shared/config' -import type { Profile } from '@shared/ipc' +import type { Profile, ProfileWork } from '@shared/ipc' import type { DataPaths } from './paths' import { agentHibernate } from './agent' import { QUICKSAVE, type VmRunner } from './vmRunner' @@ -34,11 +34,13 @@ function cleanLabel(label: string): string { /** Profiles are internal qcow2 snapshots. Labels, notes and screenshots live next to them in profiles//. */ export class Profiles { /** VMs with a take/launch/remove in flight */ - private busy = new Set() + private busy = new Map() constructor( private readonly paths: DataPaths, - private readonly runner: VmRunner + private readonly runner: VmRunner, + /** told when a VM starts or finishes a profile operation, so the toolbar can show it */ + private readonly onWork: (vm: string, work: ProfileWork | null) => void = () => undefined ) {} private dir(vm: string): string { @@ -49,13 +51,15 @@ export class Profiles { * One profile operation per VM at a time. A take waits minutes for the guest to hibernate, * and a launch or a second take during that would kill it or ask it to hibernate twice. */ - private async exclusive(vm: string, fn: () => Promise): Promise { + private async exclusive(vm: string, work: ProfileWork, fn: () => Promise): Promise { if (this.busy.has(vm)) throw new Error(`${vm} is still busy with another profile. Wait for it to finish.`) - this.busy.add(vm) + this.busy.set(vm, work) + this.onWork(vm, work) try { return await fn() } finally { this.busy.delete(vm) + this.onWork(vm, null) } } @@ -64,6 +68,11 @@ export class Profiles { return this.busy.has(vm) } + /** every VM with a profile operation running, and which one */ + work(): Record { + return Object.fromEntries(this.busy) + } + private shotFile(vm: string, tag: string): string { checkTag(tag) return join(this.dir(vm), `${tag}.png`) @@ -107,7 +116,7 @@ export class Profiles { * off gets a disk-only snapshot, which is quick and needs nothing from the guest. */ take(cfg: VmConfig, label: string, note: string): Promise { - return this.exclusive(cfg.name, async () => { + return this.exclusive(cfg.name, 'saving', async () => { const clean = cleanLabel(label) const status = this.runner.state(cfg.name).status if (status === 'off') return this.takeDisk(cfg, clean, note.trim()) @@ -172,7 +181,7 @@ export class Profiles { /** Rolls back to the profile and boots it. A session profile resumes everything that was open. */ launch(cfg: VmConfig, tag: string, force: boolean): Promise { - return this.exclusive(cfg.name, () => this.launchNow(cfg, tag, force)) + return this.exclusive(cfg.name, 'launching', () => this.launchNow(cfg, tag, force)) } private async launchNow(cfg: VmConfig, tag: string, force: boolean): Promise { @@ -201,7 +210,7 @@ export class Profiles { } remove(cfg: VmConfig, tag: string): Promise { - return this.exclusive(cfg.name, () => this.removeNow(cfg, tag)) + return this.exclusive(cfg.name, 'removing', () => this.removeNow(cfg, tag)) } private async removeNow(cfg: VmConfig, tag: string): Promise { diff --git a/src/preload/index.ts b/src/preload/index.ts index c9eb2d9..7adde1a 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -29,6 +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'), saveState: (name) => ipcRenderer.invoke('saveState', name), hasSaveState: (name) => ipcRenderer.invoke('hasSaveState', name), discardSaveState: (name) => ipcRenderer.invoke('discardSaveState', name), @@ -49,6 +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), 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 c5480f6..e2db3ec 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, VmRuntimeState, VmStatus, VmUsage } from '@shared/ipc' +import type { HostInfo, PowerAction, ProfileWork, VmRuntimeState, VmStatus, VmUsage } from '@shared/ipc' import Sidebar from './components/Sidebar' import Toolbar from './components/Toolbar' import VmDetail from './components/VmDetail' @@ -12,7 +12,7 @@ import Modal from './components/Modal' import CloneDialog from './components/CloneDialog' import Wizard from './components/Wizard' import Settings from './components/Settings' -import { errText, fileName, filterVms, isTyping } from './util' +import { errText, fileName, filterVms, isTyping, workLabel } from './util' const HISTORY = 60 // usage samples kept per VM, 2 s apart = two minutes @@ -28,6 +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>({}) 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 @@ -53,6 +55,10 @@ 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)) + ) 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 const offUsage = window.vmm.onUsage((u) => @@ -76,6 +82,7 @@ export default function App() { .catch((e) => toasts.push('error', 'Auto-start failed', errText(e))) return () => { offState() + offWork() offCrash() offHost() offUsage() @@ -85,6 +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 latestUsage = useMemo(() => Object.fromEntries(Object.entries(usage).map(([n, h]) => [n, h[h.length - 1]])), [usage]) const guard = async (fn: () => Promise, failTitle: string) => { @@ -196,8 +204,10 @@ export default function App() { // ---- keyboard shortcuts ---- // the listener is added once and reads the latest values from here - const keys = useRef({ current, status, busy, vms, query, onStart, onDelete, onNew }) - keys.current = { current, status, busy, vms, query, onStart, onDelete, onNew } + // a profile operation 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 } useEffect(() => { const onKey = (e: KeyboardEvent) => { // dialogs have their own keys (Esc, Enter in forms), and nothing behind them should react @@ -296,6 +306,7 @@ export default function App() { onSettings={() => setSettingsOpen(true)} saving={Boolean(current && hibernating.has(current.name))} saveHint={saveHint} + work={work} />
> host: HostInfo | null locked: boolean + /** why the form is locked */ + lockNotice: string isDraft: boolean dirty: boolean nameError: string | null @@ -28,14 +30,14 @@ interface Props { } export default function Hardware(props: Props) { - const { form, setForm, host, locked, isDraft, dirty, nameError, diskError, forwardsInvalid, onSave, onRevert, onDelete } = props + const { form, setForm, host, locked, lockNotice, isDraft, dirty, nameError, diskError, forwardsInvalid, onSave, onRevert, onDelete } = props const set = (k: K, v: VmConfig[K]) => setForm((f) => ({ ...f, [k]: v })) const maxRam = host ? Math.max(1024, Math.floor((host.totalRamMB - 2048) / 512) * 512) : 32768 const maxCpu = host?.cpuCount ?? 16 return (
- {locked &&
Power off the VM to change its hardware.
} + {locked &&
{lockNotice}
}
diff --git a/src/renderer/src/components/Toolbar.tsx b/src/renderer/src/components/Toolbar.tsx index 1f5b80c..2737f77 100644 --- a/src/renderer/src/components/Toolbar.tsx +++ b/src/renderer/src/components/Toolbar.tsx @@ -16,13 +16,18 @@ interface Props { saveHint: string /** the guest is hibernating, Save state was already sent */ saving: boolean + /** a profile operation runs on this VM (shown as the status). Everything but Force off waits */ + work: string | null } const ICON = 16 -export default function Toolbar({ vm, status, busy, onNew, onStart, onPower, onSaveState, onClone, onSettings, saveHint, saving }: Props) { +export default function Toolbar({ vm, status, busy, onNew, onStart, onPower, onSaveState, onClone, onSettings, saveHint, saving, work }: Props) { const off = status === 'off' const live = status === 'running' || status === 'paused' + // the backend refuses these until the profile operation is done, say why instead + const held = busy || work !== null + const wait = work ? `${work}. Wait for it to finish.` : undefined return (
{off || !vm ? ( - ) : status === 'paused' ? ( - ) : ( - )} - - - - diff --git a/src/renderer/src/components/VmDetail.tsx b/src/renderer/src/components/VmDetail.tsx index 2931ff1..382228e 100644 --- a/src/renderer/src/components/VmDetail.tsx +++ b/src/renderer/src/components/VmDetail.tsx @@ -21,6 +21,8 @@ interface Props { onSave: (cfg: VmConfig, previousName?: string) => void onCancelDraft: () => void onDelete: (name: string) => void + /** a profile operation running on this VM, shown instead of the status */ + work: string | null onDirtyChange: (dirty: boolean) => void toast: PushToast onNeedsSetup: (reason: string) => void @@ -37,7 +39,7 @@ const TABS: { id: Tab; label: string }[] = [ ] export default function VmDetail(props: Props) { - const { vm, isDraft, status, host, onSave, onCancelDraft, onDelete, onDirtyChange } = props + const { vm, isDraft, status, work, host, onSave, onCancelDraft, onDelete, onDirtyChange } = props const [tab, setTab] = useState(isDraft ? 'hardware' : 'summary') const [form, setForm] = useState(vm) useEffect(() => setForm(vm), [vm]) @@ -47,8 +49,10 @@ export default function VmDetail(props: Props) { const diskError = !Number.isInteger(form.diskSizeGB) || form.diskSizeGB < 5 || form.diskSizeGB > 16384 ? 'Pick a whole number from 5 to 16384 GB' : null const forwardsInvalid = form.forwards.some((_f, i) => forwardError(form.forwards, i) !== null) + // a profile operation can run while the VM is off (a disk-only save, a launch rolling back), save and delete wait for it + const locked = status !== 'off' || work !== null // same rule as the Save button on the Hardware tab - const canSave = dirty && !nameError && !diskError && !forwardsInvalid && status === 'off' + const canSave = dirty && !nameError && !diskError && !forwardsInvalid && !locked // Ctrl+S saves the hardware form from any tab const save = useRef(() => {}) @@ -75,7 +79,9 @@ export default function VmDetail(props: Props) {

{form.name || 'Untitled'}

- {isDraft ? 'Not created yet' : statusLabel[status]} + + {isDraft ? 'Not created yet' : work ?? statusLabel[status]} +
@@ -102,7 +108,8 @@ export default function VmDetail(props: Props) { form={form} setForm={setForm} host={host} - locked={status !== 'off'} + locked={locked} + lockNotice={work ? `${work}. Wait for it to finish.` : 'Power off the VM to change its hardware.'} isDraft={isDraft} dirty={dirty} nameError={nameError} diff --git a/src/renderer/src/mockApi.ts b/src/renderer/src/mockApi.ts index 7cdd138..d850fce 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, VmmApi, VmRuntimeState, VmUsage } from '@shared/ipc' +import type { AppSettings, Profile, ProfileWork, VmmApi, VmRuntimeState, VmUsage } from '@shared/ipc' // a gray "desktop" so the preview and profile thumbnails have something to show function fakeScreen(label: string): string { @@ -35,7 +35,13 @@ export function installMockApi(): void { // 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 Set() + 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) + 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.`) } @@ -85,6 +91,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), saveState: async (name) => { notBusy(name) // the mock pretends to be WHPX: the guest hibernates and powers off by itself @@ -106,8 +113,9 @@ export function installMockApi(): void { agentReady.add(name) throw new Error('needs-guest-setup: The guest agent is not answering.') } - profileBusy.add(name) - await new Promise((r) => setTimeout(r, 1500)).finally(() => profileBusy.delete(name)) + // long enough to look at the toolbar while it runs + setWork(name, 'saving') + await new Promise((r) => setTimeout(r, 4000)).finally(() => setWork(name, null)) const p: Profile = { tag: `p${Date.now().toString(36)}`, label: label.trim(), note: note.trim(), created: Date.now(), kind: 'session', hasShot: true } profiles[name] = [p, ...(profiles[name] ?? [])] return p @@ -189,6 +197,10 @@ export function installMockApi(): void { return () => stateListeners.delete(cb) }, onCrash: () => () => undefined, + onProfileWork: (cb) => { + workListeners.add(cb) + return () => workListeners.delete(cb) + }, onUsage: (cb) => { // made-up numbers that wobble a bit, so the UI has something to draw const t = setInterval(() => { diff --git a/src/renderer/src/util.ts b/src/renderer/src/util.ts index f256c54..84c4370 100644 --- a/src/renderer/src/util.ts +++ b/src/renderer/src/util.ts @@ -26,6 +26,13 @@ export const statusLabel = { paused: 'Paused' } as const +/** shown instead of the status while a profile operation runs */ +export const workLabel = { + saving: 'Saving profile', + launching: 'Launching profile', + removing: 'Deleting profile' +} as const + 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 e924e01..365b8b2 100644 --- a/src/shared/ipc.ts +++ b/src/shared/ipc.ts @@ -9,6 +9,9 @@ export interface VmRuntimeState { startedAt: number | null } +/** a profile operation running on a VM. Everything but Force off waits for it */ +export type ProfileWork = 'saving' | 'launching' | 'removing' + export interface HostInfo { /** this app's version, from package.json */ appVersion: string @@ -106,6 +109,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> saveState(name: string): Promise hasSaveState(name: string): Promise discardSaveState(name: string): Promise @@ -153,6 +158,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 /** 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 */ diff --git a/tests/profileSave.test.ts b/tests/profileSave.test.ts index 7dee2d7..654514f 100644 --- a/tests/profileSave.test.ts +++ b/tests/profileSave.test.ts @@ -28,7 +28,8 @@ function setup(how: ExitKind | 'timeout') { img: () => ({ snapshotCreate }), start: vi.fn(async () => undefined) } - return { cfg, paths, runner, snapshotCreate, profiles: new Profiles(paths, runner as unknown as VmRunner) } + const onWork = vi.fn() + return { cfg, paths, runner, snapshotCreate, onWork, profiles: new Profiles(paths, runner as unknown as VmRunner, onWork) } } describe('saving a session profile', () => { @@ -56,4 +57,16 @@ describe('saving a session profile', () => { expect(snapshotCreate).not.toHaveBeenCalled() expect(runner.markExpectedExit).toHaveBeenLastCalledWith(cfg.name, false) }) + + it('reports the save as running until it ends, also when it fails', async () => { + const { cfg, profiles, onWork } = setup('host') + const take = profiles.take(cfg, 'work', '') + expect(profiles.work()).toEqual({ [cfg.name]: 'saving' }) + await take.catch(() => undefined) + expect(onWork.mock.calls).toEqual([ + [cfg.name, 'saving'], + [cfg.name, null] + ]) + expect(profiles.work()).toEqual({}) + }) })