Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
Let an app that uninstalls itself go while its own service runs
Țugui Dragoș6b7e70e2d506
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 2a09a02a..f9e7115c 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -96,10 +96,12 @@ Take the most common case, uninstalling an app. Every other page follows the samlinks an app's tools and their shell completions left in `/usr/local` go last, once the app they lead intohas moved. Before any of it, the app has to quit, and Peel offers Force Quit when it doesn't(`QuitBeforeRemoving`). An item stays where it is while a program holds it (`OpenFiles`): a file one of the- user's programs holds open, or the program any process runs from it, though inside an app, which is code- and loses nothing when it moves, a file open only for reading holds nothing. The app's privacy permissions- are reset, when that was chosen, just before the move and only once the checks the move makes first (the- guard, History, and the programs holding it) say it will go (`PrivacyReset`).+ user's programs holds open, or the program any process runs from it, though inside an app, which is code and+ loses nothing when it moves, a file open only for reading holds nothing. Nor does the program running from an+ app that uninstalls itself once it has moved (`UninstallsItself`, Mullvad VPN's daemon), and what that+ uninstaller removes is held back (`leftToItsUninstaller`) rather than moved first. The app's privacy+ permissions are reset, when that was chosen, just before the move and only once the checks the move makes+ first (the guard, History, and the programs holding it) say it will go (`PrivacyReset`).6. **Finish.** Only for what really moved: the launch jobs whose files went are stopped, macOS is told toforget the preference domains whose files went, and an uninstalled app's Dock icon comes out(`DockTiles`).diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex 98bfca16..7956040a 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -65158,6 +65158,112 @@}}},+ "Left alone: the app’s own uninstaller removes this once the app is in the Trash, and History can’t bring it back." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nedotčeno: tuto položku odstraní vlastní odinstalátor aplikace, jakmile bude aplikace v koši, a Historie ji nemůže vrátit."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Unangetastet: Das eigene Deinstallationsprogramm der App entfernt dies, sobald die App im Papierkorb liegt, und über den Verlauf lässt sich das nicht zurückholen."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "No se toca: el propio desinstalador de la app elimina esto cuando la app ya está en la papelera, e Historial no puede recuperarlo."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Laissé en place : le programme de désinstallation propre à l’app le supprime une fois l’app dans la corbeille, et l’Historique ne peut pas le rétablir."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Resta dov’è: il programma di disinstallazione dell’app stessa lo rimuove quando l’app è nel Cestino, e la Cronologia non può ripristinarlo."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "対象外: アプリがゴミ箱に入ると、アプリ独自のアンインストーラによってこれが削除され、履歴から元に戻すことはできません。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "그대로 둠: 앱이 휴지통으로 이동되면 앱 자체의 제거 프로그램이 이 항목을 제거하며, 기록에서 되살릴 수 없습니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Blijft staan: het eigen de-installatieprogramma van de app verwijdert dit definitief zodra de app in de prullenmand ligt, en Geschiedenis kan het niet terugzetten."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nietknięte: własny dezinstalator aplikacji usunie to, gdy aplikacja trafi do Kosza, a Historia nie może tego przywrócić."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Preservado: o desinstalador do próprio app remove isto assim que o app estiver no Lixo, e o Histórico não pode trazê-lo de volta."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Lăsat neatins: după ce aplicația ajunge în Coș, programul ei propriu de dezinstalare elimină acest articol, care nu poate fi readus din Istoric."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Остается на месте: собственная программа удаления приложения удалит это, как только приложение окажется в Корзине, и История не сможет это вернуть."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Rörs inte: appens egen avinstallerare tar bort det här så snart appen ligger i papperskorgen, och Historik kan inte få tillbaka det."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Yerinde kalır: uygulama Çöp Sepeti’ne taşındığında uygulamanın kendi yükleme kaldırıcısı bunu siler ve Geçmiş onu geri getiremez."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Лишається на місці: власний деінсталятор програми вилучить це, щойно програма потрапить у Смітник, і Історія не зможе цього повернути."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "留在原处:App进入废纸篓后,它自己的卸载器会移除此项,“历史记录”无法将其恢复。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "原地保留:一旦App進入「垃圾桶」,它自己的解除安裝程式就會移除此項目,而「歷史記錄」無法將其恢復。"+ }+ }+ }+ },"Left out: %@." : {"localizations" : {"cs" : {diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swiftindex 57cfd02a..6311599a 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift@@ -326,6 +326,7 @@ extension HoldBack {case .holdsWorkKeptInACache: "holds work an app keeps nowhere else, such as an editor's local history"case .insideAnotherAppsFolder: "inside another app's folder"case .beyondTheHelper: "needs an administrator, and Peel's helper may not move it"+ case .leftToItsUninstaller: "removed by the app's own uninstaller once the app is in the Trash"case .keptByMacOS: "a cache macOS keeps for itself"case .openedFromMail: "an attachment opened from Mail, which may be the only copy"case .crashReport: "a crash report, which the app's developer may still ask for"diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swiftindex a6d89c80..26f4864f 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift@@ -17,8 +17,10 @@ struct UninstallPlan {let items: [Item]/// How many recommended leftovers need administrator access. The command line never asks for it, so they stay.let needsAdministrator: Int- /// How many leftovers are listed but not recommended: shared with another app, only possible, or held back.+ /// How many leftovers are listed but not recommended: shared with another app, only possible, or held back for+ /// a reason other than the app's own uninstaller, which removes what it holds back.let needsReview: Int+ var uninstallsItself = falsevar moving: [Item] { items.filter { $0.refusal == nil } }var staying: [Item] { items.filter { $0.refusal != nil } }@@ -56,7 +58,8 @@ struct UninstallPlan {app: app,items: items,needsAdministrator: rest.count(where: { $0.match.isRecommended && $0.requiresPrivileges }),- needsReview: rest.count(where: { !$0.match.isRecommended })+ needsReview: rest.count(where: { !$0.match.isRecommended && $0.match.heldBack != .leftToItsUninstaller }),+ uninstallsItself: uninstallation.uninstallsItself != nil)}@@ -89,7 +92,8 @@ struct UninstallPlan {return await service.trash(apps: [app],thenFiles: { stayed in stayed.isEmpty ? files : [] },- usingHelperFor: []+ usingHelperFor: [],+ lettingTheirProgramsRun: uninstallsItself ? [app] : [])}}diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swiftindex 5d74518d..713dac25 100644--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift@@ -74,6 +74,9 @@ public enum HoldBack: String, Sendable, Hashable {case insideAnotherAppsFolder/// Needs an administrator, and the helper's own rule refuses it (`HelperReach`).case beyondTheHelper+ /// Removed by the app's own uninstaller once the app has moved (`UninstallsItself`). Moved first, the file of+ /// the job that runs the uninstaller would stop it, and the rest of its cleanup would never happen.+ case leftToItsUninstaller/// A cache macOS keeps for its own services, which may be using it at any moment (`SystemCaches`).case keptByMacOS/// A copy Mail keeps of an attachment that was opened. One that was edited may exist nowhere else.@@ -95,7 +98,7 @@ public enum HoldBack: String, Sendable, Hashable {/// would refuse to move it.public var cannotBeMoved: Bool {self == .holdsDocuments || self == .holdsALibrary || self == .holdsKeys || self == .holdsWorkKeptInACache- || self == .beyondTheHelper+ || self == .beyondTheHelper || self == .leftToItsUninstaller|| self == .holdsAnExclusion}@@ -108,8 +111,8 @@ public enum HoldBack: String, Sendable, Hashable {case .holdsRepository, .sharedWithEveryone, .namedLikeTheApp, .holdsAnExclusion, .notMeasured, .couldNotBeRead,.holdsDocuments, .holdsALibrary, .holdsAWallet, .holdsAPasswordDatabase, .holdsLocalMail,.holdsMessageHistory, .holdsPasswordsOrCodes, .holdsVPNConnections, .holdsKeys, .holdsWorkKeptInACache,- .insideAnotherAppsFolder, .beyondTheHelper, .keptByMacOS, .openedFromMail, .inTheCloud, .openInAProgram,- .changedRecently, .keptByAnApp, .appIsRunning: true+ .insideAnotherAppsFolder, .beyondTheHelper, .leftToItsUninstaller, .keptByMacOS, .openedFromMail,+ .inTheCloud, .openInAProgram, .changedRecently, .keptByAnApp, .appIsRunning: true}}@@ -269,6 +272,15 @@ public struct LeftoverScan: Sendable {)}+ func leavingToItsUninstaller(_ app: UninstallsItself) -> LeftoverScan {+ LeftoverScan(+ leftovers: leftovers.map { app.removes($0.url) ? $0.heldBack(.leftToItsUninstaller) : $0 },+ unreadableLocations: unreadableLocations,+ cutShortLocations: cutShortLocations,+ needsFullDiskAccess: needsFullDiskAccess+ )+ }+/// Adds findings the scanner didn't see, keeping what it already knows about a path.public func adding(_ extra: [Leftover]) -> LeftoverScan {// By what each item is on the disk, not by its spelling: a cask can write a folder in another case, or withdiff --git a/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swiftindex a75495d8..2fb89b82 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift@@ -175,7 +175,8 @@ public struct BulkUninstallation: Sendable {let kept = Set(stayed.compactMap { identifiers[$0] })return order.filter { !apps.contains($0) && !(owners[$0] ?? []).contains(where: kept.contains) }},- usingHelperFor: privilegedURLs+ usingHelperFor: privilegedURLs,+ lettingTheirProgramsRun: Set(uninstallations.filter { $0.uninstallsItself != nil }.map(\.app.url)))}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swiftindex 2bdc3689..440bd300 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift@@ -6,35 +6,43 @@ internal import PeelPrivileged/// app's agent, a tool's daemon, a server. Of another account's processes, root's included, only the program each/// runs is seen, never the files it holds open.struct OpenFiles {- /// `holdsAnApp` is false for a file a process only reads: inside an app, that holds nothing.- private let files: [(names: [String], process: String, holdsAnApp: Bool)]+ private enum Hold { case reads, writes, runs }++ private let files: [(names: [String], process: String, hold: Hold)]/// Each regular file held open for reading or writing, and the program each process runs, which it holds as long/// as it runs. A watch (`O_EVTONLY`, as Finder keeps on what it shows) and a folder are no hold on what is inside.init(excluding excluded: pid_t? = getpid()) {var pids = [pid_t](repeating: 0, count: 8_192)let count = Int(proc_listallpids(&pids, Int32(pids.count * MemoryLayout<pid_t>.size)))- var files: [(names: [String], process: String, holdsAnApp: Bool)] = []+ var files: [(names: [String], process: String, hold: Hold)] = []for pid in pids.prefix(max(count, 0)) where pid > 0 && pid != excluded {- let program = Self.program(of: pid).map { [(path: $0, holdsAnApp: true)] } ?? []+ let program = Self.program(of: pid).map { [(path: $0, hold: Hold.runs)] } ?? []let paths = Self.paths(openBy: pid) + programguard !paths.isEmpty else { continue }let process = Self.name(of: pid)- files += paths.map { (PathComponents.of($0.path), process, $0.holdsAnApp) }+ files += paths.map { (PathComponents.of($0.path), process, $0.hold) }}self.files = files}/// The programs that hold `url`. An app is code, which loses nothing when it moves, so a program that only reads/// inside it, as Safari reads an app's Safari extension, holds nothing: what runs from it or writes in it does.- func holders(of url: URL) -> [String] {+ func holders(of url: URL, lettingItsProgramsRun: Bool = false) -> [String] {let names = PathComponents.of(PathPattern.canonical(url).path(percentEncoded: false))let isAnApp = url.pathExtension.caseInsensitiveCompare("app") == .orderedSame- return Set(files.filter { $0.names.starts(with: names) && ($0.holdsAnApp || !isAnApp) }.map(\.process)).sorted()+ let holding = files.filter { file in+ guard file.names.starts(with: names) else { return false }+ switch file.hold {+ case .reads: return !isAnApp+ case .writes: return true+ case .runs: return !lettingItsProgramsRun+ }+ }+ return Set(holding.map(\.process)).sorted()}- /// The regular files `pid` holds open, each with whether it may write to it.- private static func paths(openBy pid: pid_t) -> [(path: String, holdsAnApp: Bool)] {+ private static func paths(openBy pid: pid_t) -> [(path: String, hold: Hold)] {let size = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, nil, 0)guard size > 0 else { return [] }var descriptors = [proc_fdinfo](repeating: proc_fdinfo(), count: Int(size) / MemoryLayout<proc_fdinfo>.size)@@ -51,7 +59,7 @@ struct OpenFiles {let path = withUnsafeBytes(of: info.pvip.vip_path) { bytes inString(decoding: bytes.prefix { $0 != 0 }, as: UTF8.self)}- return (path, info.pfi.fi_openflags & UInt32(FWRITE) != 0)+ return (path, info.pfi.fi_openflags & UInt32(FWRITE) != 0 ? .writes : .reads)}}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/PrivacyReset.swift b/Packages/PeelCore/Sources/PeelCore/Removal/PrivacyReset.swiftindex c49f9678..f229c64a 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/PrivacyReset.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/PrivacyReset.swift@@ -49,7 +49,11 @@ public enum PrivacyReset {}static func goingNow(_ apps: [InstalledApp], with service: TrashService) -> [InstalledApp] {- let refused = service.refusalsNow(of: apps.map(\.url))+ let uninstallingThemselves = apps.filter { UninstallsItself.of($0, environment: service.environment) != nil }+ let refused = service.refusalsNow(+ of: apps.map(\.url),+ lettingTheirProgramsRun: Set(uninstallingThemselves.map(\.url))+ )return apps.filter { refused[$0.url] == nil }}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/SelfRemoval.swift b/Packages/PeelCore/Sources/PeelCore/Removal/SelfRemoval.swiftindex 90aa3c1f..b61ecf74 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/SelfRemoval.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/SelfRemoval.swift@@ -16,7 +16,8 @@ public enum SelfRemoval {var result = await service.trash(apps: urls.filter { $0 == app },thenFiles: { stayed in stayed.isEmpty ? files : [] },- usingHelperFor: []+ usingHelperFor: [],+ lettingTheirProgramsRun: [])await record(result)guarddiff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swiftindex 3ef5f552..c1db6918 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift@@ -179,7 +179,7 @@ public struct TrashService: Sendable {typealias MoveThroughHelper = @Sendable ([URL]) async -> TrashResulttypealias PutBackDockTiles = @Sendable (URL) async -> Void- private let environment: SearchEnvironment+ let environment: SearchEnvironmentprivate let removalGuard: RemovalGuardprivate let stopJobs: StopJobsprivate let forgetDomains: ForgetDomains@@ -265,13 +265,14 @@ public struct TrashService: Sendable {/// Why each of `urls` would not move now, by the checks a move makes before it starts: the guard, History, and the/// programs holding it. An item missing from the answer would move.- func refusalsNow(of urls: [URL]) -> [URL: TrashFailure.Reason] {+ func refusalsNow(of urls: [URL], lettingTheirProgramsRun apps: Set<URL>) -> [URL: TrashFailure.Reason] {let openFiles = OpenFiles()var refusals: [URL: TrashFailure.Reason] = [:]for url in urls {if let refusal = refusal(of: url) {refusals[url] = refusal- } else if case let holders = openFiles.holders(of: url), !holders.isEmpty {+ } else if case let holders = openFiles.holders(of: url, lettingItsProgramsRun: apps.contains(url)),+ !holders.isEmpty {refusals[url] = .heldOpen(by: holders)}}@@ -298,18 +299,23 @@ public struct TrashService: Sendable {@concurrentpublic func trash(_ urls: [URL], ownedBy owner: String? = nil) async -> TrashResult {if let refused = refusingAllWhileHistoryCannotBeRead(urls) { return refused }- return await trash(urls, ownedBy: owner, removal: UUID())+ return await trash(urls, ownedBy: owner, removal: UUID(), lettingTheirProgramsRun: [])}/// Moves files Peel made for itself, which History never lists, such as a copy of settings it could not/// finish: to the Trash like anything else, with nothing written down for History.@concurrentfunc trashOwnFiles(_ urls: [URL]) async -> TrashResult {- await trash(urls, ownedBy: nil, removal: nil)+ await trash(urls, ownedBy: nil, removal: nil, lettingTheirProgramsRun: [])}/// Moves `urls` as the current user, as part of `removal`, the move the journal groups them by, or of none.- private func trash(_ urls: [URL], ownedBy owner: String?, removal: UUID?) async -> TrashResult {+ private func trash(+ _ urls: [URL],+ ownedBy owner: String?,+ removal: UUID?,+ lettingTheirProgramsRun apps: Set<URL>+ ) async -> TrashResult {// The guard reads the disk, so it is asked once for each item.let refusals = urls.reduce(into: [URL: GuardRefusal]()) { $0[$1] = removalGuard.refusal(of: $1) }let allowed = urls.filter { refusals[$0] == nil }@@ -328,7 +334,7 @@ public struct TrashService: Sendable {// An item inside a folder that just moved went with it: it is neither moved again nor a failure.let path = PathPattern.comparablePath(of: url)guard !moved.hold(path) else { continue }- let holders = openFiles.holders(of: url)+ let holders = openFiles.holders(of: url, lettingItsProgramsRun: apps.contains(url))guard holders.isEmpty else {result.failures.append(TrashFailure(url: url, reason: .heldOpen(by: holders)))continue@@ -361,33 +367,45 @@ public struct TrashService: Sendable {/// Moves `privilegedURLs` through the privileged helper and everything else as the current user.@concurrentpublic func trash(_ urls: [URL], usingHelperFor privilegedURLs: Set<URL>) async -> TrashResult {- await trash(urls, usingHelperFor: privilegedURLs, removal: UUID())+ await trash(urls, usingHelperFor: privilegedURLs, removal: UUID(), lettingTheirProgramsRun: [])}/// Moves `apps` first, then what `files` returns for the apps that stayed, as one removal. An app's files wait- /// for it, so an app that stays keeps everything of its own.+ /// for it, so an app that stays keeps everything of its own. A program running from inside one of+ /// `lettingTheirProgramsRun` doesn't keep it, since that app uninstalls itself once it has moved.@concurrentpublic func trash(apps: [URL],thenFiles files: @Sendable (_ appsThatStayed: Set<URL>) -> [URL],- usingHelperFor privilegedURLs: Set<URL>+ usingHelperFor privilegedURLs: Set<URL>,+ lettingTheirProgramsRun running: Set<URL>) async -> TrashResult {let removal = UUID()var result = apps.isEmpty? TrashResult()- : await trash(apps, usingHelperFor: privilegedURLs, removal: removal)+ : await trash(apps, usingHelperFor: privilegedURLs, removal: removal, lettingTheirProgramsRun: running)let moved = Set(result.trashed.map(\.originalURL))let rest = files(Set(apps.filter { !moved.contains($0) }))guard !rest.isEmpty else { return result }- let more = await trash(rest, usingHelperFor: privilegedURLs, removal: removal)+ let more = await trash(rest, usingHelperFor: privilegedURLs, removal: removal, lettingTheirProgramsRun: [])result.trashed += more.trashedresult.failures += more.failuresreturn result}- private func trash(_ urls: [URL], usingHelperFor privilegedURLs: Set<URL>, removal: UUID) async -> TrashResult {+ private func trash(+ _ urls: [URL],+ usingHelperFor privilegedURLs: Set<URL>,+ removal: UUID,+ lettingTheirProgramsRun apps: Set<URL>+ ) async -> TrashResult {if let refused = refusingAllWhileHistoryCannotBeRead(urls) { return refused }- var result = await trash(urls.filter { !privilegedURLs.contains($0) }, ownedBy: nil, removal: removal)+ var result = await trash(+ urls.filter { !privilegedURLs.contains($0) },+ ownedBy: nil,+ removal: removal,+ lettingTheirProgramsRun: apps+ )let helperURLs = urls.filter(privilegedURLs.contains)guard !helperURLs.isEmpty else { return result }@@ -407,7 +425,7 @@ public struct TrashService: Sendable {var allowed: [URL] = []for url in permitted {guard !paths.hold(PathPattern.comparablePath(of: url)) else { continue }- let holders = openFiles.holders(of: url)+ let holders = openFiles.holders(of: url, lettingItsProgramsRun: apps.contains(url))guard holders.isEmpty else {result.failures.append(TrashFailure(url: url, reason: .heldOpen(by: holders)))continuediff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swiftindex 3e5931e7..635ef2b0 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift@@ -19,6 +19,7 @@ public struct Uninstallation: Sendable {/// True when the app is already in the Trash, where Watch the Trash finds it: its bundle can't move again, so/// it is never selected or counted, and what it left behind still is.public var isAppInTheTrash = false+ public var uninstallsItself: UninstallsItself?/// True for Peel, which is removed only from its own Settings, where its helper and login item go first. Its/// files are listed, and nothing of it is selected or moved anywhere else: `unreviewedSelection` is that way.public var isPeel: Bool { app.isPeelItself }@@ -61,6 +62,10 @@ public struct Uninstallation: Sendable {scan = scan.adding(await receiptLeftovers(for: app, receipts: receipts, exclusions: exclusions, environment: environment))+ let uninstallsItself = UninstallsItself.of(app, environment: environment)+ if let uninstallsItself {+ scan = scan.leavingToItsUninstaller(uninstallsItself)+ }let reach = HelperReach(environment: environment)scan = scan.holdingBack(beyond: reach, leaving: app.url)let appRequiresPrivileges = FileAccess.requiresPrivilegesToRemove(app.url)@@ -72,7 +77,8 @@ public struct Uninstallation: Sendable {isAppMeasured: await bundle.map { !$0.couldNotBeRead } ?? false,appSharesStorage: await bundle?.sharesMostOfItsStorage ?? false,isAppBeyondTheHelper: appRequiresPrivileges && !app.isSystemProtected && reach.isBeyond(app.url),- isAppInTheTrash: TrashService(environment: environment).isInsideATrash(app.url)+ isAppInTheTrash: TrashService(environment: environment).isInsideATrash(app.url),+ uninstallsItself: uninstallsItself)}@@ -272,7 +278,8 @@ public struct Uninstallation: Sendable {return await service.trash(apps: order.filter { $0 == app.url },thenFiles: { stayed in stayed.isEmpty ? files : [] },- usingHelperFor: throughTheHelper ? privilegedURLs : []+ usingHelperFor: throughTheHelper ? privilegedURLs : [],+ lettingTheirProgramsRun: uninstallsItself == nil ? [] : [app.url])}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/UninstallsItself.swift b/Packages/PeelCore/Sources/PeelCore/Removal/UninstallsItself.swiftindex 8c10bedc..7fc81c36 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/UninstallsItself.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/UninstallsItself.swift@@ -1,18 +1,61 @@public import Foundation+internal import PeelPrivileged/// An app whose own service uninstalls it once the app leaves its place, deleting what History can't put back.public struct UninstallsItself: Sendable, Hashable {public let app: InstalledApppublic let uninstaller: String+ private let removed: Set<String>/// Mullvad VPN's daemon watches `/Applications/Mullvad VPN.app`, and when its own program goes it logs the Mac out/// of the account and runs `uninstall_macos.sh`, which deletes the settings (`mullvad-daemon/src/macos.rs`).- private static let mullvad = (identifier: "net.mullvad.vpn", path: "/Applications/Mullvad VPN.app")+ private static let mullvad = (identifier: "net.mullvad.vpn", path: "Applications/Mullvad VPN.app")- public static func when(moving urls: Set<URL>, among apps: [InstalledApp]) -> [UninstallsItself] {- apps.filter { app in- urls.contains(app.url) && app.bundleIdentifier == mullvad.identifier- && PathPattern.comparablePath(of: app.url) == mullvad.path- }.map { UninstallsItself(app: $0, uninstaller: mullvad.path + "/Contents/Resources/uninstall.sh") }+ private static let mullvadRemoves = (+ root: [+ "Library/LaunchDaemons/net.mullvad.daemon.plist",+ "usr/local/share/zsh/site-functions/_mullvad",+ "opt/homebrew/share/fish/vendor_completions.d/mullvad.fish",+ "usr/local/share/fish/vendor_completions.d/mullvad.fish",+ "usr/local/share/nushell/vendor/autoload/mullvad.nu",+ "usr/local/bin/mullvad",+ "usr/local/bin/mullvad-problem-report",+ "private/var/db/receipts/net.mullvad.vpn.bom",+ "private/var/db/receipts/net.mullvad.vpn.plist",+ "private/var/log/mullvad-vpn",+ "private/var/root/Library/Caches/mullvad-vpn",+ "Library/Caches/mullvad-vpn",+ "private/etc/mullvad-vpn",+ ],+ home: ["Library/Logs/Mullvad VPN", "Library/Application Support/Mullvad VPN"]+ )++ public static func of(_ app: InstalledApp, environment: SearchEnvironment = .current) -> UninstallsItself? {+ let root = environment.rootDirectory+ let place = root.appending(path: mullvad.path)+ guard+ app.bundleIdentifier == mullvad.identifier,+ PathPattern.comparablePath(of: app.url) == PathPattern.comparablePath(of: place)+ else { return nil }+ let removed = mullvadRemoves.root.map { root.appending(path: $0) }+ + mullvadRemoves.home.map { environment.homeDirectory.appending(path: $0) }+ return UninstallsItself(+ app: app,+ uninstaller: place.appending(path: "Contents/Resources/uninstall.sh").path(percentEncoded: false),+ removed: Set(removed.map(PathPattern.comparablePath))+ )+ }++ func removes(_ url: URL) -> Bool {+ let path = PathPattern.comparablePath(of: url)+ return removed.contains { PathComponents.isPath(path, atOrInside: $0) }+ }++ public static func when(+ moving urls: Set<URL>,+ among apps: [InstalledApp],+ environment: SearchEnvironment = .current+ ) -> [UninstallsItself] {+ apps.filter { urls.contains($0.url) }.compactMap { of($0, environment: environment) }}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OpenFilesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OpenFilesTests.swiftindex 3972b9b7..d7735801 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/OpenFilesTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/OpenFilesTests.swift@@ -64,6 +64,21 @@ struct OpenFilesTests {#expect(!OpenFiles(excluding: nil).holders(of: app).isEmpty)}+ @Test func aProgramRunningFromInsideAnAppHoldsItUnlessItsProgramsMayRun() throws {+ let directory = try TemporaryDirectory()+ let process = try directory.runningProgram("Example.app/Contents/Resources/daemon")+ defer { process.terminate() }+ let state = try directory.file("Example.app/Contents/Resources/state.db")+ let app = directory.url.appending(path: "Example.app", directoryHint: .isDirectory)++ #expect(OpenFiles(excluding: nil).holders(of: app) == ["daemon"])+ #expect(OpenFiles(excluding: nil).holders(of: app, lettingItsProgramsRun: true).isEmpty)++ let writing = try FileHandle(forWritingTo: state)+ defer { try? writing.close() }+ #expect(!OpenFiles(excluding: nil).holders(of: app, lettingItsProgramsRun: true).isEmpty)+ }+/// A process of another account, root's included, can't be asked its name, but the program it runs says it.@Test func namesAProcessOfAnotherAccountByItsProgram() {#expect(OpenFiles.name(of: 1) == "launchd")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UninstallsItselfTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UninstallsItselfTests.swiftindex 1e768802..a2289002 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UninstallsItselfTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UninstallsItselfTests.swift@@ -1,4 +1,5 @@import Foundation+@testable import PeelCommandLine@testable import PeelCoreimport Testing@@ -36,4 +37,164 @@ struct UninstallsItselfTests {#expect(UninstallsItself.when(moving: [elsewhere.url], among: [elsewhere]).isEmpty)#expect(UninstallsItself.when(moving: [another.url], among: [another]).isEmpty)}++ private struct Installed: ~Copyable {+ let directory: TemporaryDirectory+ let app: InstalledApp+ let environment: SearchEnvironment+ let daemon: Process++ init() throws {+ let directory = try TemporaryDirectory()+ let bundle = try directory.directory("root/Applications/Mullvad VPN.app")+ let daemon = try directory.runningProgram("root/Applications/Mullvad VPN.app/Contents/Resources/mullvad-daemon")+ self.app = InstalledApp(url: bundle, bundleIdentifier: "net.mullvad.vpn", name: "Mullvad VPN")+ self.environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)+ )+ self.daemon = daemon+ self.directory = directory+ }++ deinit {+ daemon.terminate()+ }++ func service() throws -> TrashService {+ let trash = try directory.directory("home/.Trash")+ return TrashService(environment: environment) { url in+ let destination = trash.appending(path: url.lastPathComponent)+ try FileManager.default.moveItem(at: url, to: destination)+ return destination+ }+ }+ }++ @Test func leavesToTheUninstallerWhatItRemovesAndOffersTheRest() async throws {+ let installed = try Installed()+ let program = installed.app.url.appending(path: "Contents/Resources/mullvad-daemon").path(percentEncoded: false)+ let job = try installed.directory.file(+ "root/Library/LaunchDaemons/net.mullvad.daemon.plist",+ contents: PropertyListSerialization.data(+ fromPropertyList: ["Label": "net.mullvad.daemon", "Program": program], format: .xml, options: 0+ )+ )+ let removedByIt = [+ job,+ try installed.directory.directory("home/Library/Application Support/Mullvad VPN"),+ try installed.directory.directory("home/Library/Logs/Mullvad VPN"),+ try installed.directory.file("root/private/var/db/receipts/net.mullvad.vpn.bom"),+ try installed.directory.file("root/private/var/db/receipts/net.mullvad.vpn.plist"),+ ]+ let preferences = try installed.directory.file("home/Library/Preferences/net.mullvad.vpn.plist")++ let plan = await Uninstallation.prepare(+ installed.app,+ installedApps: [installed.app],+ receipts: ["net.mullvad.vpn"],+ environment: installed.environment+ )++ let heldBack = Dictionary(+ plan.scan.leftovers.map { (PathPattern.comparablePath(of: $0.url), $0.match.heldBack) },+ uniquingKeysWith: { first, _ in first }+ )+ for url in removedByIt {+ #expect(heldBack[PathPattern.comparablePath(of: url)] == .some(.leftToItsUninstaller), "\(url.path())")+ }+ #expect(heldBack[PathPattern.comparablePath(of: preferences)] == .some(nil))+ #expect(plan.uninstallsItself?.app == installed.app)+ }++ @Test func itsBundleMovesWhileItsOwnProgramRunsFromIt() async throws {+ let installed = try Installed()+ let preferences = try installed.directory.file("home/Library/Preferences/net.mullvad.vpn.plist")+ let plan = await Uninstallation.prepare(+ installed.app, installedApps: [installed.app], environment: installed.environment+ )++ let result = await plan.move([installed.app.url, preferences], using: try installed.service())++ #expect(result.failures.isEmpty, "\(result.failures.map(\.reason))")+ #expect(Set(result.trashed.map(\.originalURL)) == [installed.app.url, preferences])+ }++ @Test func itsBundleGoesThroughTheHelperWhileItsOwnProgramRunsFromIt() async throws {+ let installed = try Installed()+ let trash = try installed.directory.directory("home/.Trash")+ let service = TrashService(+ environment: installed.environment,+ moveThroughHelper: { urls in+ var result = TrashResult()+ for url in urls {+ let destination = trash.appending(path: url.lastPathComponent)+ try? FileManager.default.moveItem(at: url, to: destination)+ result.trashed.append(TrashedItem(originalURL: url, trashedURL: destination, date: .now))+ }+ return result+ },+ moveToTrash: { _ in throw CocoaError(.fileWriteNoPermission) }+ )+ let app = installed.app.url++ let held = await service.trash(+ apps: [app], thenFiles: { _ in [] }, usingHelperFor: [app], lettingTheirProgramsRun: []+ )+ let moved = await service.trash(+ apps: [app], thenFiles: { _ in [] }, usingHelperFor: [app], lettingTheirProgramsRun: [app]+ )++ #expect(held.failures.map(\.reason) == [.heldOpen(by: ["mullvad-daemon"])])+ #expect(moved.trashed.map(\.originalURL) == [app])+ }++ @Test func itsBundleMovesAmongSeveralAppsWhileItsOwnProgramRunsFromIt() async throws {+ let installed = try Installed()+ let several = await BulkUninstallation.prepare(+ [installed.app], installedApps: [installed.app], environment: installed.environment+ )++ let result = await several.move([installed.app.url], using: try installed.service())++ #expect(result.failures.isEmpty, "\(result.failures.map(\.reason))")+ #expect(result.trashed.map(\.originalURL) == [installed.app.url])+ }++ @Test func peelUninstallMovesItsBundleWhileItsOwnProgramRunsFromIt() async throws {+ let installed = try Installed()+ let plan = UninstallPlan.make(+ await Uninstallation.prepare(+ installed.app, installedApps: [installed.app], environment: installed.environment+ ),+ keepLeftovers: true,+ refusal: { _ in nil }+ )++ let result = await plan.move(using: try installed.service())++ #expect(result.failures.isEmpty, "\(result.failures.map(\.reason))")+ #expect(result.trashed.map(\.originalURL) == [installed.app.url])+ }++ @Test func peelUninstallLeavesOutOfReviewWhatItsUninstallerRemoves() async throws {+ let installed = try Installed()+ try installed.directory.directory("home/Library/Logs/Mullvad VPN")++ let plan = UninstallPlan.make(+ await Uninstallation.prepare(+ installed.app, installedApps: [installed.app], environment: installed.environment+ ),+ keepLeftovers: false,+ refusal: { _ in nil }+ )++ #expect(plan.needsReview == 0)+ }++ @Test func itsPrivacyIsResetThoughItsOwnProgramRunsFromIt() throws {+ let installed = try Installed()++ #expect(PrivacyReset.goingNow([installed.app], with: try installed.service()) == [installed.app])+ }}diff --git a/Peel/Views/Presentation.swift b/Peel/Views/Presentation.swiftindex 6d350e6d..f4a9ef0b 100644--- a/Peel/Views/Presentation.swift+++ b/Peel/Views/Presentation.swift@@ -248,6 +248,8 @@ extension HoldBack {"Not selected: only the name matches, and it sits inside a folder that belongs to macOS or to another installed app, which may be keeping it for itself."case .beyondTheHelper:"Left alone: only an administrator can move this, and Peel’s helper isn’t allowed to move it from here."+ case .leftToItsUninstaller:+ "Left alone: the app’s own uninstaller removes this once the app is in the Trash, and History can’t bring it back."case .keptByMacOS:"Not selected: macOS keeps this cache for its own services, which may be using it right now."case .openedFromMail:diff --git a/SAFETY.md b/SAFETY.mdindex f5b9e165..b891b596 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -132,9 +132,10 @@ Right before anything moves, Peel looks at the files other programs of yours holprocess runs, and leaves where it is any file or folder with one of them inside, naming the program: moving adatabase or a cache from under an agent, a daemon, or a server that is using it would break it. An app is code,which loses nothing when it moves, so a program that only reads inside it, as Safari reads an app's Safari-extension, does not keep it in place; one that runs from it or writes in it does. Of programs that run as another-account or as root, macOS's own among them, only the program can be seen, never the files it holds open, which is-why Space also leaves macOS's own caches unselected, and in the Library at the top of the disk, where those+extension, does not keep it in place; one that runs from it or writes in it does, unless the app uninstalls itself+once it is moved, as Mullvad VPN does: the program running from it is the one that cleans up. Of programs that run as+another account or as root, macOS's own among them, only the program can be seen, never the files it holds open,+which is why Space also leaves macOS's own caches unselected, and in the Library at the top of the disk, where thoseprograms keep theirs, does not list them at all.A move to the Trash, or back from it, never replaces what is already at the new name. Most disks refuse that by@@ -154,7 +155,9 @@ turns that cleanup back on, the Homebrew page says so and Peel leaves upgrades tdomain after a removal (described above) is not one of the four: it is done only once the file is in the Trash, andputting the file back undoes it, until the app writes its settings again. And one app deletes something of its own onceit is moved: Mullvad VPN's service logs the Mac out of its account and deletes its settings when the app leaves the-Applications folder, which Peel says before it moves it.+Applications folder, which Peel says before it moves it. What that service removes (its launch daemon's file, its+command links and shell completions, its receipt, its logs, and its settings) is listed and never moved by Peel:+moving the daemon's file first would stop the service before it could clean up.If the record itself is damaged, it is set aside under another name rather than overwritten, because it isthe only way back from a removal. If it can't be read at all, Peel moves nothing until it can, or until you