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
Stop an app's own background programs when they keep it from moving
Țugui Dragoș395d7db1f1bd
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swiftindex ce5823d4..9d54435c 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift@@ -8,7 +8,7 @@ internal import PeelPrivilegedstruct OpenFiles {private enum Hold { case reads, writes, runs }- private typealias File = (names: [String], process: String, hold: Hold, isAnotherAccounts: Bool)+ private typealias File = (names: [String], process: String, pid: pid_t, hold: Hold, isAnotherAccounts: Bool)private let files: [File]/// The program the excluded process runs. Its open files are no hold, but where it runs from is.@@ -28,7 +28,7 @@ struct OpenFiles {guard !paths.isEmpty else { continue }let process = Self.name(of: pid, program: path)let isAnotherAccounts = kill(pid, 0) != 0 && errno == EPERM- files += paths.map { (PathComponents.of($0.path), process, $0.hold, isAnotherAccounts) }+ files += paths.map { (PathComponents.of($0.path), process, pid, $0.hold, isAnotherAccounts) }}self.files = files}@@ -39,6 +39,10 @@ struct OpenFiles {Set(holding(url, lettingItsProgramsRun: lettingItsProgramsRun).map(\.process)).sorted()}+ func processes(holding url: URL, lettingItsProgramsRun: Bool = false) -> Set<pid_t> {+ Set(holding(url, lettingItsProgramsRun: lettingItsProgramsRun).map(\.pid))+ }+/// Why `url` can't move while it is held, or nil when nothing holds it.func refusal(of url: URL, lettingItsProgramsRun: Bool) -> TrashFailure.Reason? {let names = PathComponents.of(PathPattern.canonical(url).path(percentEncoded: false))diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swiftindex 2afcedaf..35e299c5 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift@@ -9,22 +9,78 @@ enum LaunchdCleanup {let plist: URL}+ /// A job launchd runs now whose program sits inside an app: one of the app's own background programs. `plist` is+ /// the file it is started from when that is one launchd reads from a folder, so it can be started again.+ struct Running: Sendable, Hashable {+ let label: String+ let isDaemon: Bool+ let pid: pid_t+ let plist: URL?++ var job: Job? { plist.map { Job(label: label, isDaemon: isDaemon, plist: $0) } }+ }+/// Stops jobs whose configuration has gone, so launchd doesn't keep them running or restart them, and answers/// those it stopped: a job launchd did not have is not one.@concurrentstatic func stop(_ jobs: [Job], canUseHelper: Bool) async -> [Job] {var stopped: [Job] = []- for job in jobs {- if job.isDaemon {- guard canUseHelper, PrivilegedHelper.status == .enabled else { continue }- if await PrivilegedHelper.runDaemonCommand(.bootout, label: job.label) == nil { stopped.append(job) }- } else if await Launchctl.run(["bootout", "gui/\(getuid())/\(job.label)"]).status == 0 {- stopped.append(job)+ for job in jobs where await bootout(job.label, isDaemon: job.isDaemon, canUseHelper: canUseHelper) {+ stopped.append(job)+ }+ return stopped+ }++ /// The jobs running now, in this user's domain and the system's, whose program sits inside `app`. An app Launch+ /// Services opened is a job too (`application.`), which is quit as an app and never stopped as a job.+ @concurrent+ static func running(inside app: URL, environment: SearchEnvironment = .current) async -> [Running] {+ let bundle = PathPattern.comparablePath(of: PathPattern.canonical(app))+ var found: [Running] = []+ for (domain, isDaemon) in [("gui/\(getuid())", false), ("system", true)] {+ let services = Launchctl.parseSystemServices(await Launchctl.run(["print", domain]).output) ?? [:]+ for case let (label, pid?) in services where isAppsOwn(label) {+ guard let program = RunningProgram.path(of: pid),+ PathComponents.isPath(PathPattern.comparablePath(of: URL(filePath: program)), inside: bundle)+ else { continue }+ let path = Launchctl.parseDetails(await Launchctl.run(["print", "\(domain)/\(label)"]).output)?.path+ let plist = path.flatMap { jobs(for: [URL(filePath: $0)], environment: environment).first?.plist }+ found.append(Running(label: label, isDaemon: isDaemon, pid: pid, plist: plist))}}+ return found+ }++ /// Stops `jobs` and answers those it stopped, once their processes have ended or `patience` has passed.+ @concurrent+ static func stop(_ jobs: [Running], canUseHelper: Bool, patience: Duration = .seconds(10)) async -> [Running] {+ let ends = ProcessEnds.of(jobs.map(\.pid))+ var stopped: [Running] = []+ for job in jobs where await bootout(job.label, isDaemon: job.isDaemon, canUseHelper: canUseHelper) {+ stopped.append(job)+ }+ await withTaskGroup(of: Void.self) { group in+ group.addTask { for await _ in ends {} }+ group.addTask { try? await Task.sleep(for: patience) }+ await group.next()+ group.cancelAll()+ }return stopped}+ private static func isAppsOwn(_ label: String) -> Bool {+ !label.hasPrefix("application.") && PrivilegedPathPolicy.isValidLabel(label) && label != HelperIdentity.helperIdentifier+ && !SystemDaemons.shipped.contains(label) && !SystemAgents.shipped.contains(label)+ }++ private static func bootout(_ label: String, isDaemon: Bool, canUseHelper: Bool) async -> Bool {+ if isDaemon {+ guard canUseHelper, PrivilegedHelper.status == .enabled else { return false }+ return await PrivilegedHelper.runDaemonCommand(.bootout, label: label) == nil+ }+ return await Launchctl.run(["bootout", "gui/\(getuid())/\(label)"]).status == 0+ }+@concurrentstatic func start(_ job: Job, canUseHelper: Bool) async {if job.isDaemon {diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swiftindex c6c2156f..c15913cd 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift@@ -110,6 +110,13 @@ extension TrashFailure.Reason {}}+ var isHeldByPrograms: Bool {+ switch self {+ case .heldOpen, .heldByAnotherAccount: true+ default: false+ }+ }+/// A fixed word for the reason, which the refusal log stores. It does not change with the text on screen, so/// an old record still reads.public var name: String {@@ -203,6 +210,8 @@ public struct TrashService: Sendable {typealias ForgetDomains = @Sendable ([URL], _ owner: String?) async -> Voidtypealias MoveThroughHelper = @Sendable ([URL]) async -> TrashResulttypealias PutBackDockTiles = @Sendable (URL) async -> Void+ typealias RunningInside = @Sendable (_ app: URL) async -> [LaunchdCleanup.Running]+ typealias StopRunning = @Sendable ([LaunchdCleanup.Running], _ canUseHelper: Bool) async -> [LaunchdCleanup.Running]let environment: SearchEnvironmentprivate let removalGuard: RemovalGuard@@ -211,6 +220,8 @@ public struct TrashService: Sendable {private let forgetDomains: ForgetDomainsprivate let moveThroughHelper: MoveThroughHelperprivate let putBackDockTiles: PutBackDockTiles+ private let runningInside: RunningInside+ private let stopRunning: StopRunningprivate 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.@@ -226,6 +237,8 @@ public struct TrashService: Sendable {forgetDomains: { await PreferenceCleanup.forgetDomains(for: $0, ownedBy: $1) },moveThroughHelper: Self.moveThroughTheHelper,putBackDockTiles: { await DockTiles().putBack($0) },+ runningInside: { await LaunchdCleanup.running(inside: $0, environment: environment) },+ stopRunning: { await LaunchdCleanup.stop($0, canUseHelper: $1) },moveToTrash: { try Self.moveToSystemTrash($0, refusal: removalGuard.refusal(of:)) },ownMoves: .shared,journal: RemovalJournal(beside: RemovalHistory.defaultURL)@@ -242,6 +255,8 @@ public struct TrashService: Sendable {forgetDomains: @escaping ForgetDomains = { _, _ in },moveThroughHelper: @escaping MoveThroughHelper = Self.asIfThereWereNoHelper,putBackDockTiles: @escaping PutBackDockTiles = { _ in },+ runningInside: @escaping RunningInside = { _ in [] },+ stopRunning: @escaping StopRunning = { _, _ in [] },ownMoves: OwnTrashMoves = OwnTrashMoves(),journal: RemovalJournal? = nil,moveToTrash: @escaping @Sendable (URL) throws -> URL@@ -254,6 +269,8 @@ public struct TrashService: Sendable {forgetDomains: forgetDomains,moveThroughHelper: moveThroughHelper,putBackDockTiles: putBackDockTiles,+ runningInside: runningInside,+ stopRunning: stopRunning,moveToTrash: moveToTrash,ownMoves: ownMoves,journal: journal@@ -268,6 +285,8 @@ public struct TrashService: Sendable {forgetDomains: @escaping ForgetDomains,moveThroughHelper: @escaping MoveThroughHelper,putBackDockTiles: @escaping PutBackDockTiles,+ runningInside: @escaping RunningInside,+ stopRunning: @escaping StopRunning,moveToTrash: @escaping @Sendable (URL) throws -> URL,ownMoves: OwnTrashMoves,journal: RemovalJournal?@@ -279,6 +298,8 @@ public struct TrashService: Sendable {self.forgetDomains = forgetDomainsself.moveThroughHelper = moveThroughHelperself.putBackDockTiles = putBackDockTiles+ self.runningInside = runningInside+ self.stopRunning = stopRunningself.moveToTrash = moveToTrashself.ownMoves = ownMovesself.journal = journal@@ -415,12 +436,22 @@ public struct TrashService: Sendable {var result = apps.isEmpty? TrashResult(): await trash(apps, usingHelperFor: privilegedURLs, removal: removal, lettingTheirProgramsRun: running)+ let stopped = await moveAgain(+ &result, onceTheirJobsStop: 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 }+ guard !rest.isEmpty else {+ await startAgain(stopped, unlessMoved: [])+ return result+ }let more = await trash(rest, usingHelperFor: privilegedURLs, removal: removal, lettingTheirProgramsRun: [])result.trashed += more.trashedresult.failures += more.failures+ let filesMoved = Set(more.trashed.map(\.originalURL))+ result.note(stopped.compactMap(\.job).filter { filesMoved.contains($0.plist) })+ await startAgain(stopped, unlessMoved: filesMoved)// Nobody asked for these folders, so one that stays is no failure, and they are not counted with the rest.for folder in MakersFolders(environment: environment, names: names).above(more.trashed.map(\.originalURL))where MakersFolders.isEmpty(folder) {@@ -433,6 +464,47 @@ public struct TrashService: Sendable {return result}+ /// Moves again each of `apps` that only its own background programs kept from moving, once their jobs are stopped,+ /// and answers the jobs stopped for an app that then moved. Nothing is stopped while anything else holds the app.+ private func moveAgain(+ _ result: inout TrashResult,+ onceTheirJobsStop apps: [URL],+ usingHelperFor privilegedURLs: Set<URL>,+ removal: UUID,+ lettingTheirProgramsRun running: Set<URL>+ ) async -> [LaunchdCleanup.Running] {+ var stoppedForMovedApps: [LaunchdCleanup.Running] = []+ for app in apps {+ guard let index = result.failures.firstIndex(where: { $0.url == app }),+ result.failures[index].reason.isHeldByPrograms+ else { continue }+ let holders = OpenFiles().processes(holding: app, lettingItsProgramsRun: running.contains(app))+ let jobs = await runningInside(app).filter { holders.contains($0.pid) }+ guard !holders.isEmpty, holders.isSubset(of: Set(jobs.map(\.pid))) else { continue }+ let stopped = await stopRunning(jobs, true)+ let again = await trash(+ [app], usingHelperFor: privilegedURLs, removal: removal, lettingTheirProgramsRun: running+ )+ if again.trashed.contains(where: { $0.originalURL == app }) {+ result.failures.remove(at: index)+ result.trashed += again.trashed+ stoppedForMovedApps += stopped+ } else {+ result.failures[index] = again.failures.first { $0.url == app } ?? result.failures[index]+ await startAgain(stopped, unlessMoved: [])+ }+ }+ return stoppedForMovedApps+ }++ /// Starts again each of `jobs` launchd reads from a file that did not move: stopped so their app could move, they+ /// must not stay stopped while their file stays in place.+ private func startAgain(_ jobs: [LaunchdCleanup.Running], unlessMoved moved: Set<URL>) async {+ for job in jobs.compactMap(\.job) where !moved.contains(job.plist) {+ await startJob(job, true)+ }+ }+private func trash(_ urls: [URL],usingHelperFor privilegedURLs: Set<URL>,diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swiftindex cb405301..d495d17e 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift@@ -91,6 +91,132 @@ struct TrashServiceTests {)}+ /// What launchd would have been asked, since a test never asks launchd: the jobs stopped, which end their process+ /// unless `endsTheProcess` is false, and the jobs started again.+ private actor Launchd {+ private(set) var stopped: [String] = []+ private(set) var started: [String] = []+ let endsTheProcess: Bool++ init(endsTheProcess: Bool = true) {+ self.endsTheProcess = endsTheProcess+ }++ func stop(_ jobs: [LaunchdCleanup.Running], ending process: Process) async -> [LaunchdCleanup.Running] {+ stopped += jobs.map(\.label)+ guard endsTheProcess else { return jobs }+ let ends = ProcessEnds.of([process.processIdentifier])+ process.terminate()+ for await _ in ends {}+ return jobs+ }++ func start(_ job: LaunchdCleanup.Job) {+ started.append(job.label)+ }+ }++ private func appRunningItsAgent(+ in directory: borrowing TemporaryDirectory+ ) throws -> (app: URL, agent: Process, plist: URL, job: LaunchdCleanup.Running) {+ let agent = try directory.runningProgram("root/Applications/Agentful.app/Contents/MacOS/agent")+ let plist = try launchdPlist("home/Library/LaunchAgents/org.example.agentful.agent.plist", in: directory)+ let job = LaunchdCleanup.Running(+ label: "org.example.agentful.agent", isDaemon: false, pid: agent.processIdentifier, plist: plist+ )+ return (directory.url.appending(path: "root/Applications/Agentful.app", directoryHint: .isDirectory), agent, plist, job)+ }++ private func service(+ in directory: borrowing TemporaryDirectory,+ launchd: Launchd,+ agent: Process,+ running: [LaunchdCleanup.Running]+ ) throws -> TrashService {+ let trash = try directory.directory("home/.Trash")+ return TrashService(+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)+ ),+ startJob: { job, _ in await launchd.start(job) },+ runningInside: { _ in running },+ stopRunning: { jobs, _ in await launchd.stop(jobs, ending: agent) }+ ) { url in+ let destination = trash.appending(path: url.lastPathComponent)+ try FileManager.default.moveItem(at: url, to: destination)+ return destination+ }+ }++ @Test func stopsTheAppsOwnBackgroundProgramThenMovesTheAppAndItsFiles() async throws {+ let directory = try TemporaryDirectory()+ let (app, agent, plist, job) = try appRunningItsAgent(in: directory)+ defer { agent.terminate() }+ let launchd = Launchd()+ let service = try service(in: directory, launchd: launchd, agent: agent, running: [job])++ let result = await service.trash(+ apps: [app], thenFiles: { stayed in stayed.isEmpty ? [plist] : [] }, usingHelperFor: [],+ lettingTheirProgramsRun: []+ )++ #expect(Set(result.trashed.map(\.originalURL)) == [app, plist])+ #expect(result.failures.isEmpty)+ #expect(result.trashed.first { $0.originalURL == plist }?.stoppedJob == job.label)+ #expect(await launchd.stopped == [job.label])+ #expect(await launchd.started.isEmpty)+ }++ @Test func stopsNothingWhileAProgramThatIsNotTheAppsJobHoldsIt() async throws {+ let directory = try TemporaryDirectory()+ let (app, agent, plist, _) = try appRunningItsAgent(in: directory)+ defer { agent.terminate() }+ let launchd = Launchd()+ let service = try service(in: directory, launchd: launchd, agent: agent, running: [])++ let result = await service.trash(+ apps: [app], thenFiles: { stayed in stayed.isEmpty ? [plist] : [] }, usingHelperFor: [],+ lettingTheirProgramsRun: []+ )++ #expect(result.trashed.isEmpty)+ #expect(result.failures.map(\.url) == [app])+ #expect(await launchd.stopped.isEmpty)+ }++ @Test func startsAgainWhatItStoppedWhenTheAppStillStays() async throws {+ let directory = try TemporaryDirectory()+ let (app, agent, plist, job) = try appRunningItsAgent(in: directory)+ defer { agent.terminate() }+ let launchd = Launchd(endsTheProcess: false)+ let service = try service(in: directory, launchd: launchd, agent: agent, running: [job])++ let result = await service.trash(+ apps: [app], thenFiles: { stayed in stayed.isEmpty ? [plist] : [] }, usingHelperFor: [],+ lettingTheirProgramsRun: []+ )++ #expect(result.trashed.isEmpty)+ #expect(result.failures.map(\.url) == [app])+ #expect(await launchd.started == [job.label])+ }++ @Test func startsAgainAJobWhoseFileStaysOnceTheAppMoved() async throws {+ let directory = try TemporaryDirectory()+ let (app, agent, _, job) = try appRunningItsAgent(in: directory)+ defer { agent.terminate() }+ let launchd = Launchd()+ let service = try service(in: directory, launchd: launchd, agent: agent, running: [job])++ let result = await service.trash(+ apps: [app], thenFiles: { _ in [] }, usingHelperFor: [], lettingTheirProgramsRun: []+ )++ #expect(result.trashed.map(\.originalURL) == [app])+ #expect(await launchd.started == [job.label])+ }+/// A command-line tool's link, and its shell completion's, lead into its app until the app has moved, and the/// helper takes such a link only once it leads nowhere, so the links go to the helper after everything else, in/// whatever order they came.