diff --git a/src/main/quitFlow.ts b/src/main/quitFlow.ts index e0783d8..c9a037f 100644 --- a/src/main/quitFlow.ts +++ b/src/main/quitFlow.ts @@ -26,6 +26,8 @@ export interface QuitRunner { resume(name: string): Promise shutdown(name: string): Promise waitForExit(name: string, timeoutMs: number): Promise + /** while held, the VM can't be started (by unfinished work the quit no longer waits for) */ + holdStarts(name: string, hold: boolean): void } /** What the quit flow needs from the app around it: the window, the tray and the dialogs. */ @@ -74,6 +76,10 @@ const FORCE = 'Force off and quit' const MORE = 'Wait another minute' const MINUTE = 60_000 +/** VMs whose work the user chose to leave unfinished. Quitting doesn't wait for theirs */ +type Abandoned = ReadonlySet +const NONE: Abandoned = new Set() + /** * Closing the window and quitting: the questions about running VMs and unfinished work, the * waiting that follows, and what the tray offers meanwhile. It keeps no Electron objects of its @@ -128,19 +134,21 @@ export class QuitFlow { if (this.shutting || this.endWorkWait) return // a question is already up: show it instead of a second copy, so the click isn't a no-op if (this.asking) return host.show() - if (this.hasWork() && !(await this.workFirst())) return + const abandoned = this.hasWork() ? await this.workFirst() : NONE + if (!abandoned) return if (host.runner.runningNames().length === 0) return host.quit() host.show() - await this.askAndQuit(false) + if (!(await this.askAndQuit(false, abandoned))) this.release(abandoned) } /** closing the window when it doesn't go to the tray */ private async quitFromClose(): Promise { const host = this.host - if (this.hasWork() && !(await this.workFirst())) return + const abandoned = this.hasWork() ? await this.workFirst() : NONE + if (!abandoned) return if (host.runner.runningNames().length === 0) return host.quit() - if (host.closeBehavior() === 'quit') return this.shutDownAllAndQuit() - await this.askAndQuit(true) + if (host.closeBehavior() === 'quit') return this.shutDownAllAndQuit(abandoned) + if (!(await this.askAndQuit(true, abandoned))) this.release(abandoned) } private hasWork(): boolean { @@ -160,9 +168,11 @@ export class QuitFlow { /** * Asked before quitting while a profile save or disk work runs, none of which survives the app - * quitting. True to go on with the quit (right away, or once the work has finished), false to stay. + * quitting. False to stay. Otherwise the quit goes on, right away or once the work has finished, + * and the result names the VMs whose work was left unfinished (Quit anyway, or Quit now in the + * tray), so the rest of the quit doesn't wait for it after all. */ - private async workFirst(): Promise { + private async workFirst(): Promise { const host = this.host const work = Object.entries(host.vmWork()) host.show() @@ -176,16 +186,34 @@ export class QuitFlow { defaultId: 0, noLink: true }) - if (choice === NOW) return true + // only the VMs the question named: work that started while it was up wasn't asked about + if (choice === NOW) return this.abandon(new Set(work.map(([n]) => n))) if (choice !== WAIT) return false // the work may have finished while the question was up - if (!this.hasWork()) return true + if (!this.hasWork()) return NONE host.toTray(false) host.balloon({ title: 'Quitting when the work is done', content: 'The app quits once it has finished. Right-click the tray icon to quit now or to stay.' }) - return this.allWorkDone() + const quit = await this.allWorkDone() + if (!quit) return false + // Quit now in the tray leaves whatever is still running unfinished + return this.abandon(new Set(Object.keys(host.vmWork()))) + } + + /** + * The quit no longer waits for these VMs' work, which keeps running until the app is gone. A + * session save boots the guest again at its end, only for the quit to kill it, so hold that off. + */ + private abandon(names: Abandoned): Abandoned { + for (const n of names) this.host.runner.holdStarts(n, true) + return names + } + + /** the quit didn't happen after all, the abandoned work may finish normally again */ + private release(names: Abandoned): void { + for (const n of names) this.host.runner.holdStarts(n, false) } /** resolves true once no VM has work running or Quit now was picked in the tray, false for Don't quit */ @@ -205,9 +233,10 @@ export class QuitFlow { }) } - private async askAndQuit(fromClose: boolean): Promise { + /** true once the app is on its way out (shutting down the VMs), false if it stays */ + private async askAndQuit(fromClose: boolean, abandoned: Abandoned): Promise { const host = this.host - if (this.shutting || this.asking) return + if (this.shutting || this.asking) return false // after Quit when it's done the window is in the tray host.show() const names = host.runner.runningNames() @@ -228,11 +257,16 @@ export class QuitFlow { if (checked && (choice === KEEP || choice === SHUT)) { host.rememberClose(choice === KEEP ? 'tray' : 'quit') } - if (choice === KEEP) return host.toTray() - if (choice === SHUT) return this.shutDownAllAndQuit() + if (choice === SHUT) { + // it lets go of the abandoned VMs itself if the quit is cancelled later on + await this.shutDownAllAndQuit(abandoned) + return true + } + if (choice === KEEP) host.toTray() + return false } - private async shutDownAllAndQuit(): Promise { + private async shutDownAllAndQuit(abandoned: Abandoned): Promise { const host = this.host const runner = host.runner const names = runner.runningNames() @@ -245,24 +279,22 @@ export class QuitFlow { content: `Waiting for ${names.length === 1 ? names[0] : `${names.length} VMs`} to shut down, then the app quits.` }) // a paused guest can't react to the power button, so let it run first. A VM in the middle of a - // profile save or delete gets the power button press once that's done, not while the guest hibernates + // profile save or delete gets the power button press once that's done, not while the guest + // hibernates. Unless the user already said to leave that work unfinished: then waiting for it + // only makes the quit look stuck, and a hibernate the power button turns into a shutdown is fine await Promise.all( names.map(async (n) => { + if (abandoned.has(n)) return this.pressPower(n) const saving = host.vmWork()[n] === 'saving' await this.workDone(n) if (!runner.isRunning(n)) return // a session save boots the VM again right before it ends, and the guest misses a power button // press while it's still resuming from hibernate. It has the agent, so wait for that to answer if (saving) await host.guestBack(n, 120_000) - try { - if (runner.state(n).status === 'paused') await runner.resume(n) - await runner.shutdown(n) - } catch { - // no QMP connection: it ends up in the force off question below - } + await this.pressPower(n) }) ) - if (!(await this.waitForShutdown(names))) return + if (!(await this.waitForShutdown(names))) return this.release(abandoned) host.quit() } @@ -303,6 +335,17 @@ export class QuitFlow { } } + private async pressPower(name: string): Promise { + const runner = this.host.runner + if (!runner.isRunning(name)) return + try { + if (runner.state(name).status === 'paused') await runner.resume(name) + await runner.shutdown(name) + } catch { + // no QMP connection: it ends up in the force off question + } + } + /** resolves once the VM has no profile operation or disk work running */ private workDone(name: string): Promise { return new Promise((resolve) => { diff --git a/src/main/vmRunner.ts b/src/main/vmRunner.ts index 6b72a75..f1882f5 100644 --- a/src/main/vmRunner.ts +++ b/src/main/vmRunner.ts @@ -100,6 +100,8 @@ export function isPortFree(port: number, proto: 'tcp' | 'udp' = 'tcp'): Promise< export class VmRunner extends EventEmitter { private running = new Map() + /** VMs that must not be started again, see holdStarts */ + private held = new Set() /** how each VM's latest run ended, settles when its QEMU exits */ private exits = new Map>() @@ -157,6 +159,7 @@ export class VmRunner extends EventEmitter { async start(cfg: VmConfig, opts: { loadState?: string } = {}): Promise { if (this.running.has(cfg.name)) throw new Error(`${cfg.name} is already running`) + if (this.held.has(cfg.name)) throw new Error(`${cfg.name} was not started again because the app is quitting.`) const qemu = this.qemu() if (!qemu) throw new Error(NO_QEMU) @@ -373,6 +376,15 @@ export class VmRunner extends EventEmitter { return r.agentPort } + /** + * While held, start() refuses the VM. Used when quitting leaves a profile save unfinished: + * the save boots the guest again at its end, which would only get a hard power off at the quit. + */ + holdStarts(name: string, hold: boolean): void { + if (hold) this.held.add(name) + else this.held.delete(name) + } + /** the guest is about to power itself off (hibernating), don't report that as a crash */ markExpectedExit(name: string, expected = true): void { const r = this.running.get(name) diff --git a/tests/holdStarts.test.ts b/tests/holdStarts.test.ts new file mode 100644 index 0000000..c8bd01b --- /dev/null +++ b/tests/holdStarts.test.ts @@ -0,0 +1,32 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, describe, expect, it } from 'vitest' +import { defaultConfig } from '@shared/config' +import { dataPaths } from '../src/main/paths' +import { VmRunner } from '../src/main/vmRunner' + +describe('VmRunner.holdStarts', () => { + const root = mkdtempSync(join(tmpdir(), 'vmm-hold-')) + afterAll(() => rmSync(root, { recursive: true, force: true })) + const paths = dataPaths(root) + // no QEMU: a start that gets past the hold fails on that instead, without booting anything + const runner = new VmRunner(paths, () => null) + const cfg = defaultConfig('held', paths.disks) + + it('refuses to start a held VM and says why', async () => { + runner.holdStarts('held', true) + await expect(runner.start(cfg)).rejects.toThrow('was not started again because the app is quitting') + }) + + it('starts it normally again once let go', async () => { + runner.holdStarts('held', false) + await expect(runner.start(cfg)).rejects.not.toThrow('app is quitting') + }) + + it('only holds the VM it was asked to', async () => { + runner.holdStarts('other', true) + await expect(runner.start(cfg)).rejects.not.toThrow('app is quitting') + runner.holdStarts('other', false) + }) +}) diff --git a/tests/quitFlow.test.ts b/tests/quitFlow.test.ts index 94aeddb..a6dc7bf 100644 --- a/tests/quitFlow.test.ts +++ b/tests/quitFlow.test.ts @@ -15,6 +15,8 @@ class FakeRunner { /** guests that ignore the power button, so waitForExit times out */ stuck = new Set() calls: string[] = [] + /** VMs the flow has said must not be started again */ + held = new Set() runningNames(): string[] { return [...this.running] @@ -37,6 +39,10 @@ class FakeRunner { this.calls.push(`wait:${name}`) return !this.running.has(name) } + holdStarts(name: string, hold: boolean): void { + if (hold) this.held.add(name) + else this.held.delete(name) + } } /** what the answer callback says: the button to click, and the checkbox if there is one */ @@ -282,6 +288,104 @@ describe('QuitFlow work in progress', () => { }) }) +describe('QuitFlow after Quit anyway', () => { + it('presses the power button right away on a VM whose work was abandoned', async () => { + const t = setup({ running: ['win11'], work: { win11: 'saving' }, answer: (q) => (q.title === 'Still working' ? NOW : SHUT) }) + await t.flow.requestQuit() + // the save is still going, and nothing waits for it + expect(t.titles()).toEqual(['Still working', 'VMs are still running']) + expect(t.log).not.toContain('guestBack:win11') + expect(t.runner.calls).toEqual(['shutdown:win11', 'wait:win11']) + expect(t.log).toContain('quit') + }) + + it('does the same when closing the window with the quit close behavior', async () => { + const t = setup({ running: ['win11'], work: { win11: 'compacting' }, closeBehavior: 'quit', answer: () => NOW }) + t.flow.onClose() + await settle() + expect(t.runner.calls).toEqual(['shutdown:win11', 'wait:win11']) + expect(t.log).toContain('quit') + }) + + it('still waits for work on another VM that started after the question', async () => { + const t: ReturnType = setup({ + running: ['win11', 'kali'], + work: { win11: 'saving' }, + answer: (q) => { + if (q.title === 'Still working') return NOW + t.setWork({ win11: 'saving', kali: 'removing' }) + return SHUT + } + }) + const quitting = t.flow.requestQuit() + await settle() + expect(t.runner.calls).toEqual(['shutdown:win11']) + t.setWork({ win11: 'saving' }) + await quitting + expect(t.runner.calls).toContain('shutdown:kali') + expect(t.log).toContain('quit') + }) + + it('keeps an abandoned save from starting the VM again during the quit', async () => { + const t = setup({ running: ['win11'], work: { win11: 'saving' }, answer: (q) => (q.title === 'Still working' ? NOW : SHUT) }) + await t.flow.requestQuit() + expect([...t.runner.held]).toEqual(['win11']) + }) + + it('lets go of the hold when the quit is cancelled', async () => { + const t = setup({ running: ['win11'], work: { win11: 'saving' }, answer: (q) => (q.title === 'Still working' ? NOW : 'Cancel') }) + await t.flow.requestQuit() + expect(t.log).not.toContain('quit') + expect([...t.runner.held]).toEqual([]) + }) + + it('lets go of the hold when the VMs are kept running in the tray', async () => { + const t = setup({ running: ['win11'], work: { win11: 'saving' }, answer: (q) => (q.title === 'Still working' ? NOW : KEEP) }) + t.flow.onClose() + await settle() + expect(t.log).toContain('toTray:true') + expect([...t.runner.held]).toEqual([]) + }) + + it('lets go of the hold on Cancel in the Force off question', async () => { + const t = setup({ running: ['win11'], work: { win11: 'saving' }, answer: (q) => (q.title === 'Still working' ? NOW : q.title === 'Still running' ? 'Cancel' : SHUT) }) + t.runner.stuck.add('win11') + await t.flow.requestQuit() + expect(t.titles()).toContain('Still running') + expect([...t.runner.held]).toEqual([]) + }) + + it('only counts the work the question named as abandoned', async () => { + const t: ReturnType = setup({ + running: ['win11', 'kali'], + work: { win11: 'saving' }, + answer: (q) => { + if (q.title !== 'Still working') return SHUT + // kali starts deleting a profile while the question is open + t.setWork({ win11: 'saving', kali: 'removing' }) + return NOW + } + }) + const quitting = t.flow.requestQuit() + await settle() + expect([...t.runner.held]).toEqual(['win11']) + expect(t.runner.calls).toEqual(['shutdown:win11']) + t.setWork({ win11: 'saving' }) + await quitting + expect(t.runner.calls).toContain('shutdown:kali') + }) + + it('treats Quit now in the tray like Quit anyway', async () => { + const t = setup({ running: ['win11'], work: { win11: 'compacting' }, answer: (q) => (q.title === 'Still working' ? WAIT : SHUT) }) + const quitting = t.flow.requestQuit() + await settle() + t.flow.endWait(true) + await quitting + expect(t.runner.calls).toEqual(['shutdown:win11', 'wait:win11']) + expect(t.log).toContain('quit') + }) +}) + describe('QuitFlow guests that do not shut down', () => { it('waits another minute and quits when the guest goes away', async () => { const t = setup({