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
89 changes: 66 additions & 23 deletions src/main/quitFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ export interface QuitRunner {
resume(name: string): Promise<unknown>
shutdown(name: string): Promise<unknown>
waitForExit(name: string, timeoutMs: number): Promise<boolean>
/** 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. */
Expand Down Expand Up @@ -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<string>
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
Expand Down Expand Up @@ -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<void> {
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 {
Expand All @@ -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<boolean> {
private async workFirst(): Promise<Abandoned | false> {
const host = this.host
const work = Object.entries(host.vmWork())
host.show()
Expand All @@ -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 */
Expand All @@ -205,9 +233,10 @@ export class QuitFlow {
})
}

private async askAndQuit(fromClose: boolean): Promise<void> {
/** 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<boolean> {
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()
Expand All @@ -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<void> {
private async shutDownAllAndQuit(abandoned: Abandoned): Promise<void> {
const host = this.host
const runner = host.runner
const names = runner.runningNames()
Expand All @@ -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)

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 abandoned work keeps running in the main process; only the quit stops waiting for it. For a session profile save that matters: takeSession waits for the guest to power off and then calls runner.start(cfg) to boot it again. With the power button pressed mid-hibernate, the guest powers off (a plain shutdown reads as 'guest' too, see #120), waitForExit here returns true, and at about the same time the save snapshots the disk and starts the VM again. Then host.quit() runs and before-quit calls killAll(), so a guest that is just booting gets a hard power off. Before this PR the quit waited for the save, so that couldn't happen.

The save shouldn't be able to start the VM again once the quit has given up on it. Something like a per-VM hold on start that the quit sets for the abandoned VMs (and lifts if the user cancels the Force off question) would do it.

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)

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.

Letting go here is right, but by the time the Force off question gets its Cancel (at least a minute in), the abandoned save has usually already reached its start() and failed on the hold. So after Cancel the VM stays off and the save reports an error, even though the app didn't quit. That is the same "Cancel after the guests were already told to shut down" situation as #158, so it fits better there than in this PR.

host.quit()
}

Expand Down Expand Up @@ -303,6 +335,17 @@ export class QuitFlow {
}
}

private async pressPower(name: string): Promise<void> {
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<void> {
return new Promise((resolve) => {
Expand Down
12 changes: 12 additions & 0 deletions src/main/vmRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ export function isPortFree(port: number, proto: 'tcp' | 'udp' = 'tcp'): Promise<

export class VmRunner extends EventEmitter {
private running = new Map<string, Running>()
/** VMs that must not be started again, see holdStarts */
private held = new Set<string>()
/** how each VM's latest run ended, settles when its QEMU exits */
private exits = new Map<string, Promise<ExitKind>>()

Expand Down Expand Up @@ -157,6 +159,7 @@ export class VmRunner extends EventEmitter {

async start(cfg: VmConfig, opts: { loadState?: string } = {}): Promise<void> {
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)

Expand Down Expand Up @@ -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)
Expand Down
32 changes: 32 additions & 0 deletions tests/holdStarts.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
104 changes: 104 additions & 0 deletions tests/quitFlow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ class FakeRunner {
/** guests that ignore the power button, so waitForExit times out */
stuck = new Set<string>()
calls: string[] = []
/** VMs the flow has said must not be started again */
held = new Set<string>()

runningNames(): string[] {
return [...this.running]
Expand All @@ -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 */
Expand Down Expand Up @@ -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<typeof setup> = 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<typeof setup> = 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({
Expand Down
Loading