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
8 changes: 4 additions & 4 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 { workText, type AppSettings, type AutostartIssue, type DiskInfo, type DiskWork, type HostInfo, type PowerAction, type Profile, type SaveStateResult, type StartResult, type VmWork } from '@shared/ipc'
import { workText, type AppSettings, type AutostartIssue, type DiskInfo, type DiskWork, type HostInfo, type PowerAction, type Profile, type SaveStateResult, type StartResult, type VmWork, type VmWorkState } from '@shared/ipc'
import { agentHibernate } from './agent'
import { cloneVm, compactDisk, resizeDisk } from './disks'
import { runAutostart } from './autostart'
Expand Down Expand Up @@ -51,8 +51,8 @@ export function registerIpc(ctx: IpcContext): Backend {
const send = (channel: string, payload?: unknown) => getWindow()?.webContents.send(channel, payload)
// the renderer and the tray menu both follow which VMs have work running
const workListeners = new Set<() => void>()
const announceWork = (name: string, work: VmWork | null) => {
send('vm:work', { name, work })
const announceWork = (name: string, work: VmWork | null, tag?: string) => {
send('vm:work', { name, work, tag })
for (const cb of workListeners) cb()
}
const profiles = new Profiles(paths, runner, announceWork)
Expand Down Expand Up @@ -308,7 +308,7 @@ export function registerIpc(ctx: IpcContext): Backend {

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

// the Summary tab's live screen
ipcMain.handle('preview', async (_e, name: string): Promise<string | null> => {
Expand Down
19 changes: 14 additions & 5 deletions src/main/profiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,16 @@ function cleanLabel(label: string): string {
export class Profiles {
/** VMs with a take/launch/remove in flight */
private busy = new Map<string, ProfileWork>()
/** the profile a launch or delete is working on, so the Profiles tab can mark its row */
private tags = new Map<string, string>()
/** VMs with an edit in flight. Edits are quick, so a take/launch/remove waits for them instead of refusing */
private editing = new Map<string, Promise<void>>()

constructor(
private readonly paths: DataPaths,
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 readonly onWork: (vm: string, work: ProfileWork | null, tag?: string) => void = () => undefined
) {}

private dir(vm: string): string {
Expand All @@ -53,16 +55,18 @@ 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, work: ProfileWork, fn: () => Promise<T>): Promise<T> {
private async exclusive<T>(vm: string, work: ProfileWork, fn: () => Promise<T>, tag?: string): Promise<T> {
if (this.busy.has(vm)) throw new Error(`${vm} is still busy with another profile. Wait for it to finish.`)
this.busy.set(vm, work)
this.onWork(vm, work)
if (tag) this.tags.set(vm, tag)
this.onWork(vm, work, tag)
try {
// an edit that checked the profile exists could otherwise write its meta entry back after a remove
await this.editing.get(vm)?.catch(() => undefined)
return await fn()
} finally {
this.busy.delete(vm)
this.tags.delete(vm)
this.onWork(vm, null)
}
}
Expand All @@ -82,6 +86,11 @@ export class Profiles {
return Object.fromEntries(this.busy)
}

/** for a running launch or delete, the profile it works on, by VM */
workTags(): Record<string, string> {
return Object.fromEntries(this.tags)
}

private shotFile(vm: string, tag: string): string {
checkTag(tag)
return join(this.dir(vm), `${tag}.png`)
Expand Down Expand Up @@ -190,7 +199,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, 'launching', () => this.launchNow(cfg, tag, force))
return this.exclusive(cfg.name, 'launching', () => this.launchNow(cfg, tag, force), tag)
}

private async launchNow(cfg: VmConfig, tag: string, force: boolean): Promise<void> {
Expand Down Expand Up @@ -219,7 +228,7 @@ export class Profiles {
}

remove(cfg: VmConfig, tag: string): Promise<void> {
return this.exclusive(cfg.name, 'removing', () => this.removeNow(cfg, tag))
return this.exclusive(cfg.name, 'removing', () => this.removeNow(cfg, tag), tag)
}

private async removeNow(cfg: VmConfig, tag: string): Promise<void> {
Expand Down
18 changes: 14 additions & 4 deletions src/renderer/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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, workLabel } from './util'
import { errText, fileName, filterVms, isTyping, withSnapshot, workLabel } from './util'

const HISTORY = 60 // usage samples kept per VM, 2 s apart = two minutes

Expand All @@ -30,6 +30,8 @@ export default function App() {
const [hibernating, setHibernating] = useState<Set<string>>(new Set())
// profile saves, launches and deletes and disk work, also the ones started from another VM's tabs
const [vmWork, setVmWork] = useState<Record<string, VmWork>>({})
// for a profile launch or delete, which profile, so the Profiles tab can mark its row
const [workTags, setWorkTags] = useState<Record<string, string>>({})
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,10 +57,17 @@ 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.vmWork().then(setVmWork)
const offWork = window.vmm.onVmWork(({ name, work }) =>
// VMs a vm:work event has reported since. Those events are newer than the vmWork() answer
const reported = new Set<string>()
window.vmm.vmWork().then((w) => {

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.

The vmWork() answer replaces the whole map whenever it arrives. If a vm:work event comes in between the request and the answer (a launch ending right as the window loads), the answer is the older state and puts the finished work and its tag back. Nothing clears it until that VM's next work, so the tab stays disabled with a stale "Launching…". The snapshot should only fill in VMs no event has reported yet.

setVmWork((cur) => withSnapshot(cur, w.work, reported))
setWorkTags((cur) => withSnapshot(cur, w.tags, reported))
})
const offWork = window.vmm.onVmWork(({ name, work, tag }) => {
reported.add(name)
setVmWork(({ [name]: _done, ...rest }) => (work ? { ...rest, [name]: work } : rest))
)
setWorkTags(({ [name]: _done, ...rest }) => (work && tag ? { ...rest, [name]: tag } : 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 Down Expand Up @@ -326,6 +335,7 @@ export default function App() {
vm={current}
status={status}
work={current ? vmWork[current.name] ?? null : null}
workTag={current ? workTags[current.name] ?? null : null}
host={host}
usage={usage[current.name] ?? []}
onSave={onSave}
Expand Down
23 changes: 17 additions & 6 deletions src/renderer/src/components/Profiles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ interface Props {
* VM is selected and this one comes back, this isn't
*/
work: VmWork | null
/** for a launch or delete, which profile it is. Marks the right row after the tab was remounted */
workTag: string | null
toast: PushToast
/** the guest agent didn't answer, show the one-time setup */
onNeedsSetup: (reason: string) => void
Expand All @@ -24,7 +26,7 @@ const KIND: Record<Profile['kind'], string> = {
disk: 'disk only, boots fresh'
}

export default function Profiles({ vm, status, work, toast, onNeedsSetup }: Props) {
export default function Profiles({ vm, status, work, workTag, toast, onNeedsSetup }: Props) {
const [list, setList] = useState<Profile[] | null>(null)
const [label, setLabel] = useState('')
const [note, setNote] = useState('')
Expand Down Expand Up @@ -87,11 +89,19 @@ export default function Profiles({ vm, status, work, toast, onNeedsSetup }: Prop
}

const savingSession = busy === 'take'
// work this tab didn't start, or started before it was last unmounted. Which profile it is
// isn't known here, so the hint says what is going on and every button waits
// work this tab didn't start, or started before it was last unmounted. For a launch or delete
// the backend says which profile, so its row can show it. Every button waits either way
const otherWork = busy === null && work !== null
const workProfile = otherWork && workTag ? list?.find((p) => p.tag === workTag) : undefined
/** what is happening to this row's profile, whoever started it */
const rowWork = (p: Profile): 'launching' | 'removing' | null =>
busy === `l${p.tag}` || (otherWork && work === 'launching' && workTag === p.tag)
? 'launching'
: busy === `d${p.tag}` || (otherWork && work === 'removing' && workTag === p.tag)
? 'removing'
: null
const hint = otherWork
? `${workLabel[work]} on ${vm.name}. Wait for it to finish.`
? `${workLabel[work]}${workProfile ? ` "${workProfile.label}"` : ''} on ${vm.name}. Wait for it to finish.`
: status === 'running' || savingSession
? `Saves everything that's open in ${vm.name}. It closes for a moment while it saves, then comes right back. Launch the profile any time to return to exactly this point.`
: status === 'paused'
Expand Down Expand Up @@ -139,7 +149,7 @@ export default function Profiles({ vm, status, work, toast, onNeedsSetup }: Prop
) : (
<ul className="profile-list">
{list.map((p) => (
<li key={p.tag} className="profile-card">
<li key={p.tag} className="profile-card" aria-busy={rowWork(p) !== null}>
<Shot vm={vm.name} p={p} />
<div className="profile-info">
{editing === p.tag ? (
Expand All @@ -160,6 +170,7 @@ export default function Profiles({ vm, status, work, toast, onNeedsSetup }: Prop
{when(p.created)} · {KIND[p.kind]}
</span>
{p.note && <span className="profile-note">{p.note}</span>}
{rowWork(p) === 'removing' && <span className="muted">Deleting…</span>}
</>
)}
</div>
Expand All @@ -172,7 +183,7 @@ export default function Profiles({ vm, status, work, toast, onNeedsSetup }: Prop
onClick={() => launch(p)}
title="Go back to this profile and start it"
>
<Play size={13} /> {busy === `l${p.tag}` ? 'Launching…' : 'Launch'}
<Play size={13} /> {rowWork(p) === 'launching' ? 'Launching…' : 'Launch'}
</button>
<button className="icon-btn" aria-label={`Edit ${p.label}`} title="Rename or change the note" disabled={held} onClick={() => setEditing(p.tag)}>
<Pencil size={14} />
Expand Down
4 changes: 3 additions & 1 deletion src/renderer/src/components/VmDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ interface Props {
onDelete: (name: string) => void
/** a profile operation or disk work running on this VM, shown instead of the status */
work: VmWork | null
/** for a profile launch or delete, the tag of the profile */
workTag: string | null
onDirtyChange: (dirty: boolean) => void
toast: PushToast
onNeedsSetup: (reason: string) => void
Expand Down Expand Up @@ -121,7 +123,7 @@ export default function VmDetail(props: Props) {
onDiskChanged={props.onDiskChanged}
/>
)}
{tab === 'profiles' && <Profiles vm={vm} status={status} work={props.work} toast={props.toast} onNeedsSetup={props.onNeedsSetup} />}
{tab === 'profiles' && <Profiles vm={vm} status={status} work={props.work} workTag={props.workTag} toast={props.toast} onNeedsSetup={props.onNeedsSetup} />}
{tab === 'log' && <LogView name={vm.name} status={status} toast={props.toast} />}
</div>
</main>
Expand Down
54 changes: 37 additions & 17 deletions src/renderer/src/mockApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,21 @@ export function installMockApi(): void {
const agentReady = new Set<string>()
// 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) => {
const tags = new Map<string, string>()
const workListeners = new Set<(w: { name: string; work: VmWork | null; tag?: string }) => void>()
const setWork = (name: string, work: VmWork | null, tag?: string) => {
if (work) busy.set(name, work)
else busy.delete(name)
workListeners.forEach((cb) => cb({ name, work }))
if (work && tag) tags.set(name, tag)
else tags.delete(name)
workListeners.forEach((cb) => cb({ name, work, tag }))
}
const notBusy = (name: string) => {
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> => {
const withWork = async <T,>(name: string, work: VmWork, fn: () => Promise<T>, tag?: string): Promise<T> => {
notBusy(name)
setWork(name, work)
setWork(name, work, tag)
try {
return await fn()
} finally {
Expand Down Expand Up @@ -102,7 +105,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),
vmWork: async () => Object.fromEntries(busy),
vmWork: async () => ({ work: Object.fromEntries(busy), tags: Object.fromEntries(tags) }),
saveState: async (name) => {
notBusy(name)
// the mock pretends to be WHPX: the guest hibernates and powers off by itself
Expand Down Expand Up @@ -131,17 +134,34 @@ export function installMockApi(): void {
profiles[name] = [p, ...(profiles[name] ?? [])]
return p
},
launchProfile: async (name, _tag, force) => {
if (running(name) && !force) throw new Error('vm-running')
if (running(name)) {
emit({ name, status: 'off', pid: null, startedAt: null })
await new Promise((r) => setTimeout(r, 300))
}
await api.start(name)
},
deleteProfile: async (name, tag) => {
profiles[name] = (profiles[name] ?? []).filter((p) => p.tag !== tag)
},
launchProfile: (name, tag, force) =>
withWork(
name,
'launching',
async () => {
if (running(name) && !force) throw new Error('vm-running')
if (running(name)) {
emit({ name, status: 'off', pid: null, startedAt: null })
await new Promise((r) => setTimeout(r, 300))
}
// long enough to switch to another VM and back in dev:web
await new Promise((r) => setTimeout(r, 2500))
// not api.start, that refuses while the launch itself is the VM's work
emit({ name, status: 'starting', pid: 1234, startedAt: Date.now() })
later(900, () => emit({ name, status: 'running', pid: 1234, startedAt: Date.now() }))
},
tag
),
deleteProfile: (name, tag) =>
withWork(
name,
'removing',
async () => {
await new Promise((r) => setTimeout(r, 2500))
profiles[name] = (profiles[name] ?? []).filter((p) => p.tag !== tag)
},
tag
),
editProfile: async (name, tag, label, note) => {
// like the real one: refused during a profile save, launch or delete, fine during disk work
const w = busy.get(name)
Expand Down
11 changes: 11 additions & 0 deletions src/renderer/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,14 @@ export const bytes = (n: number) => {
if (n < 1024 ** 3) return `${(n / 1024 ** 2).toFixed(0)} MB`
return `${(n / 1024 ** 3).toFixed(1)} GB`
}

/**
* Applies a snapshot that was asked for before some events came in: VMs in `reported` keep what
* the events said, every other VM gets the snapshot's value (or nothing).
*/
export function withSnapshot<T>(cur: Record<string, T>, snapshot: Record<string, T>, reported: Set<string>): Record<string, T> {
const out: Record<string, T> = {}
for (const [name, v] of Object.entries(snapshot)) if (!reported.has(name)) out[name] = v
for (const name of reported) if (name in cur) out[name] = cur[name]
return out
}
14 changes: 11 additions & 3 deletions src/shared/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ export type DiskWork = 'cloning' | 'compacting' | 'growing'
/** anything long running on a VM that the toolbar has to wait for */
export type VmWork = ProfileWork | DiskWork

/** what vmWork() answers */
export interface VmWorkState {
/** VMs with a profile operation or disk work running, by name */
work: Record<string, VmWork>
/** for a profile launch or delete, the tag of the profile it works on, by VM name */
tags: Record<string, string>
}

/** shown instead of the status while a profile operation or disk work runs (toolbar, library, tray) */
export const workLabel = {
saving: 'Saving profile',
Expand Down Expand Up @@ -133,8 +141,8 @@ export interface VmmApi {
autostart(): Promise<AutostartIssue[]>
power(name: string, action: PowerAction): Promise<void>
states(): Promise<VmRuntimeState[]>
/** VMs with a profile operation or disk work running, by name */
vmWork(): Promise<Record<string, VmWork>>
/** VMs with a profile operation or disk work running, and for a launch or delete which profile */
vmWork(): Promise<VmWorkState>
saveState(name: string): Promise<SaveStateResult>
hasSaveState(name: string): Promise<boolean>
discardSaveState(name: string): Promise<void>
Expand Down Expand Up @@ -183,7 +191,7 @@ export interface VmmApi {
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 or disk work */
onVmWork(cb: (w: { name: string; work: VmWork | null }) => void): () => void
onVmWork(cb: (w: { name: string; work: VmWork | null; tag?: string }) => 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
27 changes: 26 additions & 1 deletion tests/profileSave.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,35 @@ describe('saving a session profile', () => {
const take = profiles.take(cfg, 'work', '')
expect(profiles.work()).toEqual({ [cfg.name]: 'saving' })
await take.catch(() => undefined)
// a save has no profile yet, so no tag goes with it
expect(onWork.mock.calls).toEqual([
[cfg.name, 'saving'],
[cfg.name, 'saving', undefined],
[cfg.name, null]
])
expect(profiles.work()).toEqual({})
expect(profiles.workTags()).toEqual({})
})
})

describe('profile work with a tag', () => {
it('says which profile a delete works on until it ends', async () => {
root = mkdtempSync(join(tmpdir(), 'vmm-prof-save-'))
const paths = dataPaths(root)
const cfg = defaultConfig('tag vm', paths.disks)
let release = () => undefined as void
const gate = new Promise<void>((r) => (release = r))
const runner = {
isRunning: () => false,
img: () => ({ snapshotDelete: async () => gate })
}
const onWork = vi.fn()
const profiles = new Profiles(paths, runner as unknown as VmRunner, onWork)
const remove = profiles.remove(cfg, 'p1')
expect(profiles.workTags()).toEqual({ [cfg.name]: 'p1' })
expect(onWork).toHaveBeenLastCalledWith(cfg.name, 'removing', 'p1')
release()
await remove
expect(profiles.workTags()).toEqual({})
expect(onWork).toHaveBeenLastCalledWith(cfg.name, null)
})
})
Loading
Loading