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
5 changes: 3 additions & 2 deletions src/main/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down Expand Up @@ -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<string | null> => {
Expand Down
25 changes: 17 additions & 8 deletions src/main/profiles.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -34,11 +34,13 @@ function cleanLabel(label: string): string {
/** Profiles are internal qcow2 snapshots. Labels, notes and screenshots live next to them in profiles/<vm>/. */
export class Profiles {
/** VMs with a take/launch/remove in flight */
private busy = new Set<string>()
private busy = new Map<string, ProfileWork>()

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 {
Expand All @@ -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<T>(vm: string, fn: () => Promise<T>): Promise<T> {
private async exclusive<T>(vm: string, work: ProfileWork, fn: () => Promise<T>): Promise<T> {
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)
}
}

Expand All @@ -64,6 +68,11 @@ export class Profiles {
return this.busy.has(vm)
}

/** every VM with a profile operation running, and which one */
work(): Record<string, ProfileWork> {
return Object.fromEntries(this.busy)
}

private shotFile(vm: string, tag: string): string {
checkTag(tag)
return join(this.dir(vm), `${tag}.png`)
Expand Down Expand Up @@ -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<Profile> {
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())
Expand Down Expand Up @@ -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<void> {
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<void> {
Expand Down Expand Up @@ -201,7 +210,7 @@ export class Profiles {
}

remove(cfg: VmConfig, tag: string): Promise<void> {
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<void> {
Expand Down
2 changes: 2 additions & 0 deletions src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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())
}
Expand Down
20 changes: 16 additions & 4 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, 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'
Expand All @@ -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

Expand All @@ -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<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>>({})
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 @@ -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)

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.

Minor, no change needed: if a vm:profileWork event lands before this reply, the reply overwrites it. Same pattern as states() above it. The worst case is the toolbar staying enabled until the next event, which is what we had before this PR.

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) =>
Expand All @@ -76,6 +82,7 @@ export default function App() {
.catch((e) => toasts.push('error', 'Auto-start failed', errText(e)))
return () => {
offState()
offWork()
offCrash()
offHost()
offUsage()
Expand All @@ -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<unknown>, failTitle: string) => {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -296,6 +306,7 @@ export default function App() {
onSettings={() => setSettingsOpen(true)}
saving={Boolean(current && hibernating.has(current.name))}
saveHint={saveHint}
work={work}
/>
<div className="layout">
<Sidebar
Expand All @@ -315,6 +326,7 @@ export default function App() {
vm={current}
isDraft={false}
status={status}
work={work}
host={host}
usage={usage[current.name] ?? []}
onSave={onSave}
Expand Down
6 changes: 4 additions & 2 deletions src/renderer/src/components/Hardware.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ interface Props {
setForm: Dispatch<SetStateAction<VmConfig>>
host: HostInfo | null
locked: boolean
/** why the form is locked */
lockNotice: string
isDraft: boolean
dirty: boolean
nameError: string | null
Expand All @@ -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 extends keyof VmConfig>(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 (
<div className="hardware">
{locked && <div className="notice">Power off the VM to change its hardware.</div>}
{locked && <div className="notice">{lockNotice}</div>}
<fieldset disabled={locked}>
<Group title="General">
<Row label="Name" error={nameError}>
Expand Down
21 changes: 13 additions & 8 deletions src/renderer/src/components/Toolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,43 +16,48 @@ 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 (
<div className="toolbar" role="toolbar" aria-label="Virtual machine actions">
<button className="tb-btn" onClick={onNew} title="New virtual machine (Ctrl+N)" aria-keyshortcuts="Control+N">
<Plus size={ICON} /> New
</button>
<span className="tb-sep" />
{off || !vm ? (
<button className="tb-btn run" disabled={!vm || busy} onClick={onStart} title="Power on (Ctrl+Enter)" aria-keyshortcuts="Control+Enter">
<button className="tb-btn run" disabled={!vm || held} onClick={onStart} title={wait ?? 'Power on (Ctrl+Enter)'} aria-keyshortcuts="Control+Enter">
<Play size={ICON} /> Power on
</button>
) : status === 'paused' ? (
<button className="tb-btn run" disabled={busy} onClick={() => onPower('resume')} title="Resume (Ctrl+Enter)" aria-keyshortcuts="Control+Enter">
<button className="tb-btn run" disabled={held} onClick={() => onPower('resume')} title={wait ?? 'Resume (Ctrl+Enter)'} aria-keyshortcuts="Control+Enter">
<Play size={ICON} /> Resume
</button>
) : (
<button className="tb-btn" disabled={busy || status === 'starting'} onClick={() => onPower('pause')}>
<button className="tb-btn" disabled={held || status === 'starting'} onClick={() => onPower('pause')} title={wait}>
<Pause size={ICON} /> Suspend
</button>
)}
<button className="tb-btn" disabled={status !== 'running' || busy || saving} onClick={onSaveState} title={saving ? 'Saving, the VM turns off when it is done' : saveHint}>
<button className="tb-btn" disabled={status !== 'running' || held || saving} onClick={onSaveState} title={wait ?? (saving ? 'Saving, the VM turns off when it is done' : saveHint)}>
<Save size={ICON} /> Save state
</button>
<button className="tb-btn" disabled={!live || busy} onClick={() => onPower('reset')}>
<button className="tb-btn" disabled={!live || held} onClick={() => onPower('reset')} title={wait}>
<RotateCcw size={ICON} /> Restart
</button>
<button className="tb-btn" disabled={!live || busy} onClick={() => onPower('shutdown')} title="Asks the guest OS to shut down">
<button className="tb-btn" disabled={!live || held} onClick={() => onPower('shutdown')} title={wait ?? 'Asks the guest OS to shut down'}>
<Power size={ICON} /> Shut down
</button>
<span className="tb-sep" />
<button className="tb-btn" disabled={!vm || !off || busy} onClick={onClone} title={!vm ? undefined : off ? 'Make a copy of this VM' : 'Power off to clone'}>
<button className="tb-btn" disabled={!vm || !off || held} onClick={onClone} title={!vm ? undefined : wait ?? (off ? 'Make a copy of this VM' : 'Power off to clone')}>
<Copy size={ICON} /> Clone
</button>
<span className="tb-sep" />
Expand Down
15 changes: 11 additions & 4 deletions src/renderer/src/components/VmDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

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.

work gets as far as the status text, but the Hardware tab still uses locked={status !== 'off'} and canSave only checks status === 'off'. A disk-only profile save (VM off) or the off stretch of a launch leaves the form, Save, Ctrl+S and Delete enabled, and save / remove then fail with "busy with a profile". Lock them on work !== null too.

const [tab, setTab] = useState<Tab>(isDraft ? 'hardware' : 'summary')
const [form, setForm] = useState<VmConfig>(vm)
useEffect(() => setForm(vm), [vm])
Expand All @@ -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(() => {})
Expand All @@ -75,7 +79,9 @@ export default function VmDetail(props: Props) {
<OsMark os={form.os} large />
<div className="detail-title">
<h1>{form.name || 'Untitled'}</h1>
<span className={`state-text ${status}`}>{isDraft ? 'Not created yet' : statusLabel[status]}</span>
<span className={`state-text ${status}`} role="status">
{isDraft ? 'Not created yet' : work ?? statusLabel[status]}
</span>
</div>
</div>

Expand All @@ -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}
Expand Down
20 changes: 16 additions & 4 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, 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 {
Expand Down Expand Up @@ -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<string>()
// VMs in the middle of a live profile save, the toolbar is refused like the real backend does
const profileBusy = new Set<string>()
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)
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.`)
}
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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(() => {
Expand Down
Loading
Loading