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
Name Background Items only for a program that page can stop
Țugui Dragoș0e8cdce8c54e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fb9bf107..071cc920 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -281,6 +281,7 @@ its changes the way [Keep a Changelog](https://keepachangelog.com/) suggests.#### Background Items- An excluded app's jobs stay listed, marked Excluded in Settings, and Peel acts on none of them.+- A job an app added has Stop while it runs, and leaves the list until macOS or the app adds it again.- A job macOS hasn't listed yet reads Not listed in System Settings yet.- Before moving an item an installed app added, the question says first that the app may stop working until the item isput back.@@ -314,6 +315,8 @@ its changes the way [Keep a Changelog](https://keepachangelog.com/) suggests.the room the sidebar covered.- A message about what couldn't be read says when the permissions of what it names kept Peel out, in the app andfrom `peel`.+- When a program holds what would move, the message names Background Items only for a job, which that page can stop,+ and otherwise says to quit the program, in the app and from `peel`.- The buttons of a page follow one rule in every language: they stand under its last group at the right, with no boxaround them and no symbols, the main action last, and take a second line at the right where a language's words leaveno room. What concerns one row sits at that row's right end, and a section heading with nothing under it keeps itsdiff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex ef5f5b5e..d8ba2028 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -75031,6 +75031,112 @@}}},+ "It is in use by %@. Quit %@, then try again." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Používá ji %@. Ukončete %@ a zkuste to znovu."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Es wird gerade von %@ verwendet. Beende %@ und versuche es dann erneut."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Está en uso por %@. Sal de %@ antes de volver a intentarlo."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Il est utilisé par %@. Quittez %@, puis réessayez."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "È in uso da %@. Esci da %@, poi riprova."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@で使用中です。%@を終了してから、やり直してください。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@에서 사용 중입니다. %@을(를) 종료한 다음 다시 시도하십시오."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Het wordt gebruikt door %@. Stop %@ en probeer het opnieuw."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Jest używane przez: %@. Zakończ %@, a potem spróbuj ponownie."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Está em uso por %@. Encerre %@ e tente novamente."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Este utilizat de %@. Închideți %@, apoi încercați din nou."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Объект используется: %@. Завершите %@, а затем повторите попытку."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Det används av %@. Avsluta %@ och försök sedan igen."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ tarafından kullanılıyor. %@ programından çıkın, ardından yeniden deneyin."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Його використовує %@. Завершіть %@ та спробуйте ще раз."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "它正在被“%@”使用。请退出“%@”,然后重试。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "它正由%@使用中。請結束%@,然後再試一次。"+ }+ }+ }+ },"It is in use by %@. Run %@, then try again." : {"localizations" : {"cs" : {@@ -188609,6 +188715,112 @@}}},+ "Takes it out of launchd for now. It leaves this list until macOS or its app adds it again." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Prozatím odebere úlohu z launchd. Ze seznamu zmizí, dokud ji systém macOS nebo její aplikace znovu nepřidá."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Entfernt es vorerst aus launchd. Es verschwindet aus dieser Liste, bis macOS oder seine App es wieder hinzufügt."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Lo quita de launchd por ahora. Desaparece de esta lista hasta que macOS o su app lo añadan de nuevo."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Retire cet élément de launchd pour le moment. Il quitte cette liste jusqu’à ce que macOS ou son app l’ajoute de nouveau."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Lo toglie da launchd per ora. Esce da questo elenco finché macOS o la sua app non lo aggiungono di nuovo."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "launchdから一時的に取り除きます。macOSまたはそのアプリが再び追加するまで、このリストには表示されません。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "launchd에서 이 항목을 일단 제거합니다. macOS 또는 해당 앱이 다시 추가할 때까지 이 목록에서 사라집니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Haalt het voorlopig uit launchd. Het verdwijnt uit deze lijst totdat macOS of de app ervan het weer toevoegt."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Na razie usuwa tę rzecz z launchd. Znika ona z tej listy, dopóki macOS lub jej aplikacja nie doda jej ponownie."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Retira o item do launchd por enquanto. Ele sai desta lista até que o macOS ou o app dele o adicione novamente."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Îl scoate din launchd deocamdată. Dispare din această listă până când macOS sau aplicația sa îl adaugă din nou."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Пока убирает его из launchd. Он исчезает из этого списка, пока macOS или его программа не добавит его снова."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Tar bort det ur launchd tills vidare. Det försvinner från listan tills macOS eller dess app lägger till det igen."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Onu şimdilik launchd’den çıkarır. macOS veya uygulaması onu yeniden ekleyene kadar bu listeden kalkar."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Поки що вилучає його з launchd. Він зникає з цього списку, доки macOS або його програма не додасть його знову."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "暂时将此任务从launchd中移除。在macOS或其App再次添加它之前,它不会出现在此列表中。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "暫時將它從launchd中移除。在macOS或其App再次加入它之前,它不會出現在此列表中。"+ }+ }+ }+ },"Takes it out of launchd until the next login or restart. Its file stays where it is." : {"localizations" : {"cs" : {diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swiftindex f5969139..2b347ba5 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift@@ -544,8 +544,12 @@ extension TrashFailure.Reason {case .historyCannotBeWritten: "History can't be written: the disk is full, or Peel's folder can't be written"case .peelRemovesItself: "Peel is removing itself"case .heldOpen(let processes) where processes.count > 1:- "in use by \(processes.map(Output.plain).joined(separator: ", ")); quit them, or stop them in Background Items if they have no window, then try again"+ "in use by \(processes.map(Output.plain).joined(separator: ", ")); quit them, then try again"case .heldOpen(let processes):+ "in use by \(processes.map(Output.plain).joined(separator: ", ")); quit it, then try again"+ case .heldOpenByAJob(let processes) where processes.count > 1:+ "in use by \(processes.map(Output.plain).joined(separator: ", ")); quit them, or stop them in Background Items if they have no window, then try again"+ case .heldOpenByAJob(let processes):"in use by \(processes.map(Output.plain).joined(separator: ", ")); quit it, or stop it in Background Items if it has no window, then try again"case .peelRunsFromIt: "Peel runs from here; only Remove Peel, in the app's Settings > General, removes Peel"case .heldByAnotherAccount(let processes) where processes.count > 1:diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swiftindex bdf885e1..9a3653c7 100644--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift@@ -153,13 +153,17 @@ public struct BackgroundItem: Sendable, Hashable, Identifiable {!isSeenOnlyWhileLoaded && plistURL != nil && !usesALabelOfMacOS && !isExcluded}+ public var isRunning: Bool {+ if case .running = state { true } else { false }+ }+/// Start, Stop, Enable, and Disable, which a job Peel may not control, a job whose state Peel could not read, a/// file named by itself since its label couldn't be read, and a file whose label launchd runs from another file/// don't have. A job loaded from a file elsewhere has only Stop. A job Peel may not disable has only Enable, while/// launchd keeps it disabled.public var offersControls: Bool {guard canBeControlled, state != .unknown, !isNamedByItsFile, !anotherFileIsLoaded else { return false }- if canOnlyBeStopped { return true }+ if canOnlyBeStopped || isRunning { return true }if #available(macOS 27, *), isLeftByAGoneApp { return true }return !isSeenOnlyWhileLoaded || isDisabled || mayBeDisabled}diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swiftindex f88046aa..944aa772 100644--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift@@ -44,6 +44,19 @@ enum Launchctl {return jobs}+ /// The processes of `list` (`parseList`) that run as jobs, neither an open app, which launchd lists under+ /// `application.`, nor one of macOS's own.+ static func runningJobs(in list: [String: Int32?]) -> Set<pid_t> {+ Set(list.compactMap { label, pid in+ label.hasPrefix("application.") || label.hasPrefix("com.apple.") ? nil : pid+ })+ }++ /// The processes launchd runs as jobs of this account right now, none when `launchctl` can't say.+ static func runningJobs() async -> Set<pid_t> {+ await parseList(run(["list"]).output).map(runningJobs(in:)) ?? []+ }+/// Parses the "services = { … }" block `launchctl print` gives for a domain, the system's or a user's: "pid/// exit-status label". Nil when there is no such block.static func parseSystemServices(_ output: String) -> [String: Int32?]? {diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swiftindex 02581446..1cfc6d36 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift@@ -21,10 +21,13 @@ struct OpenFiles {/// The program the excluded process runs. Its open files are no hold, but where it runs from is.private let excludedProgram: [String]?private let attachedImages: [[String]]+ /// The processes launchd runs as jobs, which Background Items can stop.+ private let jobs: Set<pid_t>/// 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(), attachedImages: [String] = []) {+ init(excluding excluded: pid_t? = getpid(), attachedImages: [String] = [], jobs: Set<pid_t> = []) {+ self.jobs = jobsexcludedProgram = excluded.flatMap(RunningProgram.path(of:)).map(PathComponents.of)self.attachedImages = attachedImages.map {PathComponents.of(PathPattern.canonicalWithoutOpening(URL(filePath: $0)).path(percentEncoded: false))@@ -57,17 +60,19 @@ struct OpenFiles {/// A reading of the open files that is made again once it is older than `lifetime`.struct Fresh {private let attachedImages: [String]+ private let jobs: Set<pid_t>private var reading: OpenFilesprivate var read = ContinuousClock.now- init(attachedImages: [String] = []) {+ init(attachedImages: [String] = [], jobs: Set<pid_t> = []) {self.attachedImages = attachedImages- reading = OpenFiles(attachedImages: attachedImages)+ self.jobs = jobs+ reading = OpenFiles(attachedImages: attachedImages, jobs: jobs)}mutating func refusal(of url: URL, lettingItsProgramsRun: Bool) -> TrashFailure.Reason? {if ContinuousClock.now - read > OpenFiles.lifetime {- reading = OpenFiles(attachedImages: attachedImages)+ reading = OpenFiles(attachedImages: attachedImages, jobs: jobs)read = .now}return reading.refusal(of: url, lettingItsProgramsRun: lettingItsProgramsRun)@@ -111,7 +116,8 @@ struct OpenFiles {return Self.refusal(heldBy: holding.map { file inHolder(process: file.process, owner: file.owner,- isMacOSsOwn: programs[file.pid].map(Self.isMacOSsOwn) ?? false, daemon: file.daemon+ isMacOSsOwn: programs[file.pid].map(Self.isMacOSsOwn) ?? false, daemon: file.daemon,+ isAJob: jobs.contains(file.pid))})}@@ -129,6 +135,7 @@ struct OpenFiles {let owner: Ownerlet isMacOSsOwn: Boolvar daemon: BuildDaemon? = nil+ var isAJob = false}/// Why an item held by `holders` can't move, each kind of holder with the step that lets it go.@@ -142,7 +149,8 @@ struct OpenFiles {if case let system = processes(.system), !system.isEmpty { return .heldByAnotherAccount(by: system) }let daemons = named.compactMap(\.daemon)if daemons.count == named.count { return .heldByABuildTool(by: Set(daemons.map(\.rawValue)).sorted()) }- return .heldOpen(by: Set(named.map(\.process)).sorted())+ let programs = Set(named.map(\.process)).sorted()+ return named.contains(where: \.isAJob) ? .heldOpenByAJob(by: programs) : .heldOpen(by: programs)}/// The scripts a process runs when its program is one that runs a script named as an argument (Node.js, Deno,diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swiftindex b9aead65..cacb4a63 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift@@ -90,6 +90,8 @@ public struct TrashFailure: Sendable, Hashable {case peelRemovesItself/// These processes hold a file open in it, and moving it would pull it from under them.case heldOpen(by: [String])+ /// As `heldOpen`, with a background job among the programs, which Background Items can stop.+ case heldOpenByAJob(by: [String])/// Peel itself runs from it or from inside it, and only Remove Peel moves Peel.case peelRunsFromIt/// Processes of another account, root's included, run from it, and neither the person nor Peel may quit them.@@ -126,14 +128,16 @@ extension TrashFailure.Reason {case .historyUnreadable, .historyCannotBeWritten, .peelRemovesItself, .needsHelper: falsecase .guarded, .changedSinceScan, .changeNotKnown, .claimedSinceScan, .lastCopy, .notPermitted, .locked,.movedWithoutATrace,- .somethingElseMoved, .heldOpen, .peelRunsFromIt, .heldByAnotherAccount, .openForAnotherUser,+ .somethingElseMoved, .heldOpen, .heldOpenByAJob, .peelRunsFromIt, .heldByAnotherAccount,+ .openForAnotherUser,.heldByABuildTool, .inUseAsAnInputSource, .inUseByMacOS, .attachedDiskImage, .failed: true}}var isHeldByPrograms: Bool {switch self {- case .heldOpen, .heldByAnotherAccount, .openForAnotherUser, .heldByABuildTool, .inUseAsAnInputSource: true+ case .heldOpen, .heldOpenByAJob, .heldByAnotherAccount, .openForAnotherUser, .heldByABuildTool,+ .inUseAsAnInputSource: truedefault: false}}@@ -156,6 +160,7 @@ extension TrashFailure.Reason {case .historyCannotBeWritten: "history-cannot-be-written"case .peelRemovesItself: "peel-removes-itself"case .heldOpen: "held-open"+ case .heldOpenByAJob: "held-open-by-a-job"case .peelRunsFromIt: "peel-runs-from-it"case .heldByAnotherAccount: "held-by-another-account"case .openForAnotherUser: "open-for-another-user"@@ -172,7 +177,8 @@ extension TrashFailure.Reason {case .guarded(let refusal): refusal?.detailcase .failed(let message): messagecase .somethingElseMoved(let name): name- case .heldOpen(let processes), .heldByAnotherAccount(let processes), .openForAnotherUser(let processes),+ case .heldOpen(let processes), .heldOpenByAJob(let processes), .heldByAnotherAccount(let processes),+ .openForAnotherUser(let processes),.heldByABuildTool(let processes), .inUseByMacOS(let processes):processes.joined(separator: "\n")default: nil@@ -200,6 +206,7 @@ extension TrashFailure.Reason {case "history-cannot-be-written": self = .historyCannotBeWrittencase "peel-removes-itself": self = .peelRemovesItselfcase "held-open": self = .heldOpen(by: (detail ?? "").split(separator: "\n").map(String.init))+ case "held-open-by-a-job": self = .heldOpenByAJob(by: (detail ?? "").split(separator: "\n").map(String.init))case "peel-runs-from-it": self = .peelRunsFromItcase "held-by-another-account":self = .heldByAnotherAccount(by: (detail ?? "").split(separator: "\n").map(String.init))@@ -283,6 +290,7 @@ public struct TrashService: Sendable {typealias MoveThroughHelper = @Sendable ([URL]) async -> TrashResulttypealias PutBackDockTiles = @Sendable (_ items: [URL]) async -> Voidtypealias RunningInside = @Sendable (_ app: URL) async -> [LaunchdCleanup.Running]+ typealias RunningJobs = @Sendable () async -> Set<pid_t>typealias StopRunning = @Sendable ([LaunchdCleanup.Running], _ canUseHelper: Bool) async -> [LaunchdCleanup.Running]typealias RegistrationAtLogin = @Sendable (_ app: URL) async -> StartsAtLogin.Registration?typealias RegisterApp = @Sendable (_ app: URL) async -> Void@@ -296,6 +304,7 @@ public struct TrashService: Sendable {private let putBackDockTiles: PutBackDockTilesprivate let runningInside: RunningInsideprivate let stopRunning: StopRunning+ private let runningJobs: RunningJobsprivate let registrationAtLogin: RegistrationAtLoginprivate let registerApp: RegisterAppprivate let moveToTrash: @Sendable (URL) throws -> URL@@ -315,6 +324,7 @@ public struct TrashService: Sendable {putBackDockTiles: { await DockTiles().putBack($0) },runningInside: { await LaunchdCleanup.running(inside: $0, environment: environment) },stopRunning: { await LaunchdCleanup.stop($0, canUseHelper: $1) },+ runningJobs: { await Launchctl.runningJobs() },// Seen on macOS 27, which is where the note that reads it is shown.registrationAtLogin: { app inguard #available(macOS 27, *) else { return nil }@@ -340,6 +350,7 @@ public struct TrashService: Sendable {putBackDockTiles: @escaping PutBackDockTiles = { _ in },runningInside: @escaping RunningInside = { _ in [] },stopRunning: @escaping StopRunning = { _, _ in [] },+ runningJobs: @escaping RunningJobs = { [] },registrationAtLogin: @escaping RegistrationAtLogin = { _ in nil },registerApp: @escaping RegisterApp = { _ in },ownMoves: OwnTrashMoves = OwnTrashMoves(),@@ -356,6 +367,7 @@ public struct TrashService: Sendable {putBackDockTiles: putBackDockTiles,runningInside: runningInside,stopRunning: stopRunning,+ runningJobs: runningJobs,registrationAtLogin: registrationAtLogin,registerApp: registerApp,moveToTrash: moveToTrash,@@ -374,6 +386,7 @@ public struct TrashService: Sendable {putBackDockTiles: @escaping PutBackDockTiles,runningInside: @escaping RunningInside,stopRunning: @escaping StopRunning,+ runningJobs: @escaping RunningJobs,registrationAtLogin: @escaping RegistrationAtLogin,registerApp: @escaping RegisterApp,moveToTrash: @escaping @Sendable (URL) throws -> URL,@@ -389,6 +402,7 @@ public struct TrashService: Sendable {self.putBackDockTiles = putBackDockTilesself.runningInside = runningInsideself.stopRunning = stopRunning+ self.runningJobs = runningJobsself.registrationAtLogin = registrationAtLoginself.registerApp = registerAppself.moveToTrash = moveToTrash@@ -402,6 +416,10 @@ public struct TrashService: Sendable {func excludes(_ app: InstalledApp) -> Bool { removalGuard.excludes(app) }func excludes(ownerOf item: BackgroundItem) -> Bool { removalGuard.excludes(ownerOf: item) }+ private func readingOfOpenFiles() async -> OpenFiles.Fresh {+ OpenFiles.Fresh(attachedImages: await AttachedDiskImages.paths() ?? [], jobs: await runningJobs())+ }+/// Why every move would be refused now, whatever it is asked to move, or nil when a move may go ahead.public var refusalOfEveryMove: TrashFailure.Reason? {guard knowsTheExclusions else { return .guarded(.exclusionsNotKnown) }@@ -422,7 +440,7 @@ public struct TrashService: Sendable {ofApps apps: [URL],lettingTheirProgramsRun running: Set<URL>) async -> [URL: TrashFailure.Reason] {- let openFiles = OpenFiles()+ let openFiles = OpenFiles(jobs: await runningJobs())var refusals: [URL: TrashFailure.Reason] = [:]for app in apps {if let refusal = refusal(of: app) {@@ -491,7 +509,7 @@ public struct TrashService: Sendable {// 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 }- var openFiles = OpenFiles.Fresh(attachedImages: await AttachedDiskImages.paths() ?? [])+ var openFiles = await readingOfOpenFiles()// Read before the move, while the files are still there to say which jobs they declare.let jobs = LaunchdCleanup.jobs(for: allowed, environment: environment)@@ -542,7 +560,7 @@ public struct TrashService: Sendable {urls.filter(jobFiles.contains).forEach(move)let stopped = await stop(jobs, thatMoved: result, canUseHelper: false)if !stopped.isEmpty {- openFiles = OpenFiles.Fresh(attachedImages: await AttachedDiskImages.paths() ?? [])+ openFiles = await readingOfOpenFiles()}urls.filter { !jobFiles.contains($0) }.forEach(move)ownMoves.ended(landedAt: result.trashed.map(\.trashedURL))@@ -713,7 +731,7 @@ public struct TrashService: Sendable {// answer that never comes can affect. The helper reads no open files, so they are read right before each// request, and again once the last reading is older than `OpenFiles.lifetime`.let limit = HelperRequest.maximumItems- var openFiles = OpenFiles.Fresh(attachedImages: await AttachedDiskImages.paths() ?? [])+ var openFiles = await readingOfOpenFiles()// A job's file goes first, and the job stops with it, so a program only that job runs moves in this pass too.let jobFiles = Set(jobs.map(\.plist))var stopped: [LaunchdCleanup.Job] = []@@ -725,7 +743,7 @@ public struct TrashService: Sendable {if index == 1 {stopped = await stop(jobs, thatMoved: helperResult, canUseHelper: true)if !stopped.isEmpty {- openFiles = OpenFiles.Fresh(attachedImages: await AttachedDiskImages.paths() ?? [])+ openFiles = await readingOfOpenFiles()}}for start in stride(from: 0, to: batch.count, by: limit) {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swiftindex 2c8fabec..d4a7e4cd 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift@@ -54,6 +54,22 @@ struct BackgroundItemActionsTests {)}+ @Test func aJobAnAppAddedCanBeStoppedOnlyWhileItRuns() {+ func added(_ state: BackgroundItem.State) -> BackgroundItem {+ var job = BackgroundItem(+ label: "com.example.agent", kind: .agent, source: .app, plistURL: nil, program: "/Applications/App.app/x",+ runsAtLoad: nil, keepsAlive: nil, ownerBundleIdentifier: "com.example", ownerName: "App",+ ownerURL: URL(filePath: "/Applications/App.app"), isOrphan: false, state: state, isDisabled: false+ )+ job.isManagedByServiceManagement = true+ return job+ }+ #expect(added(.running(pid: 42)).offersControls)+ #expect(added(.running(pid: 42)).isRunning)+ #expect(!added(.loaded).offersControls)+ #expect(!added(.loaded).isRunning)+ }+@Test func stoppingAJobThatHasLeftIsNoFailure() async throws {var left = item(state: .loaded, plist: nil)left.loadsInTheBackgroundSession = truediff --git a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swiftindex 33973c65..ad4b5ddd 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift@@ -1226,8 +1226,9 @@ struct CommandLineTests {}@Test func aRefusalForAProgramUsingTheItemSaysWhatToQuitOrStop() {- #expect(TrashFailure.Reason.heldOpen(by: ["FigmaAgent"]).summary == "in use by FigmaAgent; quit it, or stop it in Background Items if it has no window, then try again")- #expect(TrashFailure.Reason.heldOpen(by: ["FigmaAgent", "java"]).summary == "in use by FigmaAgent, java; quit them, or stop them in Background Items if they have no window, then try again")+ #expect(TrashFailure.Reason.heldOpen(by: ["node", "java"]).summary == "in use by node, java; quit them, then try again")+ #expect(TrashFailure.Reason.heldOpenByAJob(by: ["FigmaAgent"]).summary == "in use by FigmaAgent; quit it, or stop it in Background Items if it has no window, then try again")+ #expect(TrashFailure.Reason.heldOpenByAJob(by: ["FigmaAgent", "java"]).summary == "in use by FigmaAgent, java; quit them, or stop them in Background Items if they have no window, then try again")#expect(TrashFailure.Reason.heldByAnotherAccount(by: ["CtxHelper", "updater"]).summary == "in use by CtxHelper, updater, running as another account or as the system, which Peel can't quit; stop them in Background Items or with the app's own uninstaller, then try again")#expect(TrashFailure.Reason.inUseByMacOS(by: ["geod", "appleaccountd"]).summary == "in use by macOS (geod, appleaccountd)")#expect(TrashFailure.Reason.openForAnotherUser(by: ["Spotify"]).summary == "in use by Spotify in another user's account on this Mac; quit it in that account, then try again")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swiftindex 0e7d38ec..30ba493a 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift@@ -187,4 +187,12 @@ struct LaunchctlTests {#expect(BackgroundItemOwnership.bundle(holding: helper)?.identifier == "com.example.app")#expect(BackgroundItemOwnership.bundle(holding: "/usr/bin/true") == nil)}++ @Test func aRunningJobIsNeitherAnOpenAppNorOneOfMacOSs() {+ let jobs = Launchctl.runningJobs(in: [+ "org.example.agent": 12, "org.example.idle": nil, "application.org.example.1.2": 13, "com.apple.Finder": 14,+ ])++ #expect(jobs == [12])+ }}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OpenFilesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OpenFilesTests.swiftindex 753b2053..f73a4be8 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/OpenFilesTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/OpenFilesTests.swift@@ -175,6 +175,15 @@ struct OpenFilesTests {#expect(OpenFiles.refusal(heldBy: []) == nil)}+ @Test func onlyAJobIsSaidToStopInBackgroundItems() {+ let program = OpenFiles.Holder(process: "node", owner: .thisAccount, isMacOSsOwn: false)+ let job = OpenFiles.Holder(process: "agent", owner: .thisAccount, isMacOSsOwn: false, isAJob: true)++ #expect(OpenFiles.refusal(heldBy: [program]) == .heldOpen(by: ["node"]))+ #expect(OpenFiles.refusal(heldBy: [job]) == .heldOpenByAJob(by: ["agent"]))+ #expect(OpenFiles.refusal(heldBy: [program, job]) == .heldOpenByAJob(by: ["agent", "node"]))+ }+@Test func aBuildToolsDaemonIsNamedByItsToolWithTheCommandThatStopsIt() throws {let directory = try TemporaryDirectory()let log = try directory.file("home/.gradle/daemon/9.2/daemon-1.out.log")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swiftindex f44f6c93..73ebe03a 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift@@ -368,7 +368,7 @@ struct RefusalLogTests {.guarded(nil), .changedSinceScan, .changeNotKnown, .claimedSinceScan, .lastCopy, .notPermitted, .locked,.needsHelper,.movedWithoutATrace, .somethingElseMoved(named: "x 2"), .historyUnreadable, .historyCannotBeWritten,- .peelRemovesItself, .heldOpen(by: ["Figma Agent", "java"]), .peelRunsFromIt,+ .peelRemovesItself, .heldOpen(by: ["Figma Agent", "java"]), .heldOpenByAJob(by: ["Figma Agent", "java"]), .peelRunsFromIt,.heldByAnotherAccount(by: ["CtxHelper"]), .openForAnotherUser(by: ["Spotify"]), .heldByABuildTool(by: ["Gradle"]),.inUseAsAnInputSource, .inUseByMacOS(by: ["geod", "appleaccountd"]), .attachedDiskImage, .failed("x"),] + GuardRefusal.allCases.map { .guarded($0) }@@ -379,7 +379,7 @@ struct RefusalLogTests {#expect(Set(reasons.map(\.name)).count == reasons.count)#expect(reasons.allSatisfy { !$0.name.contains(" ") })- #expect(reasons.filter { $0.detail != nil }.count == 7)+ #expect(reasons.filter { $0.detail != nil }.count == 8)}/// History words a refusal from the reason it stored, so every word leads back to its reason, and a word adiff --git a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swiftindex 41a40909..93a043c7 100644--- a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift+++ b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift@@ -431,11 +431,17 @@ struct BackgroundItemDetailView: View {}.help(removeHelp)} else {- // No Start or Stop for a job Peel sees only while it is loaded: once stopped it would leave the list,- // and Peel could not start it again. For an app's job, System Settings also offers only a switch.- if !item.isSeenOnlyWhileLoaded {- let isRunning = if case .running = item.state { true } else { false }- if !isRunning {+ // A job Peel sees only while it is loaded has no Start, since once stopped it leaves the list, and has+ // Stop only while it runs, to let go of what it holds.+ if item.isSeenOnlyWhileLoaded {+ if item.isRunning {+ Button("Stop") {+ Task { await backgroundItems.perform(.stop, on: item) }+ }+ .help(Text("Takes it out of launchd for now. It leaves this list until macOS or its app adds it again."))+ }+ } else {+ if !item.isRunning {Button("Start") {Task { await backgroundItems.perform(.start, on: item) }}diff --git a/Peel/Views/Presentation.swift b/Peel/Views/Presentation.swiftindex 5b941f63..0ffb9dcc 100644--- a/Peel/Views/Presentation.swift+++ b/Peel/Views/Presentation.swift@@ -184,9 +184,11 @@ extension TrashFailure.Reason {case .historyUnreadable: String(localized: "Peel couldn’t read History, and it moves nothing it can’t put back.", bundle: bundle)case .historyCannotBeWritten: String(localized: "Peel couldn’t write to History, because the disk is full or Peel’s folder can’t be written, and it moves nothing it can’t put back.", bundle: bundle)case .peelRemovesItself: String(localized: "Peel is removing itself, so it moves nothing else meanwhile.", bundle: bundle)- case .heldOpen(let processes) where processes.count > 1:- String(localized: "It is in use by \(processes.formatted(.list(type: .and))). Quit \(processes.formatted(.list(type: .and))), or stop them in Background Items if they have no window, then try again.", bundle: bundle)case .heldOpen(let processes):+ String(localized: "It is in use by \(processes.formatted(.list(type: .and))). Quit \(processes.formatted(.list(type: .and))), then try again.", bundle: bundle)+ case .heldOpenByAJob(let processes) where processes.count > 1:+ String(localized: "It is in use by \(processes.formatted(.list(type: .and))). Quit \(processes.formatted(.list(type: .and))), or stop them in Background Items if they have no window, then try again.", bundle: bundle)+ case .heldOpenByAJob(let processes):String(localized: "It is in use by \(processes.formatted(.list(type: .and))). Quit \(processes.formatted(.list(type: .and))), or stop it in Background Items if it has no window, then try again.", bundle: bundle)case .peelRunsFromIt: String(localized: "Peel itself runs from here, and only Remove Peel, in Settings > General, removes Peel.", bundle: bundle)case .heldByAnotherAccount(let processes) where processes.count > 1:diff --git a/SAFETY.md b/SAFETY.mdindex 3c7d081e..d18e69f9 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -167,8 +167,8 @@ it was removing, or, for a removal `peel` made, as an interrupted removal.Right before anything moves, and again once a second while a removal of many items goes on, Peel looks at the filesother programs of yours hold open, at the program each process runs, and at the script a program such as Node.js orPython was given to run, and leaves where it is any file or folder with one of them inside, naming the program and-how to free the item: quit it, or stop it in Background Items when it has no window, since launchd starts such a-program again. A build tool's daemon, which stays after a build and keeps+how to free the item: quit it, or, when launchd runs it as a job, stop it in Background Items, since launchd starts+such a program again. A build tool's daemon, which stays after a build and keepsthe tool's caches open, is named by its tool with the command that tool documents for stopping it: Gradle's andKotlin's stop with `gradle --stop`, Bazel's with `bazel shutdown`, and mvnd's with `mvnd --stop`.Moving a database or a cache from under an agent, a daemon, or a server that is using it would break it. A program of