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
Say when macOS still starts an uninstalled app's background items
Țugui Dragoș696799af18c8
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex 7a970758..c059f09a 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -36919,6 +36919,112 @@}}},+ "Empty the Trash to finish." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Chcete-li odstranění dokončit, vysypte koš."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Entleere den Papierkorb, um das Entfernen abzuschließen."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Vacía la papelera para terminar."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Videz la corbeille pour terminer la suppression."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Svuota il Cestino per completare la rimozione."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "完了するにはゴミ箱を空にしてください。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "제거를 완료하려면 휴지통을 비우십시오."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Leeg de prullenmand om de verwijdering te voltooien."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Aby zakończyć, opróżnij Kosz."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Esvazie o Lixo para concluir."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Goliți Coșul pentru a încheia eliminarea."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Чтобы завершить удаление, очистите Корзину."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Töm papperskorgen för att slutföra borttagningen."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Kaldırma işlemini tamamlamak için Çöp Sepeti’ni boşaltın."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Очистьте Смітник, щоб завершити вилучення."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "清倒废纸篓以完成移除。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "請清空「垃圾桶」以完成移除。"+ }+ }+ }+ },"Enable" : {"localizations" : {"cs" : {@@ -99487,6 +99593,112 @@}}},+ "Open Login Items & Extensions" : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Otevřít nastavení Aktivace položek a rozšíření při přihlášení"+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Anmeldeobjekte & Erweiterungen öffnen"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Abrir Ítems de inicio y extensiones"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ouvrir Ouverture et extensions"+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Apri “Elementi login ed estensioni”"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ログイン項目と機能拡張を開く"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "로그인 항목 및 확장 프로그램 열기"+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Open 'Inlogonderdelen en extensies'"+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Otwórz Rzeczy i rozszerzenia otwierane podczas logowania"+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Abrir Itens de Início de Sessão e Extensões"+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Deschideți Lansare la login și extensii"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Открыть раздел «Объекты входа и расширения»"+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Öppna Startobjekt och tillägg"+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Oturum Açma Öğeleri ve Genişletmeler’i Aç"+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Відкрити Автозапуск і розширення"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开登录项与扩展"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打開登入項目與延伸功能"+ }+ }+ }+ },"Open Peel" : {"localizations" : {"cs" : {@@ -130051,6 +130263,112 @@}}},+ "Restart your Mac and empty the Trash to finish." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Chcete-li odstranění dokončit, restartujte Mac a vysypte koš."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Starte deinen Mac neu und entleere den Papierkorb, um das Entfernen abzuschließen."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Reinicia el Mac y vacía la papelera para terminar."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Redémarrez votre Mac et videz la corbeille pour terminer la suppression."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Riavvia il Mac e svuota il Cestino per completare la rimozione."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "完了するにはMacを再起動してゴミ箱を空にしてください。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "제거를 완료하려면 Mac을 재시동하고 휴지통을 비우십시오."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Start je Mac opnieuw op en leeg de prullenmand om de verwijdering te voltooien."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Aby zakończyć, uruchom ponownie Maca i opróżnij Kosz."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Reinicie o Mac e esvazie o Lixo para concluir."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Reporniți Mac‑ul și goliți Coșul pentru a încheia eliminarea."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Чтобы завершить удаление, перезагрузите Mac и очистите Корзину."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Starta om datorn och töm papperskorgen för att slutföra borttagningen."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Kaldırma işlemini tamamlamak için Mac’inizi yeniden başlatın ve Çöp Sepeti’ni boşaltın."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Перезапустіть Mac і очистьте Смітник, щоб завершити вилучення."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重新启动你的Mac并清倒废纸篓以完成移除。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "請將Mac重新開機並清空「垃圾桶」以完成移除。"+ }+ }+ }+ },"Restart your Mac to finish." : {"localizations" : {"cs" : {@@ -205536,6 +205854,112 @@}}},+ "macOS still starts the background items of %@ from the Trash each time you log in, until you empty the Trash." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Aplikace %@ leží v koši spolu se svými položkami na pozadí, které systém macOS odtud při každém přihlášení dál spouští, dokud nevysypete koš."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "macOS startet die Hintergrundobjekte von %@ weiterhin bei jeder Anmeldung aus dem Papierkorb, bis du den Papierkorb entleerst."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "macOS sigue iniciando los ítems en segundo plano de %@ desde la papelera cada vez que inicias sesión, hasta que vacíes la papelera."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "macOS continue de lancer les éléments en arrière-plan de %@ depuis la corbeille à chaque ouverture de session, jusqu’à ce que vous vidiez la corbeille."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "macOS continua ad avviare dal Cestino gli elementi in background di %@ ogni volta che esegui il login, finché non svuoti il Cestino."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ゴミ箱を空にするまで、macOSはログインするたびに%@のバックグラウンド項目をゴミ箱から起動し続けます。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "휴지통을 비울 때까지는 로그인할 때마다 macOS가 휴지통에서 %@의 백그라운드 항목을 계속 시작합니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "macOS start de achtergrondonderdelen van %@ nog steeds vanuit de prullenmand telkens als je inlogt, totdat je de prullenmand leegt."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "macOS nadal uruchamia z Kosza rzeczy działające w tle aplikacji %@ przy każdym logowaniu, dopóki nie opróżnisz Kosza."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "O macOS ainda inicia os itens em segundo plano de %@ a partir do Lixo sempre que você iniciar a sessão, até você esvaziar o Lixo."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "La fiecare login, macOS pornește în continuare din Coș articolele de fundal de la %@, până când goliți Coșul."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "macOS продолжит запускать фоновые объекты %@ из Корзины при каждом входе в систему, пока Вы не очистите Корзину."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "macOS startar fortfarande bakgrundsobjekten för %@ från papperskorgen varje gång du loggar in, tills du tömmer papperskorgen."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Çöp Sepeti boşaltılana kadar macOS, her oturum açtığınızda %@ arka plan öğelerini Çöp Sepeti’nden başlatmaya devam eder."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "macOS і далі запускає зі Смітника фонові елементи %@ щоразу, коли ви входите в систему, доки ви не очистите Смітник."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "macOS仍会在你每次登录时从废纸篓中启动“%@”的后台项目,直到你清倒废纸篓。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "macOS仍會在你每次登入時從「垃圾桶」啟動%@的背景項目,直到你清空「垃圾桶」。"+ }+ }+ }+ },"macOS stops an app from moving another developer’s app to the Trash unless you allow it. Without this, Peel can still clear an app’s files, but macOS may refuse to move the app itself." : {"localizations" : {"cs" : {diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swiftindex b461e948..26948879 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift@@ -392,6 +392,12 @@ struct UninstallCommand: AsyncParsableCommand {return "Peel takes \(Output.plain(app.name))'s icon out of the Dock once it is in the Trash, and puts it back if you put the app back. Add --keep-in-dock to leave it."}+ /// What macOS still starts from the Trash once the app moved: its background items, at each login.+ static func startsFromTheTrashNote(for app: InstalledApp, after result: TrashResult) -> String? {+ guard result.startsFromTheTrash.contains(app.url) else { return nil }+ return "macOS still starts the background items of \(Output.plain(app.name)) from the Trash each time you log in, until you empty the Trash. System Settings > General > Login Items & Extensions can turn them off."+ }+/// What would stop the move now, as a note on a dry run, which moves nothing, and as the refusal otherwise.static func note(for failure: CommandFailure?, dryRun: Bool) throws -> String? {guard let failure else { return nil }@@ -620,6 +626,9 @@ struct UninstallCommand: AsyncParsableCommand {privacy.failed ? Output.note(privacy.line) : Output.line(privacy.line)}}+ if let note = Self.startsFromTheTrashNote(for: target, after: result) {+ Output.note(note)+ }if !recorded {Output.note("Peel couldn't write this to its History, so drag these back out of the Trash in Finder if you need to.")}diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swiftindex 607f446d..9fe67f33 100644--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift@@ -3,7 +3,7 @@ import Foundationimport PeelPrivilegedpublic enum BackgroundItems {- private static let serviceManagement = "com.apple.xpc.ServiceManagement"+ static let serviceManagement = "com.apple.xpc.ServiceManagement"private static let concurrentDetailQueries = 8public struct Scan: Sendable {diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swiftindex 35e299c5..2e4df496 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift@@ -68,7 +68,7 @@ enum LaunchdCleanup {return stopped}- private static func isAppsOwn(_ label: String) -> Bool {+ static func isAppsOwn(_ label: String) -> Bool {!label.hasPrefix("application.") && PrivilegedPathPolicy.isValidLabel(label) && label != HelperIdentity.helperIdentifier&& !SystemDaemons.shipped.contains(label) && !SystemAgents.shipped.contains(label)}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/StartsAtLogin.swift b/Packages/PeelCore/Sources/PeelCore/Removal/StartsAtLogin.swiftnew file mode 100644index 00000000..05ca302d--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Removal/StartsAtLogin.swift@@ -0,0 +1,60 @@+import Foundation+internal import PeelPrivileged++/// The background items an app registers for this user through ServiceManagement: its login items, in+/// `Contents/Library/LoginItems`, and its agents, in `Contents/Library/LaunchAgents` (`SMAppService.h`). Once+/// registered, macOS starts them at every login from wherever the app is, the Trash included, until it is emptied.+enum StartsAtLogin {+ /// What launchd holds of what an app registered.+ struct Registration: Sendable, Equatable {+ let identifier: String+ let labels: [String]+ }++ /// A bundle writes its labels itself, so only so many are asked about.+ static let mostAsked = 64++ /// The labels launchd gives an app's items: each login item's bundle identifier, each agent's `Label`.+ static func labels(declaredBy app: URL) -> [String] {+ let library = app.appending(path: "Contents/Library", directoryHint: .isDirectory)+ let loginItems = entries(of: library.appending(path: "LoginItems", directoryHint: .isDirectory))+ .filter { $0.pathExtension == "app" }+ .compactMap(identifier(of:))+ let agents = entries(of: library.appending(path: "LaunchAgents", directoryHint: .isDirectory))+ .filter { $0.pathExtension == "plist" }+ .compactMap { JobDefinition(contentsOf: $0)?.label }+ var seen: Set<String> = []+ return Array((loginItems + agents).filter { LaunchdCleanup.isAppsOwn($0) && seen.insert($0).inserted }+ .prefix(mostAsked))+ }++ /// What launchd holds now of what `app` registered, or nil when it holds nothing.+ @concurrent+ static func registration(of app: URL) async -> Registration? {+ guard let identifier = identifier(of: app), Identifier.isValid(identifier) else { return nil }+ var registered: [String] = []+ for label in labels(declaredBy: app) {+ let printed = await Launchctl.run(["print", "gui/\(getuid())/\(label)"])+ if isRegistered(Launchctl.answer(status: printed.status, output: printed.output), for: identifier) {+ registered.append(label)+ }+ }+ return registered.isEmpty ? nil : Registration(identifier: identifier, labels: registered)+ }++ /// Whether `answer` is a job ServiceManagement manages for the app `identifier` names.+ static func isRegistered(_ answer: Launchctl.Answer, for identifier: String) -> Bool {+ guard case .details(let details) = answer else { return false }+ return details.managedBy == BackgroundItems.serviceManagement+ && details.parentBundleIdentifier?.caseInsensitiveCompare(identifier) == .orderedSame+ }++ private static func identifier(of bundle: URL) -> String? {+ BoundedRead.propertyList(at: bundle.appending(path: "Contents/Info.plist"))?["CFBundleIdentifier"] as? String+ }++ private static func entries(of folder: URL) -> [URL] {+ let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path(percentEncoded: false))) ?? []+ return names.sorted().map { folder.appending(path: $0) }+ }+}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swiftindex 95644745..e09beecc 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift@@ -192,6 +192,8 @@ public struct TrashResult: Sendable {public var failures: [TrashFailure] = []/// The folders an uninstall left empty and moved too, which free nothing.public internal(set) var emptied: Set<URL> = []+ /// The apps that moved whose background items macOS still starts at login, now from the Trash, until it is emptied.+ public internal(set) var startsFromTheTrash: [URL] = []public init(trashed: [TrashedItem] = [], failures: [TrashFailure] = []) {self.trashed = trashed@@ -217,6 +219,7 @@ public struct TrashService: Sendable {typealias PutBackDockTiles = @Sendable (URL) async -> Voidtypealias RunningInside = @Sendable (_ app: URL) async -> [LaunchdCleanup.Running]typealias StopRunning = @Sendable ([LaunchdCleanup.Running], _ canUseHelper: Bool) async -> [LaunchdCleanup.Running]+ typealias RegistrationAtLogin = @Sendable (_ app: URL) async -> StartsAtLogin.Registration?let environment: SearchEnvironmentprivate let removalGuard: RemovalGuard@@ -227,6 +230,7 @@ public struct TrashService: Sendable {private let putBackDockTiles: PutBackDockTilesprivate let runningInside: RunningInsideprivate let stopRunning: StopRunning+ private let registrationAtLogin: RegistrationAtLoginprivate let moveToTrash: @Sendable (URL) throws -> URLprivate let ownMoves: OwnTrashMoves/// Where each item is written down as soon as it moves, so a removal cut short still reaches History.@@ -244,14 +248,19 @@ public struct TrashService: Sendable {putBackDockTiles: { await DockTiles().putBack($0) },runningInside: { await LaunchdCleanup.running(inside: $0, environment: environment) },stopRunning: { await LaunchdCleanup.stop($0, canUseHelper: $1) },+ // Seen on macOS 27, which is where the note that reads it is shown.+ registrationAtLogin: { app in+ guard #available(macOS 27, *) else { return nil }+ return await StartsAtLogin.registration(of: app)+ },moveToTrash: { try Self.moveToSystemTrash($0, refusal: removalGuard.refusal(of:)) },ownMoves: .shared,journal: RemovalJournal(beside: RemovalHistory.defaultURL))}- /// For tests. Unless a test passes its own, it stops and starts no launchd job, forgets no preference domain, acts- /// as if there were no helper, changes no Dock, and writes no journal.+ /// For tests. Unless a test passes its own, it stops and starts no launchd job, asks launchd nothing, forgets no+ /// preference domain, acts as if there were no helper, changes no Dock, and writes no journal.init(environment: SearchEnvironment,exclusions: Exclusions = .none,@@ -262,6 +271,7 @@ public struct TrashService: Sendable {putBackDockTiles: @escaping PutBackDockTiles = { _ in },runningInside: @escaping RunningInside = { _ in [] },stopRunning: @escaping StopRunning = { _, _ in [] },+ registrationAtLogin: @escaping RegistrationAtLogin = { _ in nil },ownMoves: OwnTrashMoves = OwnTrashMoves(),journal: RemovalJournal? = nil,moveToTrash: @escaping @Sendable (URL) throws -> URL@@ -276,6 +286,7 @@ public struct TrashService: Sendable {putBackDockTiles: putBackDockTiles,runningInside: runningInside,stopRunning: stopRunning,+ registrationAtLogin: registrationAtLogin,moveToTrash: moveToTrash,ownMoves: ownMoves,journal: journal@@ -292,6 +303,7 @@ public struct TrashService: Sendable {putBackDockTiles: @escaping PutBackDockTiles,runningInside: @escaping RunningInside,stopRunning: @escaping StopRunning,+ registrationAtLogin: @escaping RegistrationAtLogin,moveToTrash: @escaping @Sendable (URL) throws -> URL,ownMoves: OwnTrashMoves,journal: RemovalJournal?@@ -305,6 +317,7 @@ public struct TrashService: Sendable {self.putBackDockTiles = putBackDockTilesself.runningInside = runningInsideself.stopRunning = stopRunning+ self.registrationAtLogin = registrationAtLoginself.moveToTrash = moveToTrashself.ownMoves = ownMovesself.journal = journal@@ -449,6 +462,11 @@ public struct TrashService: Sendable {emptiedFoldersNamed names: Set<String> = []) async -> TrashResult {let removal = UUID()+ // Asked before anything moves: a job stopped so its app could move is no longer named by launchd.+ var registrations: [URL: StartsAtLogin.Registration] = [:]+ for app in apps {+ registrations[app] = await registrationAtLogin(app)+ }var result = apps.isEmpty? TrashResult(): await trash(apps, usingHelperFor: privilegedURLs, removal: removal, lettingTheirProgramsRun: running)@@ -457,6 +475,11 @@ public struct TrashService: Sendable {lettingTheirProgramsRun: running)let moved = Set(result.trashed.map(\.originalURL))+ // With another copy installed, macOS may start the items from that copy.+ result.startsFromTheTrash = apps.filter { app in+ guard moved.contains(app), let registration = registrations[app] else { return false }+ return AppInspector.applicationURLs(forBundleIdentifier: registration.identifier).isEmpty+ }let rest = files(Set(apps.filter { !moved.contains($0) }))guard !rest.isEmpty else {await startAgain(stopped, unlessMoved: [])diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swiftindex 3a83ccfd..e17a9f4c 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift@@ -77,6 +77,21 @@ struct CommandLineTests {#expect(UninstallCommand.dockNote(for: app, isInTheDock: true, keeping: true) == nil)}+ @Test func saysWhatMacOSStillStartsFromTheTrash() {+ let app = InstalledApp(+ url: URL(filePath: "/Applications/Example.app", directoryHint: .isDirectory),+ bundleIdentifier: "org.example.app", name: "Example"+ )+ let trashed = URL(filePath: "/Users/me/.Trash/Example.app")+ var noted = TrashResult(trashed: [TrashedItem(originalURL: app.url, trashedURL: trashed, date: .now)])+ noted.startsFromTheTrash = [app.url]++ let note = UninstallCommand.startsFromTheTrashNote(for: app, after: noted)+ #expect(note?.hasPrefix("macOS still starts the background items of Example from the Trash") == true)+ #expect(note?.contains("Login Items & Extensions") == true)+ #expect(UninstallCommand.startsFromTheTrashNote(for: app, after: TrashResult()) == nil)+ }+/// A dry run moves nothing, so what would stop the move now, an app still running or a permission missing, is/// said beside the plan instead of standing in for it.@Test func aDryRunShowsThePlanAndSaysWhatWouldStopTheMove() throws {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/StartsAtLoginTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/StartsAtLoginTests.swiftnew file mode 100644index 00000000..53c4471f--- /dev/null+++ b/Packages/PeelCore/Tests/PeelCoreTests/StartsAtLoginTests.swift@@ -0,0 +1,243 @@+import Foundation+@testable import PeelCore+import Testing++struct StartsAtLoginTests {+ /// `launchctl print gui/<uid>/<label>` of a login item an app registered, as macOS 27 writes it, names made up.+ private static let registeredLoginItem = """+ gui/501/org.example.tide.helper = {+ \tactive count = 3+ \tpath = (submitted by smd.341)+ \ttype = Submitted+ \tmanaged_by = com.apple.xpc.ServiceManagement+ \tstate = running++ \tprogram identifier = org.example.tide.helper (mode: 1)+ \tparent bundle identifier = org.example.tide+ \tparent bundle version = 1+ \tBTM uuid = BDB2A4AF-9245-448E-B8A7-EBF0A6967323+ \tinherited environment = {+ \t\tSSH_AUTH_SOCK => /var/run/com.apple.launchd.8xrz08QAWw/Listeners+ \t}+ }+ """++ private static let agentFromAFile = """+ gui/501/org.example.tide.agent = {+ \tactive count = 0+ \tpath = /Users/someone/Library/LaunchAgents/org.example.tide.agent.plist+ \ttype = LaunchAgent+ \tstate = not running++ \tprogram = /Applications/Tide.app/Contents/MacOS/agent+ }+ """++ private func plist(_ values: [String: Any]) throws -> Data {+ try PropertyListSerialization.data(fromPropertyList: values, format: .xml, options: 0)+ }++ private func app(in directory: borrowing TemporaryDirectory, identifier: String = "org.example.tide") throws -> URL {+ let app = try directory.directory("home/Applications/Tide.app")+ _ = try directory.file("home/Applications/Tide.app/Contents/Info.plist", contents: plist(["CFBundleIdentifier": identifier]))+ _ = try directory.file(+ "home/Applications/Tide.app/Contents/Library/LoginItems/TideHelper.app/Contents/Info.plist",+ contents: plist(["CFBundleIdentifier": "org.example.tide.helper"])+ )+ _ = try directory.file("home/Applications/Tide.app/Contents/Library/LoginItems/ReadMe.txt", contents: Data())+ _ = try directory.file(+ "home/Applications/Tide.app/Contents/Library/LoginItems/Other.bundle/Contents/Info.plist",+ contents: plist(["CFBundleIdentifier": "org.example.tide.other"])+ )+ let agents = "home/Applications/Tide.app/Contents/Library/LaunchAgents"+ _ = try directory.file("\(agents)/org.example.tide.agent.plist", contents: plist(["Label": "org.example.tide.agent"]))+ _ = try directory.file("\(agents)/apples.plist", contents: plist(["Label": "com.apple.example"]))+ _ = try directory.file("\(agents)/odd.plist", contents: plist(["Label": "../system/org.example.odd"]))+ _ = try directory.file("\(agents)/org.example.tide.backup", contents: plist(["Label": "org.example.tide.backup"]))+ _ = try directory.file("\(agents)/same.plist", contents: plist(["Label": "org.example.tide.helper"]))+ _ = try directory.file(+ "home/Applications/Tide.app/Contents/Library/LaunchDaemons/org.example.tide.daemon.plist",+ contents: plist(["Label": "org.example.tide.daemon"])+ )+ return app+ }++ @Test func labelsAreEachLoginItemsIdentifierAndEachAgentsLabel() throws {+ let directory = try TemporaryDirectory()+ let app = try app(in: directory)++ #expect(StartsAtLogin.labels(declaredBy: app) == ["org.example.tide.helper", "org.example.tide.agent"])+ }++ @Test func asksAboutAtMostSoManyLabels() throws {+ let directory = try TemporaryDirectory()+ let app = try app(in: directory)+ for index in 0..<StartsAtLogin.mostAsked {+ let label = "org.example.tide.extra\(index)"+ _ = try directory.file(+ "home/Applications/Tide.app/Contents/Library/LaunchAgents/\(label).plist",+ contents: plist(["Label": label])+ )+ }++ let labels = StartsAtLogin.labels(declaredBy: app)+ #expect(labels.count == StartsAtLogin.mostAsked)+ #expect(labels.first == "org.example.tide.helper")+ }++ @Test func aJobIsTheAppsWhenServiceManagementManagesItForThatApp() {+ let registered = Launchctl.answer(status: 0, output: Self.registeredLoginItem)+ let unmanaged = Launchctl.answer(+ status: 0,+ output: Self.registeredLoginItem.replacingOccurrences(of: "\tmanaged_by = com.apple.xpc.ServiceManagement\n", with: "")+ )+ let fromAFile = Launchctl.answer(status: 0, output: Self.agentFromAFile)+ let gone = Launchctl.answer(status: 113, output: "Bad request.\nCould not find service")++ #expect(StartsAtLogin.isRegistered(registered, for: "org.example.tide"))+ #expect(StartsAtLogin.isRegistered(registered, for: "ORG.EXAMPLE.TIDE"))+ #expect(!StartsAtLogin.isRegistered(registered, for: "org.example.other"))+ #expect(!StartsAtLogin.isRegistered(unmanaged, for: "org.example.tide"))+ #expect(!StartsAtLogin.isRegistered(fromAFile, for: "org.example.tide"))+ #expect(!StartsAtLogin.isRegistered(gone, for: "org.example.tide"))+ }++ @Test func launchdHoldsNothingForAnAppThatRegisteredNothing() async throws {+ let directory = try TemporaryDirectory()+ let app = try app(in: directory)++ #expect(await StartsAtLogin.registration(of: app) == nil)+ }++ /// Records where each app was when its registration was asked about.+ private actor Asked {+ private(set) var whileInPlace: [Bool] = []++ func record(_ app: URL) {+ whileInPlace.append(FileManager.default.fileExists(atPath: app.path(percentEncoded: false)))+ }+ }++ private func service(+ in directory: borrowing TemporaryDirectory,+ stuck: URL? = nil,+ asked: Asked = Asked(),+ registration: StartsAtLogin.Registration?+ ) throws -> TrashService {+ let trash = try directory.directory("home/.Trash")+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)+ )+ return TrashService(+ environment: environment,+ registrationAtLogin: { app in+ await asked.record(app)+ return registration+ }+ ) { url in+ guard url != stuck else { throw CocoaError(.fileWriteNoPermission) }+ let destination = trash.appending(path: url.lastPathComponent)+ try FileManager.default.moveItem(at: url, to: destination)+ return destination+ }+ }++ @Test func notesAnAppThatMovedWithItsBackgroundItemsRegisteredAskedBeforeItMoved() async throws {+ let directory = try TemporaryDirectory()+ let app = try app(in: directory)+ let asked = Asked()+ let registration = StartsAtLogin.Registration(identifier: "org.example.tide", labels: ["org.example.tide.helper"])+ let service = try service(in: directory, asked: asked, registration: registration)++ let result = await service.trash(+ apps: [app], thenFiles: { _ in [] }, usingHelperFor: [], lettingTheirProgramsRun: []+ )++ #expect(result.trashed.map(\.originalURL) == [app])+ #expect(result.startsFromTheTrash == [app])+ #expect(await asked.whileInPlace == [true])+ }++ @Test func notesNoAppThatStayed() async throws {+ let directory = try TemporaryDirectory()+ let app = try app(in: directory)+ let registration = StartsAtLogin.Registration(identifier: "org.example.tide", labels: ["org.example.tide.helper"])+ let service = try service(in: directory, stuck: app, registration: registration)++ let result = await service.trash(+ apps: [app], thenFiles: { _ in [] }, usingHelperFor: [], lettingTheirProgramsRun: []+ )++ #expect(result.failures.map(\.url) == [app])+ #expect(result.startsFromTheTrash.isEmpty)+ }++ @Test func notesNoAppWithNothingRegistered() async throws {+ let directory = try TemporaryDirectory()+ let app = try app(in: directory)+ let service = try service(in: directory, registration: nil)++ let result = await service.trash(+ apps: [app], thenFiles: { _ in [] }, usingHelperFor: [], lettingTheirProgramsRun: []+ )++ #expect(result.trashed.map(\.originalURL) == [app])+ #expect(result.startsFromTheTrash.isEmpty)+ }++ @Test func notesEachAppOfSeveralThatMovedWithItsItemsRegistered() async throws {+ let directory = try TemporaryDirectory()+ let trash = try directory.directory("home/.Trash")+ var apps: [URL] = []+ for name in ["Tide", "Ebb", "Moor"] {+ let app = try directory.directory("home/Applications/\(name).app")+ _ = try directory.file(+ "home/Applications/\(name).app/Contents/Info.plist",+ contents: plist(["CFBundleIdentifier": "org.example.\(name.lowercased())"])+ )+ apps.append(app)+ }+ let (tide, ebb, moor) = (apps[0], apps[1], apps[2])+ let service = TrashService(+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)+ ),+ registrationAtLogin: { app in+ guard app != ebb else { return nil }+ let name = app.deletingPathExtension().lastPathComponent.lowercased()+ return StartsAtLogin.Registration(identifier: "org.example.\(name)", labels: ["org.example.\(name).helper"])+ }+ ) { url in+ guard url != moor else { throw CocoaError(.fileWriteNoPermission) }+ let destination = trash.appending(path: url.lastPathComponent)+ try FileManager.default.moveItem(at: url, to: destination)+ return destination+ }++ let result = await service.trash(+ apps: apps, thenFiles: { _ in [] }, usingHelperFor: [], lettingTheirProgramsRun: []+ )++ #expect(Set(result.trashed.map(\.originalURL)) == [tide, ebb])+ #expect(result.failures.map(\.url) == [moor])+ #expect(result.startsFromTheTrash == [tide])+ }++ /// Calculator is on every Mac, so an app that shares its identifier has another copy installed, which macOS may+ /// start the items from instead.+ @Test func notesNoAppWhoseIdentifierAnotherInstalledAppHas() async throws {+ let directory = try TemporaryDirectory()+ let app = try app(in: directory, identifier: "com.apple.calculator")+ let registration = StartsAtLogin.Registration(identifier: "com.apple.calculator", labels: ["org.example.tide.helper"])+ let service = try service(in: directory, registration: registration)++ let result = await service.trash(+ apps: [app], thenFiles: { _ in [] }, usingHelperFor: [], lettingTheirProgramsRun: []+ )++ #expect(result.trashed.map(\.originalURL) == [app])+ #expect(result.startsFromTheTrash.isEmpty)+ }+}diff --git a/Peel/Model/RemovalOutcome.swift b/Peel/Model/RemovalOutcome.swiftindex 098eda8b..e3fab8d5 100644--- a/Peel/Model/RemovalOutcome.swift+++ b/Peel/Model/RemovalOutcome.swift@@ -21,30 +21,42 @@ final class RemovalOutcome {private(set) var keptTheirFiles: [String] = []/// The audio drivers that moved, which macOS keeps running until the Mac restarts.private(set) var driversAwaitingARestart: [String] = []+ /// The apps that moved whose background items macOS still starts at login from the Trash (`TrashResult`).+ private(set) var appsStartingFromTheTrash: [String] = []private(set) var movedCount = 0- var isEmpty: Bool { failures.isEmpty && privacy.isEmpty && appsToQuit.isEmpty && driversAwaitingARestart.isEmpty }+ var isEmpty: Bool {+ failures.isEmpty && privacy.isEmpty && appsToQuit.isEmpty && driversAwaitingARestart.isEmpty+ && appsStartingFromTheTrash.isEmpty+ }- /// Keeps what the removal could not do, and the audio drivers a restart finishes removing, for the alert.+ /// Keeps what the removal could not do, and what a restart or an emptied Trash finishes, for the alert./// `privacy` is every reset the removal ran, and `PrivacyReset.worthTelling` picks which of them to tell. A/// removal with nothing to tell changes nothing.func report(_ result: TrashResult,privacy resets: [(app: InstalledApp, result: PrivacyReset.Result)] = [],appsToQuit: [String] = [],- keptTheirFiles: [String] = []+ keptTheirFiles: [String] = [],+ startingFromTheTrash: [String] = []) {let privacy = PrivacyReset.worthTelling(resets, after: result).map {Privacy(app: $0.app.name, result: $0.result)}let drivers = AudioDrivers.awaitingARestart(after: result)- guard !result.failures.isEmpty || !privacy.isEmpty || !appsToQuit.isEmpty || !drivers.isEmpty else { return }+ guard+ !result.failures.isEmpty || !privacy.isEmpty || !appsToQuit.isEmpty || !drivers.isEmpty+ || !startingFromTheTrash.isEmpty+ else { return }failures = result.failuresmovedCount = result.trashed.countself.privacy = privacyself.appsToQuit = appsToQuitself.keptTheirFiles = keptTheirFilesdriversAwaitingARestart = drivers+ // Two copies of an app share its name and its background items.+ var named: Set<String> = []+ appsStartingFromTheTrash = startingFromTheTrash.filter { named.insert($0).inserted }}func clear() {@@ -54,5 +66,6 @@ final class RemovalOutcome {appsToQuit = []keptTheirFiles = []driversAwaitingARestart = []+ appsStartingFromTheTrash = []}}diff --git a/Peel/Views/AppDetailView.swift b/Peel/Views/AppDetailView.swiftindex 8224c2b9..7eb7611e 100644--- a/Peel/Views/AppDetailView.swift+++ b/Peel/Views/AppDetailView.swift@@ -480,7 +480,12 @@ struct AppDetailView: View {let privacy = await PrivacyReset.reset(resetting(request.urls), beforeMovingWith: service)let result = await plan.move(request)let keptItsFiles = plan.uninstallation?.keptItsFiles(after: result, selection: request.urls) == true- outcome.report(result, privacy: privacy, keptTheirFiles: keptItsFiles ? [plan.app.name] : [])+ outcome.report(+ result,+ privacy: privacy,+ keptTheirFiles: keptItsFiles ? [plan.app.name] : [],+ startingFromTheTrash: result.startsFromTheTrash.contains(plan.app.url) ? [plan.app.name] : []+ )if plan.removesDockTile, result.trashed.contains(where: { $0.originalURL == plan.app.url }) {_ = await DockTiles().takeOut([plan.app.url])}diff --git a/Peel/Views/MultipleAppsView.swift b/Peel/Views/MultipleAppsView.swiftindex 32ec34f7..d375060f 100644--- a/Peel/Views/MultipleAppsView.swift+++ b/Peel/Views/MultipleAppsView.swift@@ -358,7 +358,12 @@ struct MultipleAppsView: View {let privacy = await PrivacyReset.reset(resetting(request.urls), beforeMovingWith: service)let result = await plan.move(request)let kept = plan.bulk?.appsThatKeptTheirFiles(after: result, selection: request.urls) ?? []- outcome.report(result, privacy: privacy, keptTheirFiles: kept.map(\.name))+ outcome.report(+ result,+ privacy: privacy,+ keptTheirFiles: kept.map(\.name),+ startingFromTheTrash: plan.apps.filter { result.startsFromTheTrash.contains($0.url) }.map(\.name)+ )if plan.removesDockTiles {let moved = Set(result.trashed.map(\.originalURL))// Asked of every app that moved, since one opened after the last scan has a tile now.diff --git a/Peel/Views/RemovalFailureAlert.swift b/Peel/Views/RemovalFailureAlert.swiftindex a5c35f62..96743934 100644--- a/Peel/Views/RemovalFailureAlert.swift+++ b/Peel/Views/RemovalFailureAlert.swift@@ -1,10 +1,12 @@import AppKitimport PeelCore+import ServiceManagementimport SwiftUI/// The alert every tool shows when a removal fails for some items: which ones, and why, with a button that-/// fixes the cause when there is one. It also reports the privacy resets worth telling about, and the audio drivers-/// that wait for a restart, since two alerts cannot be up at once.+/// fixes the cause when there is one. It also reports the privacy resets worth telling about, the audio drivers that+/// wait for a restart, and on macOS 27 the background items macOS still starts from the Trash, since two alerts cannot+/// be up at once.struct RemovalFailureAlert: ViewModifier {/// How many items the alert lists by path. The rest are only counted, to keep the alert short.static let mostListed = 4@@ -20,6 +22,9 @@ struct RemovalFailureAlert: ViewModifier {if needsHelper {Button("Open Peel Settings") { SettingsPane.helper.open(with: openSettings) }}+ if #available(macOS 27, *), !outcome.appsStartingFromTheTrash.isEmpty {+ Button("Open Login Items & Extensions") { SMAppService.openSystemSettingsLoginItems() }+ }if !outcome.failures.isEmpty {Button("Copy Details") { copyDetails() }}@@ -40,6 +45,12 @@ struct RemovalFailureAlert: ViewModifier {}private var title: Text {+ if #available(macOS 27, *), !outcome.appsStartingFromTheTrash.isEmpty, outcome.failures.isEmpty,+ outcome.appsToQuit.isEmpty, outcome.privacy.isEmpty {+ return outcome.driversAwaitingARestart.isEmpty+ ? Text("Empty the Trash to finish.")+ : Text("Restart your Mac and empty the Trash to finish.")+ }if outcome.failures.isEmpty, outcome.appsToQuit.isEmpty, outcome.privacy.isEmpty {return Text("Restart your Mac to finish.")}@@ -57,6 +68,9 @@ struct RemovalFailureAlert: ViewModifier {lines.append(String(inflecting: "And ^[\(rest) more item](inflect: true)."))}lines += keptLines + driverLines + extraLines+ if #available(macOS 27, *) {+ lines += trashLines+ }return lines.joined(separator: "\n\n")}@@ -69,6 +83,14 @@ struct RemovalFailureAlert: ViewModifier {: [String(localized: "macOS keeps the audio drivers \(names) running until you restart your Mac.")]}+ /// One line for the apps whose background items macOS still starts from the Trash at each login.+ private var trashLines: [String] {+ let apps = outcome.appsStartingFromTheTrash+ guard !apps.isEmpty else { return [] }+ let names = apps.formatted(.list(type: .and))+ return [String(localized: "macOS still starts the background items of \(names) from the Trash each time you log in, until you empty the Trash.")]+ }+/// A line for each app that stayed, since its files, which wait for it, stayed too and are not listed.private var keptLines: [String] {outcome.keptTheirFiles.map { String(localized: "\($0) stayed, and so did its files.") }@@ -86,8 +108,11 @@ struct RemovalFailureAlert: ViewModifier {/// Copies every item with its full path, since the alert lists only the first few and its text can't be/// selected.private func copyDetails() {- let lines = quitLines + outcome.failures.map { "\($0.url.path(percentEncoded: false))\n\($0.reason.explanation)" }+ var lines = quitLines + outcome.failures.map { "\($0.url.path(percentEncoded: false))\n\($0.reason.explanation)" }+ keptLines + driverLines + extraLines+ if #available(macOS 27, *) {+ lines += trashLines+ }NSPasteboard.general.clearContents()NSPasteboard.general.setString(lines.joined(separator: "\n\n"), forType: .string)}