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.

Say when Background Items may be missing jobs apps added

Țugui Dragoș3c3671e3b4fc
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index f4dc89a9..b217b737 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -91790,6 +91790,112 @@
}
}
},
+ "Part of this list may be missing" : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Část tohoto seznamu může chybět"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ein Teil dieser Liste fehlt möglicherweise"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Puede que falte parte de esta lista"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Il manque peut-être une partie de cette liste"
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Potrebbe mancare una parte di questo elenco"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "このリストの一部が欠けている可能性があります"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "이 목록의 일부가 누락되었을 수 있음"
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Een deel van deze lijst ontbreekt mogelijk"
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Może brakować części tej listy"
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Parte desta lista pode estar faltando"
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O parte din această listă ar putea lipsi"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Часть этого списка может отсутствовать"
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "En del av listan kan saknas"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bu listenin bir kısmı eksik olabilir"
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Може бракувати частини цього списку"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "此列表可能缺少部分内容"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "此列表可能缺少一部分"
+ }
+ }
+ }
+ },
"Peel" : {
"comment" : "The app's name, never translated.",
"shouldTranslate" : false
@@ -182006,6 +182112,324 @@
}
}
},
+ "macOS didn’t list the agents and daemons that apps added, so some may be missing here." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Systém macOS neuvedl agenty a démony, které aplikace přidaly, takže někteří z nich mohou v seznamu chybět."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS hat die von Apps hinzugefügten Agenten und Daemons nicht aufgeführt, daher fehlen hier möglicherweise einige."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS no ha enumerado los agentes y demonios que las apps han añadido, así que puede que aquí falten algunos."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS n’a pas listé les agents et les démons que les apps ont ajoutés : certains peuvent donc manquer ici."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS non ha elencato gli agenti e i daemon aggiunti dalle app, quindi qui potrebbero mancarne alcuni."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "アプリが追加したエージェントとデーモンをmacOSが一覧にしなかったため、ここでは一部が欠けている可能性があります。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS가 앱에서 추가한 에이전트와 데몬을 나열하지 않았으므로 그중 일부가 여기에서 누락되었을 수 있습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS heeft de agents en daemons niet vermeld die door apps zijn toegevoegd, dus sommige ontbreken hier mogelijk."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS nie podał, jakie agenty i demony dodały aplikacje, więc może tu brakować niektórych z nich."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O macOS não listou os agentes e daemons que os apps adicionaram, então alguns podem estar faltando aqui."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS nu a listat agenții și daemonii adăugați de aplicații, așa că unii ar putea lipsi de aici."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS не сообщила, какие агенты и демоны добавлены приложениями, поэтому некоторые из них могут здесь отсутствовать."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS listade inte de agenter och daemons som appar har lagt till, så vissa kan saknas här."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS, uygulamaların eklediği aracıları ve arka plan programlarını listelemedi, bu yüzden bazıları burada eksik olabilir."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS не перелічила агентів і демонів, доданих програмами, тож деяких із них тут може бракувати."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS没有列出App添加的代理和监控程序,因此这里可能缺少其中一些。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS沒有列出App加入的代理程式和服務程式,因此這裡可能缺少其中一些。"
+ }
+ }
+ }
+ },
+ "macOS didn’t list the agents that apps added, so some may be missing here." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Systém macOS neuvedl agenty, které aplikace přidaly, takže někteří z nich mohou v seznamu chybět."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS hat die von Apps hinzugefügten Agenten nicht aufgeführt, daher fehlen hier möglicherweise einige."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS no ha enumerado los agentes que las apps han añadido, así que puede que aquí falten algunos."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS n’a pas listé les agents que les apps ont ajoutés : certains peuvent donc manquer ici."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS non ha elencato gli agenti aggiunti dalle app, quindi qui potrebbero mancarne alcuni."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "アプリが追加したエージェントをmacOSが一覧にしなかったため、ここでは一部が欠けている可能性があります。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS가 앱에서 추가한 에이전트를 나열하지 않았으므로 그중 일부가 여기에서 누락되었을 수 있습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS heeft de agents niet vermeld die door apps zijn toegevoegd, dus sommige ontbreken hier mogelijk."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS nie podał, jakie agenty dodały aplikacje, więc może tu brakować niektórych z nich."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O macOS não listou os agentes que os apps adicionaram, então alguns podem estar faltando aqui."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS nu a listat agenții adăugați de aplicații, așa că unii ar putea lipsi de aici."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS не сообщила, какие агенты добавлены приложениями, поэтому некоторые из них могут здесь отсутствовать."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS listade inte de agenter som appar har lagt till, så vissa kan saknas här."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS, uygulamaların eklediği aracıları listelemedi, bu yüzden bazıları burada eksik olabilir."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS не перелічила агентів, доданих програмами, тож деяких із них тут може бракувати."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS没有列出App添加的代理,因此这里可能缺少其中一些。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS沒有列出App加入的代理程式,因此這裡可能缺少其中一些。"
+ }
+ }
+ }
+ },
+ "macOS didn’t list the daemons that apps added, so some may be missing here." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Systém macOS neuvedl démony, které aplikace přidaly, takže někteří z nich mohou v seznamu chybět."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS hat die von Apps hinzugefügten Daemons nicht aufgeführt, daher fehlen hier möglicherweise einige."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS no ha enumerado los demonios que las apps han añadido, así que puede que aquí falten algunos."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS n’a pas listé les démons que les apps ont ajoutés : certains peuvent donc manquer ici."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS non ha elencato i daemon aggiunti dalle app, quindi qui potrebbero mancarne alcuni."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "アプリが追加したデーモンをmacOSが一覧にしなかったため、ここでは一部が欠けている可能性があります。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS가 앱에서 추가한 데몬을 나열하지 않았으므로 그중 일부가 여기에서 누락되었을 수 있습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS heeft de daemons niet vermeld die door apps zijn toegevoegd, dus sommige ontbreken hier mogelijk."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS nie podał, jakie demony dodały aplikacje, więc może tu brakować niektórych z nich."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O macOS não listou os daemons que os apps adicionaram, então alguns podem estar faltando aqui."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS nu a listat daemonii adăugați de aplicații, așa că unii ar putea lipsi de aici."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS не сообщила, какие демоны добавлены приложениями, поэтому некоторые из них могут здесь отсутствовать."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS listade inte de daemons som appar har lagt till, så vissa kan saknas här."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS, uygulamaların eklediği arka plan programlarını listelemedi, bu yüzden bazıları burada eksik olabilir."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS не перелічила демонів, доданих програмами, тож деяких із них тут може бракувати."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS没有列出App添加的监控程序,因此这里可能缺少其中一些。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS沒有列出App加入的服務程式,因此這裡可能缺少其中一些。"
+ }
+ }
+ }
+ },
"macOS didn’t say what this package installed, so Peel can’t tell what is left." : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
index d41b03d7..1d71bc63 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
@@ -6,12 +6,27 @@ public enum BackgroundItems {
private static let serviceManagement = "com.apple.xpc.ServiceManagement"
private static let concurrentDetailQueries = 8
+ public struct Scan: Sendable {
+ public let items: [BackgroundItem]
+ /// The kinds that may be missing jobs, because `launchctl` answered about them in a form Peel cannot read.
+ public let unanswered: Set<BackgroundItem.Kind>
+ }
+
+ /// A loaded job no file in the three folders declares, as `launchctl` described it.
+ enum Undeclared: Equatable {
+ case item(BackgroundItem)
+ /// Nothing to list: one of macOS's own, an excluded file, or a job that is no longer loaded.
+ case nothing
+ /// `launchctl` answered in a form Peel cannot read, so the job may belong in the list.
+ case unreadable(BackgroundItem.Kind)
+ }
+
@concurrent
public static func scan(
installedApps: [InstalledApp] = [],
environment: SearchEnvironment = .current,
exclusions: Exclusions = .none
- ) async -> [BackgroundItem] {
+ ) async -> Scan {
let ownership = BackgroundItemOwnership(installedApps: installedApps)
let userDomain = "gui/\(getuid())"
async let userList = Launchctl.run(["list"])
@@ -30,9 +45,9 @@ public enum BackgroundItems {
let submitted = undeclared(in: loaded, declared: items, userDomain: userDomain)
- items += await withTaskGroup(of: BackgroundItem?.self) { group in
+ let found = await withTaskGroup(of: Undeclared.self) { group in
var pending = submitted.makeIterator()
- var results: [BackgroundItem] = []
+ var results: [Undeclared] = []
for _ in 0..<concurrentDetailQueries {
guard let next = pending.next() else { break }
group.addTask {
@@ -40,7 +55,7 @@ public enum BackgroundItems {
}
}
while let result = await group.next() {
- if let result { results.append(result) }
+ results.append(result)
if !Task.isCancelled, let next = pending.next() {
group.addTask {
await appSubmittedItem(next, ownership: ownership, loaded: loaded, exclusions: exclusions)
@@ -49,11 +64,33 @@ public enum BackgroundItems {
}
return results
}
+ let undeclared = merged(found, loaded: loaded)
+ items += undeclared.items
items += disabledJobs(in: loaded, listed: items, ownership: ownership)
- return items
- .filter { $0.ownerBundleIdentifier.map(exclusions.excludes(bundleIdentifier:)) != true }
- .sorted { $0.label.localizedStandardCompare($1.label) == .orderedAscending }
+ return Scan(
+ items: items
+ .filter { $0.ownerBundleIdentifier.map(exclusions.excludes(bundleIdentifier:)) != true }
+ .sorted { $0.label.localizedStandardCompare($1.label) == .orderedAscending },
+ unanswered: undeclared.unanswered
+ )
+ }
+
+ /// The items among what `launchctl` said of each undeclared job, and the kinds some of whose jobs may be missing:
+ /// those `loaded` could not read, and those of a job whose answer could not be read.
+ static func merged(
+ _ found: [Undeclared], loaded: Loaded
+ ) -> (items: [BackgroundItem], unanswered: Set<BackgroundItem.Kind>) {
+ var items: [BackgroundItem] = []
+ var unanswered = loaded.unanswered
+ for result in found {
+ switch result {
+ case .item(let item): items.append(item)
+ case .nothing: break
+ case .unreadable(let kind): unanswered.insert(kind)
+ }
+ }
+ return (items, unanswered)
}
/// The loaded jobs no file in the three folders declares, which an app may have submitted and `appSubmittedItem`
@@ -131,6 +168,15 @@ public enum BackgroundItems {
overrides(kind)?[label]
}
+ /// The kinds whose loaded jobs or overrides could not be read, so that jobs an app registered, which are
+ /// known only from them, may be missing.
+ var unanswered: Set<BackgroundItem.Kind> {
+ var kinds: Set<BackgroundItem.Kind> = []
+ if user == nil || userDisabled == nil { kinds.insert(.agent) }
+ if system == nil || systemDisabled == nil { kinds.insert(.daemon) }
+ return kinds
+ }
+
private func overrides(_ kind: BackgroundItem.Kind) -> [String: Bool]? {
kind == .agent ? userDisabled : systemDisabled
}
@@ -214,9 +260,10 @@ public enum BackgroundItems {
ownership: BackgroundItemOwnership,
loaded: Loaded,
exclusions: Exclusions
- ) async -> BackgroundItem? {
- let details = Launchctl.parseDetails(await Launchctl.run(["print", candidate.target]).output)
- return undeclaredItem(candidate, details: details, ownership: ownership, loaded: loaded, exclusions: exclusions)
+ ) async -> Undeclared {
+ let printed = await Launchctl.run(["print", candidate.target])
+ let answer = Launchctl.answer(status: printed.status, output: printed.output)
+ return undeclaredItem(candidate, answer: answer, ownership: ownership, loaded: loaded, exclusions: exclusions)
}
/// The item for a loaded job no file in the three folders declares, from what `launchctl print` said of it: one
@@ -225,11 +272,17 @@ public enum BackgroundItems {
/// not an item, and neither is a file the user excluded.
static func undeclaredItem(
_ candidate: (label: String, kind: BackgroundItem.Kind, target: String),
- details: Launchctl.JobDetails,
+ answer: Launchctl.Answer,
ownership: BackgroundItemOwnership,
loaded: Loaded,
exclusions: Exclusions
- ) -> BackgroundItem? {
+ ) -> Undeclared {
+ let details: Launchctl.JobDetails
+ switch answer {
+ case .details(let read): details = read
+ case .gone: return .nothing
+ case .unreadable: return .unreadable(candidate.kind)
+ }
let isSubmittedByApp = details.path?.hasPrefix("(submitted by") == true
&& details.program.map { !PathComponents.isPath($0, inside: "/System") } == true
let isAnApps = details.managedBy == serviceManagement || isSubmittedByApp
@@ -237,7 +290,7 @@ public enum BackgroundItems {
let isMacOSs = path.map { file in
["/System", "/Library/Apple"].contains { PathComponents.isPath(file.path(percentEncoded: false), inside: $0) }
} ?? false
- guard isAnApps || (path != nil && !isMacOSs), path.map(exclusions.excludes) != true else { return nil }
+ guard isAnApps || (path != nil && !isMacOSs), path.map(exclusions.excludes) != true else { return .nothing }
let job = path.flatMap(JobDefinition.init(contentsOf:))
let program = details.program ?? job?.program
let owner = ownership.owner(
@@ -247,7 +300,7 @@ public enum BackgroundItems {
program: program
)
- return BackgroundItem(
+ return .item(BackgroundItem(
label: candidate.label,
kind: candidate.kind,
source: isAnApps ? .app : .otherFile,
@@ -263,7 +316,7 @@ public enum BackgroundItems {
isDisabled: loaded.override(of: candidate.label, candidate.kind) ?? false,
isOwnerConfirmed: owner?.isConfirmed ?? false,
unusualCommand: UnusualCommand(arguments: job?.arguments ?? program.map { [$0] } ?? [])
- )
+ ))
}
private static func plists(in folder: URL) -> [URL] {
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift
index 82933705..88add967 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift
@@ -76,8 +76,27 @@ enum Launchctl {
return overrides
}
- /// Parses the top-level "key = value" lines of `launchctl print <domain>/<label>`.
- static func parseDetails(_ output: String) -> JobDetails {
+ /// What `launchctl print <domain>/<label>` said of one job.
+ enum Answer: Equatable {
+ case details(JobDetails)
+ /// The job is no longer loaded: it left between the list and the question.
+ case gone
+ /// An answer in a form Peel cannot read.
+ case unreadable
+ }
+
+ /// `launchctl error 113` reads "Could not find specified service" (`man launchctl`, EXIT STATUS).
+ private static let serviceNotFound: Int32 = 113
+
+ static func answer(status: Int32, output: String) -> Answer {
+ if status == serviceNotFound { return .gone }
+ guard status == 0, let details = parseDetails(output) else { return .unreadable }
+ return .details(details)
+ }
+
+ /// Parses the top-level "key = value" lines of `launchctl print <domain>/<label>`. Nil when there is no `path`
+ /// line, which every job's answer has, since another form says nothing.
+ static func parseDetails(_ output: String) -> JobDetails? {
var details = JobDetails()
for line in output.split(whereSeparator: \.isNewline) where line.hasPrefix("\t") && !line.hasPrefix("\t\t") {
let trimmed = line.trimmingCharacters(in: .whitespaces)
@@ -92,6 +111,6 @@ enum Launchctl {
default: break
}
}
- return details
+ return details.path == nil ? nil : details
}
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
index f7b1d0ca..92b95313 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
@@ -311,13 +311,15 @@ struct DeclaredBackgroundItemsTests {
let ownership = BackgroundItemOwnership(installedApps: [])
let stray = try directory.file("home/Desktop/org.example.stray.plist", contents: job("org.example.stray", program: "/bin/sh"))
func item(_ label: String, _ details: Launchctl.JobDetails, exclusions: Exclusions = .none) -> BackgroundItem? {
- BackgroundItems.undeclaredItem(
+ let found = BackgroundItems.undeclaredItem(
(label, .agent, "gui/501/\(label)"),
- details: details,
+ answer: .details(details),
ownership: ownership,
loaded: .init(),
exclusions: exclusions
)
+ guard case .item(let item) = found else { return nil }
+ return item
}
let loadedElsewhere = try #require(item("org.example.stray", .init(path: stray.path(percentEncoded: false), program: "/bin/sh")))
@@ -339,6 +341,29 @@ struct DeclaredBackgroundItemsTests {
)
}
+ /// A job whose answer cannot be read may belong in the list, so its kind is reported; one no longer loaded is gone.
+ @Test func reportsTheKindOfAJobItCouldNotRead() {
+ let ownership = BackgroundItemOwnership(installedApps: [])
+ func found(_ answer: Launchctl.Answer, _ kind: BackgroundItem.Kind) -> BackgroundItems.Undeclared {
+ BackgroundItems.undeclaredItem(
+ ("org.example.job", kind, "gui/501/org.example.job"),
+ answer: answer, ownership: ownership, loaded: .init(), exclusions: .none
+ )
+ }
+
+ #expect(found(.unreadable, .agent) == .unreadable(.agent))
+ #expect(found(.unreadable, .daemon) == .unreadable(.daemon))
+ #expect(found(.gone, .agent) == .nothing)
+ #expect(BackgroundItems.Loaded().unanswered.isEmpty)
+ #expect(BackgroundItems.Loaded(user: nil).unanswered == [.agent])
+ #expect(BackgroundItems.Loaded(userDisabled: nil).unanswered == [.agent])
+ #expect(BackgroundItems.Loaded(system: nil, systemDisabled: nil).unanswered == [.daemon])
+ let merged = BackgroundItems.merged([found(.gone, .agent), found(.unreadable, .daemon)], loaded: .init())
+ #expect(merged.items.isEmpty)
+ #expect(merged.unanswered == [.daemon])
+ #expect(BackgroundItems.merged([], loaded: .init(user: nil)).unanswered == [.agent])
+ }
+
/// A job an app registered is known only while it is loaded, so after Disable and a restart it would leave the
/// list with no way to Enable it. launchd keeps the override by label, and an override that disables a job no row
/// lists yet, of an app that is installed, is a row of its own. Apple's labels and a gone app's stay out.
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift
index bb914999..ad74e693 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift
@@ -351,11 +351,11 @@ struct ExclusionsReachEveryScannerTests {
<plist version="1.0"><dict><key>Label</key><string>com.example.keepme</string></dict></plist>
""".utf8))
- let listed = await BackgroundItems.scan(environment: environment(in: directory))
+ let listed = await BackgroundItems.scan(environment: environment(in: directory)).items
let kept = await BackgroundItems.scan(
environment: environment(in: directory),
exclusions: Exclusions(paths: [plist])
- )
+ ).items
#expect(listed.contains { $0.label == "com.example.keepme" })
#expect(!kept.contains { $0.label == "com.example.keepme" }, "the scanner spells the path with /private and the exclusion does not")
@@ -444,12 +444,12 @@ struct ExclusionsReachEveryScannerTests {
""".utf8))
let app = InstalledApp(url: URL(filePath: "/Applications/Keep Me.app"), bundleIdentifier: "com.example.KeepMe", name: "Keep Me")
- let listed = await BackgroundItems.scan(installedApps: [app], environment: environment(in: directory))
+ let listed = await BackgroundItems.scan(installedApps: [app], environment: environment(in: directory)).items
let kept = await BackgroundItems.scan(
installedApps: [app],
environment: environment(in: directory),
exclusions: Exclusions(bundleIdentifiers: ["com.example.KeepMe"])
- )
+ ).items
#expect(listed.first { $0.label == "com.example.keepme.updater" }?.ownerBundleIdentifier == "com.example.KeepMe")
#expect(!kept.contains { $0.label == "com.example.keepme.updater" })
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift
index 2b27ff0e..45278901 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift
@@ -35,6 +35,8 @@ struct LaunchctlTests {
#expect(Launchctl.parseList("Could not connect to the domain.\n") == nil)
#expect(Launchctl.parseSystemServices("system = {\n\tjobs = {\n\t}\n}\n") == nil)
#expect(Launchctl.parseDisabled("Bad request.\n") == nil)
+ #expect(Launchctl.parseDetails("Bad request.\nCould not find service \"x\" in domain for user gui: 501\n") == nil)
+ #expect(Launchctl.parseDetails("gui/501/org.example.agent = {\n\tstate = not running\n}\n") == nil)
#expect(Launchctl.parseList("PID\tStatus\tLabel\n") == [:])
#expect(Launchctl.parseSystemServices("system = {\n\tservices = {\n\t}\n}\n") == [:])
@@ -67,7 +69,7 @@ struct LaunchctlTests {
#expect(disabled == ["org.example.agent": false, "com.example.daemon": true])
}
- @Test func parsesJobDetails() {
+ @Test func parsesJobDetails() throws {
let output = """
gui/501/com.adguard.mac.adguard.loginhelper = {
\tactive count = 0
@@ -81,12 +83,59 @@ struct LaunchctlTests {
\t}
}
"""
- let details = Launchctl.parseDetails(output)
+ let details = try #require(Launchctl.parseDetails(output))
#expect(details.managedBy == "com.apple.xpc.ServiceManagement")
#expect(details.parentBundleIdentifier == "com.adguard.mac.adguard")
#expect(details.path == "(submitted by smd.524)")
}
+ @Test func tellsAJobThatLeftFromAnAnswerItCannotRead() {
+ let printed = """
+ gui/501/org.example.updater = {
+ \tactive count = 0
+ \tpath = (submitted by smd.332)
+ \ttype = Submitted
+ \tmanaged_by = com.apple.xpc.ServiceManagement
+ \tstate = not running
+
+ \tprogram identifier = Contents/Resources/Updater (mode: 2)
+ \tparent bundle identifier = org.example.app
+ \tparent bundle version = 0
+ \tinherited environment = {
+ \t\tSSH_AUTH_SOCK => /private/tmp/com.apple.launchd.example/Listeners
+ \t}
+
+ \tdomain = gui/501 [100023]
+ \truns = 0
+ \tlast exit code = (never exited)
+ }
+ """
+ let read = Launchctl.JobDetails(
+ path: "(submitted by smd.332)", managedBy: "com.apple.xpc.ServiceManagement",
+ parentBundleIdentifier: "org.example.app"
+ )
+
+ #expect(Launchctl.answer(status: 0, output: printed) == .details(read))
+ #expect(Launchctl.answer(status: 113, output: "Bad request.\nCould not find service \"x\" in domain\n") == .gone)
+ #expect(Launchctl.answer(status: 0, output: "Bad request.\n") == .unreadable)
+ #expect(Launchctl.answer(status: 112, output: "Bad request.\nCould not find domain for user gui: 9\n") == .unreadable)
+ }
+
+ /// Every Mac with someone logged in runs Finder as a job, so this is what `launchctl` really answers here.
+ @Test func readsWhatThisMacsLaunchctlSays() async {
+ let domain = "gui/\(getuid())"
+ let finder = await Launchctl.run(["print", "\(domain)/com.apple.Finder"])
+ let nobody = await Launchctl.run(["print", "\(domain)/org.example.nothing"])
+
+ guard case .details(let details) = Launchctl.answer(status: finder.status, output: finder.output) else {
+ Issue.record("launchctl's answer about Finder could not be read: \(finder.output.prefix(200))")
+ return
+ }
+ #expect(details.path == "/System/Library/LaunchAgents/com.apple.Finder.plist")
+ #expect(details.program == "/System/Library/CoreServices/Finder.app/Contents/MacOS/Finder")
+ #expect(Launchctl.answer(status: nobody.status, output: nobody.output) == .gone)
+ }
+
@Test func readsJobDefinitions() throws {
let job = try #require(JobDefinition([
"Label": "com.example.helper",
diff --git a/Peel/Model/BackgroundItemLibrary.swift b/Peel/Model/BackgroundItemLibrary.swift
index f5ecad22..2c881da8 100644
--- a/Peel/Model/BackgroundItemLibrary.swift
+++ b/Peel/Model/BackgroundItemLibrary.swift
@@ -5,6 +5,8 @@ import PeelCore
@Observable
final class BackgroundItemLibrary {
private(set) var items: [BackgroundItem]?
+ /// The kinds of job some of which may be missing, because macOS answered about them in a form Peel cannot read.
+ private(set) var unanswered: Set<BackgroundItem.Kind> = []
/// The scan this page runs, which a newer one or the Stop button ends.
let scanRun = ScanRun()
var isScanning: Bool { scanRun.isRunning }
@@ -30,7 +32,8 @@ final class BackgroundItemLibrary {
await BackgroundItems.scan(installedApps: installedApps, exclusions: ExclusionsStore.shared.exclusions)
})
else { return }
- items = result
+ items = result.items
+ unanswered = result.unanswered
if let selection, items?.contains(where: { $0.id == selection }) != true {
self.selection = nil
}
@@ -90,3 +93,15 @@ final class BackgroundItemLibrary {
await refresh(installedApps: installedApps)
}
}
+
+extension BackgroundItemLibrary {
+ /// What the page says when some jobs may be missing, or nil when macOS answered about every kind.
+ var unansweredNote: LocalizedStringResource? {
+ switch (unanswered.contains(.agent), unanswered.contains(.daemon)) {
+ case (true, true): "macOS didn’t list the agents and daemons that apps added, so some may be missing here."
+ case (true, false): "macOS didn’t list the agents that apps added, so some may be missing here."
+ case (false, true): "macOS didn’t list the daemons that apps added, so some may be missing here."
+ case (false, false): nil
+ }
+ }
+}
diff --git a/Peel/Model/IntelLibrary.swift b/Peel/Model/IntelLibrary.swift
index fdcde898..4a22430c 100644
--- a/Peel/Model/IntelLibrary.swift
+++ b/Peel/Model/IntelLibrary.swift
@@ -30,7 +30,7 @@ final class IntelLibrary {
return await IntelInspector.scan(
installedApps: installedApps,
plugins: plugins,
- backgroundItems: backgroundItems,
+ backgroundItems: backgroundItems.items,
exclusions: exclusions
)
}) else { return }
diff --git a/Peel/Views/BackgroundItems/BackgroundItemList.swift b/Peel/Views/BackgroundItems/BackgroundItemList.swift
index 2be69b55..420aa6c3 100644
--- a/Peel/Views/BackgroundItems/BackgroundItemList.swift
+++ b/Peel/Views/BackgroundItems/BackgroundItemList.swift
@@ -12,11 +12,22 @@ struct BackgroundItemList: View {
let filtered = filteredItems
List(selection: $backgroundItems.selection) {
+ if let note = backgroundItems.unansweredNote, !filtered.isEmpty {
+ Notice(title: Text("Part of this list may be missing"), detail: Text(note), kind: .note) {}
+ .padding(.vertical, 6)
+ .listRowSeparator(.hidden)
+ }
section(Text("Agents"), items: filtered.filter { $0.kind == .agent })
section(Text("Daemons"), items: filtered.filter { $0.kind == .daemon })
}
.scanState(phase(filtered), isRescanning: isRescanning, scan: backgroundItems.scanRun) {
- if backgroundItems.items?.isEmpty == true {
+ if let note = backgroundItems.unansweredNote, backgroundItems.items?.isEmpty == true {
+ ContentUnavailableView(
+ "macOS Didn’t Answer",
+ systemImage: "exclamationmark.triangle",
+ description: Text(note)
+ )
+ } else if backgroundItems.items?.isEmpty == true {
ContentUnavailableView(
"No Background Items",
systemImage: "gearshape.2",
@@ -32,6 +43,7 @@ struct BackgroundItemList: View {
.announcesScan(
backgroundItems.isScanning,
found: backgroundItems.summary,
+ couldNotLook: backgroundItems.unanswered.isEmpty ? nil : "macOS Didn’t Answer",
wasStopped: backgroundItems.scanRun.wasStopped
)
.toolbar {