Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Keep a disabled background job's row within reach after a restart

Țugui Dragoș2d0453e9eecc
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
index 7a97458d..2d4ed11e 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
@@ -60,6 +60,9 @@ public struct BackgroundItem: Sendable, Hashable, Identifiable {
/// True for a job ServiceManagement manages: the person turns it on and off in System Settings > General > Login
/// Items & Extensions, so Peel never disables it.
public var isManagedByServiceManagement = false
+ /// False for an app's job that, once disabled, would leave the list at the next restart: launchd keeps only its
+ /// label, which neither starts with its app's identifier nor is declared in its app's bundle.
+ public var staysListedWhenDisabled = true
public var isOwnerInstalled: Bool { ownerURL != nil }
@@ -94,6 +97,9 @@ public struct BackgroundItem: Sendable, Hashable, Identifiable {
!usesALabelOfMacOS && !isSystemExtension && (!requiresPrivileges || PrivilegedPathPolicy.allowsDaemon(label))
}
+ /// True when Peel may disable the job: not one ServiceManagement manages, and one whose row Enable stays on.
+ public var mayBeDisabled: Bool { canBeControlled && !isManagedByServiceManagement && staysListedWhenDisabled }
+
public var removalRequiresPrivileges: Bool { source == .systemLibrary }
/// True for a job Peel sees only while it is loaded, so once stopped it would leave the list and could not be
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift
index c7ec825f..e35fa4bd 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift
@@ -77,10 +77,10 @@ public enum BackgroundItemActions {
}
/// Why Peel will not switch `item` on or off, or nil. Only System Settings turns off a job ServiceManagement
- /// manages: an override of launchd's alone would leave the two saying different things.
+ /// manages, and a job whose row would leave the list once disabled is never disabled from here.
static func refusal(toSwitch item: BackgroundItem, on isEnabled: Bool) -> Failure? {
if let refusal = refusal(for: item) { return refusal }
- return !isEnabled && item.isManagedByServiceManagement ? .launchctl(HelperRefusal.invalidRequest.rawValue) : nil
+ return !isEnabled && !item.mayBeDisabled ? .launchctl(HelperRefusal.invalidRequest.rawValue) : nil
}
@concurrent
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemOwnership.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemOwnership.swift
index e96ca8e6..85812dbc 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemOwnership.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemOwnership.swift
@@ -86,6 +86,13 @@ public struct BackgroundItemOwnership: Sendable {
return gone.map { Owner(bundleIdentifier: $0, name: nil, url: nil, isConfirmed: false) }
}
+ /// The installed app whose own bundle declares the job `label`: a label launchd still keeps after a restart, when
+ /// the job is no longer loaded and nothing else points to its app.
+ func owner(declaring label: String, kind: BackgroundItem.Kind) -> Owner? {
+ apps.first { StartsAtLogin.declaration(of: label, kind: kind, in: $0.url) != nil }
+ .map { Owner(bundleIdentifier: $0.bundleIdentifier, name: $0.name, url: $0.url) }
+ }
+
/// Whether a job is orphaned: no installed app claims it, and its program is gone from disk or it names
/// none of its own. Labels that start with `com.apple.` or `application.` are never orphaned.
public func isOrphan(label: String, program: String?, owner: Owner?) -> Bool {
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
index ee5cfb07..61a7ec2c 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
@@ -123,18 +123,23 @@ public enum BackgroundItems {
+ (loaded.systemDisabled ?? [:]).map { ($0.key, $0.value, BackgroundItem.Kind.daemon) }
return overrides.compactMap { label, isDisabled, kind in
guard isDisabled, !label.hasPrefix("com.apple."), !label.hasPrefix("application."),
- !known.contains("\(kind.rawValue)/\(label)"), loaded.state(of: label, kind) == .notLoaded,
- let owner = ownership.owner(label: label, associated: [], program: nil), let app = owner.url
+ !known.contains("\(kind.rawValue)/\(label)"), loaded.state(of: label, kind) == .notLoaded
else { return nil }
- let schedule = StartsAtLogin.schedule(of: label, kind: kind, in: app)
+ let byLabel = ownership.owner(label: label, associated: [], program: nil)
+ guard let owner = byLabel?.isInstalled == true ? byLabel : ownership.owner(declaring: label, kind: kind),
+ let app = owner.url
+ else {
+ return nil
+ }
+ let declared = StartsAtLogin.declaration(of: label, kind: kind, in: app)
return BackgroundItem(
label: label,
kind: kind,
source: .app,
plistURL: nil,
program: nil,
- runsAtLoad: schedule.runsAtLoad,
- keepsAlive: schedule.keepsAlive,
+ runsAtLoad: declared?.runsAtLoad,
+ keepsAlive: declared?.keepsAlive ?? nil,
ownerBundleIdentifier: owner.bundleIdentifier,
ownerName: owner.name,
ownerURL: owner.url,
@@ -304,7 +309,7 @@ public enum BackgroundItems {
)
let state = loaded.state(of: candidate.label, candidate.kind)
let registered = details.managedBy == serviceManagement
- ? owner?.url.map { StartsAtLogin.schedule(of: candidate.label, kind: candidate.kind, in: $0) } : nil
+ ? owner?.url.flatMap { StartsAtLogin.declaration(of: candidate.label, kind: candidate.kind, in: $0) } : nil
// launchctl names no program for an app's login item or agent: macOS finds it in the app as it starts it.
let programIsUnnamed = isAnApps && program == nil
let running = if case .running(let pid) = state { RunningProgram.path(of: pid) } else { String?.none }
@@ -316,7 +321,7 @@ public enum BackgroundItems {
plistURL: path,
program: program,
runsAtLoad: job?.runsAtLoad ?? registered?.runsAtLoad,
- keepsAlive: job?.keepsAlive ?? registered?.keepsAlive,
+ keepsAlive: job?.keepsAlive ?? registered?.keepsAlive ?? nil,
ownerBundleIdentifier: owner?.bundleIdentifier,
ownerName: owner?.name,
ownerURL: owner?.url,
@@ -329,6 +334,11 @@ public enum BackgroundItems {
item.runsFromTheTrash = programIsUnnamed && running.map { AppInspector.isInATrash(URL(filePath: $0)) } == true
item.isSystemExtension = program.map { PathComponents.isPath($0, inside: "/Library/SystemExtensions") } == true
item.isManagedByServiceManagement = details.managedBy == serviceManagement
+ if isAnApps, item.canBeControlled, !item.isManagedByServiceManagement {
+ item.staysListedWhenDisabled =
+ ownership.owner(label: candidate.label, associated: [], program: nil)?.isInstalled == true
+ || ownership.owner(declaring: candidate.label, kind: candidate.kind) != nil
+ }
return .item(item)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/StartsAtLogin.swift b/Packages/PeelCore/Sources/PeelCore/Removal/StartsAtLogin.swift
index 7b36d0bd..8862f3bb 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/StartsAtLogin.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/StartsAtLogin.swift
@@ -28,23 +28,28 @@ enum StartsAtLogin {
.prefix(mostAsked))
}
- /// Whether the job `label` that `app` registered starts as it loads and again after it exits, as far as the app's
- /// bundle says: a login item does both and the app itself starts at login (`SMAppService.h`), while an agent or a
- /// daemon says it in its plist.
- static func schedule(
- of label: String, kind: BackgroundItem.Kind, in app: URL
- ) -> (runsAtLoad: Bool?, keepsAlive: Bool?) {
+ /// What `app`'s bundle declares about the job `label`, or nil when it declares no such job: a login item starts
+ /// at login and is started again, the app itself starts at login (`SMAppService.h`), and an agent or a daemon
+ /// says it in its plist.
+ struct Declaration: Equatable {
+ let runsAtLoad: Bool
+ let keepsAlive: Bool?
+ }
+
+ static func declaration(of label: String, kind: BackgroundItem.Kind, in app: URL) -> Declaration? {
let library = app.appending(path: "Contents/Library", directoryHint: .isDirectory)
if kind == .agent {
- if identifier(of: app) == label { return (true, nil) }
+ if identifier(of: app) == label { return Declaration(runsAtLoad: true, keepsAlive: nil) }
let loginItems = entries(of: library.appending(path: "LoginItems", directoryHint: .isDirectory))
.lazy.filter { $0.pathExtension == "app" }.prefix(mostAsked)
- if loginItems.contains(where: { identifier(of: $0) == label }) { return (true, true) }
+ if loginItems.contains(where: { identifier(of: $0) == label }) {
+ return Declaration(runsAtLoad: true, keepsAlive: true)
+ }
}
let folder = library.appending(path: kind == .agent ? "LaunchAgents" : "LaunchDaemons", directoryHint: .isDirectory)
let job = entries(of: folder).lazy.filter { $0.pathExtension == "plist" }.prefix(mostAsked)
.compactMap(JobDefinition.init(contentsOf:)).first { $0.label == label }
- return (job?.runsAtLoad, job?.keepsAlive)
+ return job.map { Declaration(runsAtLoad: $0.runsAtLoad, keepsAlive: $0.keepsAlive) }
}
/// What launchd holds now of what `app` registered, or nil when it holds nothing.
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
index 225ebbc6..d98e18ba 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
@@ -185,10 +185,11 @@ struct BackgroundItemActionsTests {
@Test func aJobServiceManagementManagesIsTurnedOffInSystemSettings() throws {
let label = "org.example.tide.loginhelper"
+ let tide = InstalledApp(url: URL(filePath: "/Applications/Tide.app"), bundleIdentifier: "org.example.tide", name: "Tide")
func item(_ details: Launchctl.JobDetails, disabled: Bool = false) throws -> BackgroundItem {
let found = BackgroundItems.undeclaredItem(
(label, .agent, "gui/501/\(label)"), answer: .details(details),
- ownership: BackgroundItemOwnership(installedApps: []),
+ ownership: BackgroundItemOwnership(installedApps: [tide]),
loaded: .init(user: [label: nil], userDisabled: [label: disabled]), exclusions: .none
)
guard case .item(let item) = found else { throw CocoaError(.featureUnsupported) }
@@ -211,6 +212,60 @@ struct BackgroundItemActionsTests {
#expect(BackgroundItemActions.refusal(toSwitch: other, on: false) == nil)
}
+ @Test func aDisabledJobComesBackWhenItsAppDeclaresIt() throws {
+ let directory = try TemporaryDirectory()
+ func write(_ plist: [String: Any], at path: String) throws {
+ let data = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
+ try directory.file(path, contents: data)
+ }
+ try write(["CFBundleIdentifier": "org.example.postgres2"], at: "Applications/Postgres.app/Contents/Info.plist")
+ try write(
+ ["CFBundleIdentifier": "org.example.postgres2LoginHelper"],
+ at: "Applications/Postgres.app/Contents/Library/LoginItems/PostgresLoginHelper.app/Contents/Info.plist"
+ )
+ let app = InstalledApp(
+ url: directory.url.appending(path: "Applications/Postgres.app"), bundleIdentifier: "org.example.postgres2",
+ name: "Postgres"
+ )
+
+ let items = BackgroundItems.disabledJobs(
+ in: .init(user: [:], system: [:], userDisabled: ["org.example.postgres2LoginHelper": true, "org.example.unknown": true]),
+ listed: [], ownership: BackgroundItemOwnership(installedApps: [app])
+ )
+
+ #expect(items.map(\.label) == ["org.example.postgres2LoginHelper"])
+ #expect(items.first?.ownerURL == app.url)
+ #expect(items.first?.runsAtLoad == true)
+ }
+
+ @Test func aJobWhoseLabelLeadsNowhereIsNotDisabled() throws {
+ let directory = try TemporaryDirectory()
+ let info = try PropertyListSerialization.data(
+ fromPropertyList: ["CFBundleIdentifier": "org.example.tide"], format: .xml, options: 0
+ )
+ try directory.file("Applications/Tide.app/Contents/Info.plist", contents: info)
+ let app = InstalledApp(
+ url: directory.url.appending(path: "Applications/Tide.app"), bundleIdentifier: "org.example.tide", name: "Tide"
+ )
+ let program = app.url.appending(path: "Contents/MacOS/helperd").path(percentEncoded: false)
+ func item(_ label: String) throws -> BackgroundItem {
+ let found = BackgroundItems.undeclaredItem(
+ (label, .agent, "gui/501/\(label)"), answer: .details(.init(path: "(submitted by Tide.42)", program: program)),
+ ownership: BackgroundItemOwnership(installedApps: [app]), loaded: .init(user: [label: nil]),
+ exclusions: .none
+ )
+ guard case .item(let item) = found else { throw CocoaError(.featureUnsupported) }
+ return item
+ }
+
+ let byLabel = try item("org.example.tide.ShipIt")
+ let elsewhere = try item("org.example.helperd")
+
+ #expect(byLabel.ownerBundleIdentifier == "org.example.tide" && byLabel.mayBeDisabled)
+ #expect(elsewhere.ownerBundleIdentifier == "org.example.tide" && !elsewhere.mayBeDisabled)
+ #expect(BackgroundItemActions.refusal(toSwitch: elsewhere, on: false) != nil)
+ }
+
@Test func aDisabledJobLaunchdDoesNotHaveIsEnabledFirst() {
let plist = URL(filePath: "/Users/x/Library/LaunchAgents/com.example.agent.plist")
let disabled = BackgroundItem(
diff --git a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
index cdc4f7df..674c9515 100644
--- a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
+++ b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
@@ -332,14 +332,14 @@ struct BackgroundItemDetailView: View {
/// Start, Stop, Enable, and Disable, which a job Peel may not control, a job whose state Peel could not read, a
/// file macOS can't load, and a job loaded from a file elsewhere don't have. Disabled, that last one would leave
- /// the list at the next logout or restart with nothing left to Enable it from. A job ServiceManagement manages has
- /// only Enable, while launchd keeps it disabled.
+ /// the list at the next logout or restart with nothing left to Enable it from. A job Peel may not disable has only
+ /// Enable, while launchd keeps it disabled.
private var hasOwnControls: Bool {
guard item.canBeControlled, item.state != .unknown, item.source != .otherFile, !item.isUnreadable else {
return false
}
if #available(macOS 27, *), item.isLeftByAGoneApp { return true }
- return !item.isSeenOnlyWhileLoaded || item.isDisabled || !item.isManagedByServiceManagement
+ return !item.isSeenOnlyWhileLoaded || item.isDisabled || item.mayBeDisabled
}
private var controls: some View {
@@ -377,7 +377,7 @@ struct BackgroundItemDetailView: View {
Task { await backgroundItems.perform(isRunning ? .stop : .start, on: item) }
}
}
- if item.isDisabled || !item.isManagedByServiceManagement {
+ if item.isDisabled || item.mayBeDisabled {
Button(item.isDisabled ? "Enable" : "Disable", systemImage: item.isDisabled ? "checkmark.circle" : "minus.circle") {
Task { await backgroundItems.perform(item.isDisabled ? .enable : .disable, on: item) }
}