From 3b46c14c4548f8372fd2d462d12513ddb04399d6 Mon Sep 17 00:00:00 2001 From: Ari <149393150+A21-devs@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:16:21 -0500 Subject: [PATCH 1/4] Write a full clone under .vmm-clone and rename it when it's done A clone the app was quit in the middle of left a half-written .qcow2 in the disks folder with no VM using it, and nothing could tell it apart from a disk the user kept on purpose after deleting a VM. Writing it under a name no VM can use makes it recognisable as ours. Not .part: a browser downloading a disk image into that folder writes .qcow2.part, same reason the ISO copies use .vmm-copy. --- src/main/disks.ts | 49 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/src/main/disks.ts b/src/main/disks.ts index 91fdd4a..1731fc1 100644 --- a/src/main/disks.ts +++ b/src/main/disks.ts @@ -1,4 +1,4 @@ -import { chmodSync, existsSync, renameSync, rmSync } from 'node:fs' +import { chmodSync, existsSync, readdirSync, renameSync, rmSync } from 'node:fs' import { join } from 'node:path' import { validateVmName, type PortForward, type VmConfig } from '@shared/config' import type { DataPaths } from './paths' @@ -7,6 +7,41 @@ import { QUICKSAVE, type VmRunner } from './vmRunner' const GB = 1024 ** 3 +/** + * Suffixes of a disk this app is in the middle of writing. Neither is .part on purpose: a + * browser downloading a disk image into the disks folder writes .qcow2.part, and the + * startup cleanup must never touch another program's file. + */ +export const CLONE_SUFFIX = '.vmm-clone' +export const COMPACT_SUFFIX = '.compact.tmp' + +/** + * Deletes the clone and compact files the app was writing when it last stopped, so a Quit + * anyway in the middle of either doesn't leave a big file behind for good. Returns their names. + * + * Only files it knows it wrote: a disk in here with no VM may well be one the user kept on + * purpose, because deleting a VM leaves its disk. A disk the config points at outside this + * folder keeps its leftover until the next compact of that VM replaces it. + */ +export function removeUnfinishedDisks(disksDir: string): string[] { + let names: string[] + try { + names = readdirSync(disksDir) + } catch { + return [] // folder missing + } + return names.filter((f) => { + const l = f.toLowerCase() + if (!l.endsWith(`.qcow2${CLONE_SUFFIX}`) && !l.endsWith(`.qcow2${COMPACT_SUFFIX}`)) return false + try { + rmSync(join(disksDir, f)) + return true + } catch { + return false // in use or no permission: the next compact or clone overwrites it + } + }) +} + function needOff(runner: VmRunner, cfg: VmConfig, what: string): void { if (runner.isRunning(cfg.name)) throw new Error(`Power off ${cfg.name} before you ${what}.`) } @@ -36,7 +71,7 @@ export async function compactDisk(runner: VmRunner, cfg: VmConfig): Promise<{ be // convert doesn't copy internal snapshots, they would be gone afterwards if (info.snapshots.length > 0) throw new Error(`Compacting would throw away this VM's ${snapshotWord(info.snapshots)}. Delete them first if you really want to.`) if (info.backingFile) throw new Error('This disk is a linked clone. Compacting it would copy the whole base disk into it.') - const tmp = `${cfg.diskPath}.compact.tmp` + const tmp = `${cfg.diskPath}${COMPACT_SUFFIX}` rmSync(tmp, { force: true }) try { await img.convert(cfg.diskPath, tmp) @@ -90,11 +125,15 @@ export async function cloneVm( const img = runner.img() if (!linked) { - // convert doesn't copy internal snapshots, so the copy starts without the source's profiles + // written under a name no VM can use, so a copy the app is killed in the middle of is + // recognisable as ours and cleaned up at the next start instead of looking like a real disk + const part = `${target}${CLONE_SUFFIX}` + rmSync(part, { force: true }) try { - await img.convert(cfg.diskPath, target) + await img.convert(cfg.diskPath, part) + renameSync(part, target) } catch (e) { - rmSync(target, { force: true }) // don't leave a half-written disk that blocks the next try + rmSync(part, { force: true }) // don't leave a half-written disk that blocks the next try throw e } } else { From bac9faaa2edac7a60a22603deee3fe1f8e33a19f Mon Sep 17 00:00:00 2001 From: Ari <149393150+A21-devs@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:16:21 -0500 Subject: [PATCH 2/4] Remove unfinished clone and compact files at startup Quit anyway in the middle of a clone or a compact leaves a file as big as the disk behind. The app now clears them when it starts, the way it already clears unfinished ISO copies, and only the two names it writes itself. --- src/main/ipc.ts | 6 +++++- tests/clones.test.ts | 32 ++++++++++++++++++++++++++++++-- tests/integration/clones.test.ts | 4 +++- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 80b9427..05520d1 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -5,7 +5,7 @@ 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, type VmWorkState } from '@shared/ipc' import { agentHibernate } from './agent' -import { cloneVm, compactDisk, resizeDisk } from './disks' +import { cloneVm, compactDisk, removeUnfinishedDisks, resizeDisk } from './disks' import { runAutostart } from './autostart' import { GuestSetupServer } from './guestSetup' import { importIso, listIsos, removeUnfinishedCopies, watchFolder } from './isos' @@ -65,6 +65,10 @@ export function registerIpc(ctx: IpcContext): Backend { const leftovers = removeUnfinishedCopies(paths.isos) if (leftovers.length) console.log(`removed unfinished ISO copies: ${leftovers.join(', ')}`) + // the same for a clone or a compact the app was quit in the middle of, which can be tens of GB + const halfDisks = removeUnfinishedDisks(paths.disks) + if (halfDisks.length) console.log(`removed unfinished disk files: ${halfDisks.join(', ')}`) + // new or removed ISOs show up without restarting the app const stopIsoWatch = watchFolder(paths.isos, () => send('host:changed')) diff --git a/tests/clones.test.ts b/tests/clones.test.ts index 319a79a..702617f 100644 --- a/tests/clones.test.ts +++ b/tests/clones.test.ts @@ -1,6 +1,9 @@ -import { describe, expect, it } from 'vitest' +import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { defaultConfig, type PortForward } from '@shared/config' -import { shiftForwards } from '../src/main/disks' +import { CLONE_SUFFIX, COMPACT_SUFFIX, removeUnfinishedDisks, shiftForwards } from '../src/main/disks' import { suggestCloneName } from '../src/renderer/src/components/CloneDialog' const withFwd = (name: string, forwards: PortForward[]) => ({ ...defaultConfig(name, 'C:\\VMs\\disks'), forwards }) @@ -39,3 +42,28 @@ describe('suggestCloneName', () => { expect(suggestCloneName('Kali', ['Kali', 'kali COPY', 'Kali copy 2'])).toBe('Kali copy 3') }) }) + +describe('removeUnfinishedDisks', () => { + let dir: string + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'vmm-disks-')) + }) + afterEach(() => rmSync(dir, { recursive: true, force: true })) + + it('deletes the clone and compact files it was writing and leaves everything else', () => { + writeFileSync(join(dir, 'Kali.qcow2'), 'disk') + writeFileSync(join(dir, 'Kali.base-m1.qcow2'), 'base of a linked clone') + writeFileSync(join(dir, `Kali copy.qcow2${CLONE_SUFFIX}`), 'half a clone') + writeFileSync(join(dir, `KALI.QCOW2${COMPACT_SUFFIX.toUpperCase()}`), 'half a compact') + // a browser downloading a disk image writes this, and it may be in progress right now + writeFileSync(join(dir, 'debian.qcow2.part'), 'downloading') + // a disk the user kept after deleting its VM: no config points at it, it still stays + writeFileSync(join(dir, 'old-parrot.qcow2'), 'kept on purpose') + expect(removeUnfinishedDisks(dir).sort()).toEqual([`KALI.QCOW2${COMPACT_SUFFIX.toUpperCase()}`, `Kali copy.qcow2${CLONE_SUFFIX}`]) + expect(readdirSync(dir).sort()).toEqual(['Kali.base-m1.qcow2', 'Kali.qcow2', 'debian.qcow2.part', 'old-parrot.qcow2']) + }) + + it('copes with a missing folder', () => { + expect(removeUnfinishedDisks(join(dir, 'nope'))).toEqual([]) + }) +}) diff --git a/tests/integration/clones.test.ts b/tests/integration/clones.test.ts index f7d637c..07e3476 100644 --- a/tests/integration/clones.test.ts +++ b/tests/integration/clones.test.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { afterAll, describe, expect, it } from 'vitest' import { defaultConfig, type VmConfig } from '@shared/config' import type { VmRuntimeState } from '@shared/ipc' -import { cloneVm } from '../../src/main/disks' +import { CLONE_SUFFIX, cloneVm } from '../../src/main/disks' import { dataPaths, findQemu } from '../../src/main/paths' import { VmRunner } from '../../src/main/vmRunner' @@ -61,6 +61,8 @@ describe.skipIf(!qemu)('clones with real qemu-img', () => { const full = await cloneVm(runner, paths, src, 'clone full', false, [src, linked]) expect((await runner.img().info(full.diskPath)).backingFile).toBeNull() + // the copy is written under .vmm-clone and renamed, so nothing is left under that name + expect(existsSync(`${full.diskPath}${CLONE_SUFFIX}`)).toBe(false) // names are compared like Windows compares file names await expect(cloneVm(runner, paths, src, 'CLONE FULL', false, [src, linked, full])).rejects.toThrow(/already exists/) From fb759f4231f3f6f7ae50edfaf2f8e22f1288bb4f Mon Sep 17 00:00:00 2001 From: Ari <149393150+A21-devs@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:18:44 -0500 Subject: [PATCH 3/4] Don't let the tidy-up after a failed clone or compact hide the error qemu-img convert overwrites its output, so removing the file first was only a way to fail where the convert wouldn't: on Windows unlinking a file another process has open throws, and force: true only swallows ENOENT. The removals in the failure paths go through a helper that ignores its own errors, so the error the user sees is the one from qemu-img. The linked clone also says where the original disk is if putting it back fails, instead of throwing an unlink error over it. --- src/main/disks.ts | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/main/disks.ts b/src/main/disks.ts index 1731fc1..d5e5c37 100644 --- a/src/main/disks.ts +++ b/src/main/disks.ts @@ -46,6 +46,15 @@ function needOff(runner: VmRunner, cfg: VmConfig, what: string): void { if (runner.isRunning(cfg.name)) throw new Error(`Power off ${cfg.name} before you ${what}.`) } +/** tidy-up after a failure must never replace the error that caused it */ +function tryRemove(path: string): void { + try { + rmSync(path, { force: true }) + } catch { + // in use or no permission: leave it, the startup cleanup or the next write deals with it + } +} + /** "save state" when the only snapshot is the quick save, "profiles" otherwise */ const snapshotWord = (snaps: ImgSnapshot[]) => (snaps.every((s) => s.name === QUICKSAVE) ? 'save state' : 'profiles') @@ -72,14 +81,14 @@ export async function compactDisk(runner: VmRunner, cfg: VmConfig): Promise<{ be if (info.snapshots.length > 0) throw new Error(`Compacting would throw away this VM's ${snapshotWord(info.snapshots)}. Delete them first if you really want to.`) if (info.backingFile) throw new Error('This disk is a linked clone. Compacting it would copy the whole base disk into it.') const tmp = `${cfg.diskPath}${COMPACT_SUFFIX}` - rmSync(tmp, { force: true }) try { + // convert overwrites a leftover from a compact that was cut off await img.convert(cfg.diskPath, tmp) // one rename that replaces the disk. With two (disk -> .old, tmp -> disk) a crash in between // leaves no file at diskPath, and the next Power on would create a blank disk there renameSync(tmp, cfg.diskPath) } catch (e) { - rmSync(tmp, { force: true }) // the original is untouched + tryRemove(tmp) // the original is untouched throw e } return { before: info.actualBytes, after: (await img.info(cfg.diskPath)).actualBytes } @@ -128,12 +137,12 @@ export async function cloneVm( // written under a name no VM can use, so a copy the app is killed in the middle of is // recognisable as ours and cleaned up at the next start instead of looking like a real disk const part = `${target}${CLONE_SUFFIX}` - rmSync(part, { force: true }) try { + // convert overwrites a leftover from a clone that was cut off await img.convert(cfg.diskPath, part) renameSync(part, target) } catch (e) { - rmSync(part, { force: true }) // don't leave a half-written disk that blocks the next try + tryRemove(part) // don't leave a half-written disk that blocks the next try throw e } } else { @@ -148,9 +157,16 @@ export async function cloneVm( await img.createOverlay(cfg.diskPath, base) await img.createOverlay(target, base) } catch (e) { - rmSync(target, { force: true }) - rmSync(cfg.diskPath, { force: true }) - renameSync(base, cfg.diskPath) // put the original back + tryRemove(target) + tryRemove(cfg.diskPath) + try { + renameSync(base, cfg.diskPath) // put the original back + } catch { + // the overlay is still in the way: say where the disk went rather than hide it + throw new Error(`${(e as Error).message} + +The original disk is at ${base}. Move it back to ${cfg.diskPath} before starting ${cfg.name}.`) + } throw e } // the base must never change again or both overlays break From 8de6d8b37cf0057e6761dfb1514c84981aa0ea2a Mon Sep 17 00:00:00 2001 From: Ari <149393150+A21-devs@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:19:34 -0500 Subject: [PATCH 4/4] Say what was thrown without assuming it was an Error --- src/main/disks.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/disks.ts b/src/main/disks.ts index d5e5c37..dc8b0c5 100644 --- a/src/main/disks.ts +++ b/src/main/disks.ts @@ -163,7 +163,8 @@ export async function cloneVm( renameSync(base, cfg.diskPath) // put the original back } catch { // the overlay is still in the way: say where the disk went rather than hide it - throw new Error(`${(e as Error).message} + const why = e instanceof Error ? e.message : String(e) + throw new Error(`${why} The original disk is at ${base}. Move it back to ${cfg.diskPath} before starting ${cfg.name}.`) }