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
Never start a background item System Settings keeps from running
Țugui Dragoș8257da73afbe
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex f78af756..ce66a74d 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -445,7 +445,9 @@ macOS asks the user to approve it once. It talks to the app over XPC.`BackgroundItemOwnership`: an app it runs from inside, else the app its label names, a rule Orphaned Files reads too.Start, Stop, Enable, and Disable go to `launchctl`, a daemon's through the helper, never under a label macOS uses forits own jobs (`SystemDaemons`, `SystemAgents`), and a job ServiceManagement manages is turned off only in System- Settings. Move to Trash takes the job's file, and the job is stopped once the file has moved.+ Settings. A job file System Settings keeps from running (`LoginItemsStatus`, from+ `SMAppService.statusForLegacyPlist(at:)`, read with each scan and asked again before a start) is only ever stopped.+ Move to Trash takes the job's file, and the job is stopped once the file has moved.- **Extensions.** `AppExtensions.scan` reads `pluginkit -m -v` and `systemextensionsctl list`. Each ends by counting itsrows, so a listing read short of its count is no answer, and the page says which kind is missing. macOS's ownextensions are left out by where they sit. A system extension's copy, the app it was installed for and its versiondiff --git a/CHANGELOG.md b/CHANGELOG.mdindex c6bf2b40..42230553 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -871,6 +871,9 @@ its changes the way [Keep a Changelog](https://keepachangelog.com/) suggests.- Pressing a button no longer turns every button gray and Rescan into Stop for a moment.- Stop, Unload, and Remove wait for the job's process to end, so a job slow to quit no longer reads as still runningafter launchd let it go.+- A job turned off in System Settings > General > Login Items & Extensions, or waiting for approval there, is no+ longer loaded, run, restarted, or disabled from here, which went over that choice: it can only be stopped, and its+ page says why.#### Extensionsdiff --git a/GUIDE.md b/GUIDE.mdindex a578e3fa..562fa0c2 100644--- a/GUIDE.md+++ b/GUIDE.md@@ -291,11 +291,12 @@ and how many items the others hold.through Peel's helper for those that run as root. One whose programis gone, or whose command looks unusual, says so. Remove takes out a job a deleted app left loaded,and an item whose app is in the Trash says that macOS starts it from there each time you log in, until you empty- the Trash. A job an app gave launchd itself, such as an update's installer, says so. Edit… beside an agent's file in- your own `~/Library/LaunchAgents` opens the file as text: Save moves the file as it was to the Trash, writes yours- in its place, and loads the job again if it was loaded, and putting the old file back from History moves your edit- to the Trash first. Apps set to open at login are in System Settings > General > Login Items & Extensions, not- here.+ the Trash. A job an app gave launchd itself, such as an update's installer, says so. One turned off in System+ Settings > General > Login Items & Extensions, or waiting for approval there, is only ever stopped here, never+ started. Edit… beside an agent's file in your own `~/Library/LaunchAgents` opens the file as text: Save moves the+ file as it was to the Trash, writes yours in its place, and loads the job again if it was loaded, and putting the+ old file back from History moves your edit to the Trash first. Apps set to open at login are in System Settings >+ General > Login Items & Extensions, not here.- **Extensions:** app extensions and system extensions, the app each one came with and whether it is still installed,the choice made for each one, or that macOS decides when nobody chose, which keeps a Finder extension off, and whereit is turned on or off: System Settings for most, Safari > Settings > Extensions for a Safari extension, which Safaridiff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex 53a8d82c..4e5e2711 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -81634,6 +81634,112 @@}}},+ "It needs approval in System Settings > General > Login Items & Extensions, or was turned off there, so macOS doesn’t run it, and Peel doesn’t start it either." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Čeká na schválení v Nastavení systému > Obecné > Aktivace položek a rozšíření při přihlášení, nebo tam byla vypnuta, takže ji nespouští systém macOS ani Peel."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Es benötigt eine Genehmigung unter „Systemeinstellungen“ > „Allgemein“ > „Anmeldeobjekte & Erweiterungen“ oder wurde dort deaktiviert, daher führt macOS es nicht aus, und auch Peel startet es nicht."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Necesita aprobación en Ajustes del Sistema > General > Ítems de inicio y extensiones, o se ha desactivado ahí, así que macOS no lo ejecuta y Peel tampoco lo inicia."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Cet élément nécessite une approbation dans Réglages Système > Général > Ouverture et extensions, ou y a été désactivé : macOS ne l’exécute donc pas, et Peel ne le démarre pas non plus."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Richiede l’approvazione in Impostazioni di Sistema > Generali > Elementi login ed estensioni, oppure è stato disattivato lì, quindi macOS non lo esegue, e nemmeno Peel lo avvia."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "“システム設定”>“一般”>“ログイン項目と機能拡張”で承認が必要か、そこでオフにされているため、macOSはこれを実行せず、Peelも開始しません。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "이 항목은 시스템 설정 > 일반 > 로그인 항목 및 확장 프로그램에서 승인이 필요하거나 꺼져 있으므로, macOS가 실행하지 않으며 Peel도 시작하지 않습니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Het vereist goedkeuring in Systeeminstellingen > Algemeen > Inlogonderdelen en extensies, of is daar uitgeschakeld, dus macOS voert het niet uit, en Peel start het ook niet."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ta rzecz wymaga zatwierdzenia lub została wyłączona w Ustawieniach systemowych > Ogólne > Rzeczy i rozszerzenia otwierane podczas logowania, więc nie uruchamia jej ani macOS, ani Peel."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ele precisa de aprovação em Ajustes do Sistema > Geral > Itens de Início de Sessão e Extensões ou foi desativado ali, por isso o macOS não o executa, e o Peel também não o inicia."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Necesită aprobare în Configurări sistem > General > Lansare la login și extensii sau a fost dezactivat acolo, așa că macOS nu îl rulează și nici Peel nu îl pornește."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Этот объект ожидает разрешения в разделе «Системные настройки» > «Основные» > «Объекты входа и расширения» или был там выключен, поэтому macOS его не запускает, и Peel тоже его не запускает."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Det behöver godkännas i Systeminställningar > Allmänt > Startobjekt och tillägg, eller så har det stängts av där, så macOS kör det inte och Peel startar det inte heller."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Sistem Ayarları > Genel > Oturum Açma Öğeleri ve Genişletmeler bölümünde onay gerekiyor veya orada kapatıldı, bu yüzden macOS onu çalıştırmaz, Peel de başlatmaz."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Його потрібно схвалити в розділі Системні параметри > Загальні > Автозапуск і розширення, або його там вимкнено, тож macOS його не виконує, і Peel його теж не запускає."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "它需要在“系统设置”>“通用”>“登录项与扩展”中获得批准,或已在那里被关闭,因此macOS不会运行它,Peel也不会启动它。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "它需要在「系統設定」>「一般」>「登入項目與延伸功能」中核准,或已在那裡關閉,因此macOS不會執行它,Peel也不會啟動它。"+ }+ }+ }+ },"It no longer builds." : {"localizations" : {"cs" : {diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swiftindex c5a0c210..a688a1af 100644--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift@@ -89,9 +89,12 @@ public struct BackgroundItem: Sendable, Hashable, Identifiable {/// ServiceManagement: System Settings doesn't list it, and launchd forgets it at the next logout or restart.public var isSubmittedByItsApp = falsepublic var anotherFileIsLoaded = false+ public internal(set) var loginItemsStatus: LoginItemsStatus?public var isOwnerInstalled: Bool { ownerURL != nil }+ public var isKeptOffBySystemSettings: Bool { loginItemsStatus.map { !$0.letsItRun } == true }+/// Whether Start runs the job now, whatever its schedule (`launchctl kickstart`), rather than loading it from its/// file, after which macOS runs it as the file says.public var startsAtOnce: Bool { state != .notLoaded || plistURL == nil }@@ -161,8 +164,10 @@ public struct BackgroundItem: Sendable, Hashable, Identifiable {/// elsewhere, still there or gone. Disabled, it would leave the list with nothing to enable it from.public var canOnlyBeStopped: Bool { canBeControlled && source == .otherFile }- /// 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 }+ /// True when Peel may disable the job: not one whose switch is System Settings', and one whose row Enable stays on.+ public var mayBeDisabled: Bool {+ canBeControlled && !isManagedByServiceManagement && !isKeptOffBySystemSettings && staysListedWhenDisabled+ }public var removalRequiresPrivileges: Bool { source == .systemLibrary }@@ -193,6 +198,7 @@ public struct BackgroundItem: Sendable, Hashable, Identifiable {guard canBeControlled, state != .unknown, !isNamedByItsFile, !anotherFileIsLoaded else { return false }if canOnlyBeStopped || isRunning { return true }if isLeftByAGoneApp { return true }+ if isKeptOffBySystemSettings { return state == .loaded || isDisabled }return !isSeenOnlyWhileLoaded || isDisabled || mayBeDisabled}@@ -210,21 +216,25 @@ public struct BackgroundItem: Sendable, Hashable, Identifiable {case load/// Stop under the name the page gives it for a job its gone app left loaded.case remove++ var startsTheJob: Bool { self == .restart || self == .runNow || self == .load }}/// The buttons that change whether the job runs, in the order shown. A job Peel sees only while it is loaded has- /// Stop only while it runs, and a disabled job that isn't loaded has none, since launchd refuses to load it.+ /// Stop only while it runs, and a disabled job that isn't loaded has none, since launchd refuses to load it. A job+ /// System Settings keeps from running is never started: that would go over the person's choice there.public var controls: [Control] {guard offersControls else { return [] }if canOnlyBeStopped { return [.stop] }if isLeftByAGoneApp { return [.remove] }if isSeenOnlyWhileLoaded { return isRunning ? [.stop] : [] }- switch state {- case .running: return [.stop, .restart]- case .loaded: return [.runNow, .unload]- case .notLoaded: return isDisabled ? [] : [.load]- case .unknown: return []+ let controls: [Control] = switch state {+ case .running: [.stop, .restart]+ case .loaded: [.runNow, .unload]+ case .notLoaded: isDisabled ? [] : [.load]+ case .unknown: []}+ return isKeptOffBySystemSettings ? controls.filter { !$0.startsTheJob } : controls}/// Enable and Disable, which a job Peel can only stop, and one its gone app left, don't have.diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swiftindex c64b3fbd..e6813073 100644--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift@@ -14,6 +14,7 @@ public enum BackgroundItemActions {case quarantinedPlist/// launchd does not load a job that is disabled (`bootstrap` answers error 5), so it is enabled first.case disabled+ case turnedOffInSystemSettings}/// Why Peel will not start, stop or switch `item`, or nil. These go by label, so a label macOS itself uses@@ -90,9 +91,15 @@ public enum BackgroundItemActions {return now}+ /// Asks macOS again: the page read the job's status earlier.+ static func refusal(toStart item: BackgroundItem) -> Failure? {+ if let refusal = refusal(for: item) { return refusal }+ return LoginItemsStatus.of(item)?.letsItRun == false ? .turnedOffInSystemSettings : nil+ }+@concurrentpublic static func start(_ item: BackgroundItem) async throws(Failure) {- if let refusal = refusal(for: item) { throw refusal }+ if let refusal = refusal(toStart: item) { throw refusal }switch plan(toStart: asItIsNow(item, isGone: await isGone(item))) {case .blockedByQuarantine:throw .quarantinedPlist@@ -116,7 +123,7 @@ public enum BackgroundItemActions {/// Stops the running job and starts it again at once (`launchctl kickstart -k`).@concurrentpublic static func restart(_ item: BackgroundItem) async throws(Failure) {- if let refusal = refusal(for: item) { throw refusal }+ if let refusal = refusal(toStart: item) { throw refusal }if item.requiresPrivileges {try await runPrivileged(.restart, for: item)} else {diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swiftindex f56e26b7..382047e7 100644--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift@@ -114,6 +114,7 @@ public enum BackgroundItems {items = items.map { item invar item = itemif item.state == .unknown, item.stateNotKnown == nil { item.stateNotKnown = loaded.whyNotKnown(item.kind) }+ item.loginItemsStatus = LoginItemsStatus.of(item)return item}diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/LoginItemsStatus.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/LoginItemsStatus.swiftnew file mode 100644index 00000000..3b8ae36f--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/LoginItemsStatus.swift@@ -0,0 +1,37 @@+import Foundation+import ServiceManagement++public enum LoginItemsStatus: Sendable, Hashable {+ case allowed+ /// Turned off by the person, or waiting for their approval (`SMAppService.h`).+ case turnedOff+ case notListedYet+ case notFound+ case unknown++ /// An answer Peel doesn't know is no leave to run the job.+ public var letsItRun: Bool {+ switch self {+ case .allowed, .notListedYet, .notFound: true+ case .turnedOff, .unknown: false+ }+ }++ /// Nil for a job with no file in a folder launchd reads by itself, the only ones macOS answers for.+ static func of(_ item: BackgroundItem) -> LoginItemsStatus? {+ guard let plist = item.plistURL, item.source == .userLibrary || item.source == .systemLibrary else {+ return nil+ }+ if let standIn { return standIn(plist) }+ return switch SMAppService.statusForLegacyPlist(at: plist) {+ case .enabled: .allowed+ case .requiresApproval: .turnedOff+ case .notRegistered: .notListedYet+ case .notFound: .notFound+ @unknown default: .unknown+ }+ }++ /// For a test: no test can turn a job off in System Settings.+ @TaskLocal static var standIn: (@Sendable (URL) -> LoginItemsStatus)?+}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LoginItemsStatusTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LoginItemsStatusTests.swiftnew file mode 100644index 00000000..4f0b2121--- /dev/null+++ b/Packages/PeelCore/Tests/PeelCoreTests/LoginItemsStatusTests.swift@@ -0,0 +1,108 @@+import Foundation+@testable import PeelCore+import Testing++struct LoginItemsStatusTests {+ private func daemon(+ _ state: BackgroundItem.State, disabled: Bool = false, _ status: LoginItemsStatus?+ ) -> BackgroundItem {+ var job = BackgroundItem(+ label: "org.example.helper", kind: .daemon, source: .systemLibrary,+ plistURL: URL(filePath: "/Library/LaunchDaemons/org.example.helper.plist"),+ program: "/Library/Application Support/Example/helper", runsAtLoad: true, keepsAlive: true,+ ownerBundleIdentifier: nil, ownerName: nil, ownerURL: nil, isOrphan: false, state: state,+ isDisabled: disabled+ )+ job.loginItemsStatus = status+ return job+ }++ @Test func aJobSystemSettingsKeepsFromRunningIsOnlyTakenOutOfLaunchd() {+ for status in [LoginItemsStatus.turnedOff, .unknown] {+ #expect(daemon(.notLoaded, status).controls.isEmpty)+ #expect(!daemon(.notLoaded, status).offersControls)+ #expect(!daemon(.notLoaded, status).offersEnableOrDisable)+ #expect(daemon(.running(pid: 42), status).controls == [.stop])+ #expect(!daemon(.running(pid: 42), status).offersEnableOrDisable)+ #expect(daemon(.loaded, status).controls == [.unload])+ #expect(!daemon(.loaded, status).mayBeDisabled)+ #expect(daemon(.notLoaded, disabled: true, status).controls.isEmpty)+ #expect(daemon(.notLoaded, disabled: true, status).offersEnableOrDisable)+ }+ for status in [nil, .allowed, .notListedYet, .notFound] as [LoginItemsStatus?] {+ #expect(daemon(.notLoaded, status).controls == [.load])+ #expect(daemon(.running(pid: 42), status).controls == [.stop, .restart])+ #expect(daemon(.loaded, status).controls == [.runNow, .unload])+ #expect(daemon(.loaded, status).offersEnableOrDisable)+ }+ let disabled = daemon(.notLoaded, disabled: true, .turnedOff)+ #expect(BackgroundItemActions.refusal(toSwitch: daemon(.loaded, .turnedOff), on: false) != nil)+ #expect(BackgroundItemActions.refusal(toSwitch: disabled, on: true) == nil)+ }++ @Test func startAndRestartAskSystemSettingsAtTheMoment() async throws {+ let directory = try TemporaryDirectory()+ // No file is made, so whatever reached launchctl would find nothing to load.+ let read = BackgroundItem(+ label: "org.example.off", kind: .agent, source: .userLibrary,+ plistURL: directory.url.appending(path: "LaunchAgents/org.example.off.plist"), program: nil,+ runsAtLoad: true, keepsAlive: false, ownerBundleIdentifier: nil, ownerName: nil, ownerURL: nil,+ isOrphan: false, state: .notLoaded, isDisabled: false+ )+ #expect(read.controls == [.load])++ await LoginItemsStatus.$standIn.withValue({ _ in .turnedOff }) {+ await #expect(throws: BackgroundItemActions.Failure.turnedOffInSystemSettings) {+ try await BackgroundItemActions.start(read)+ }+ await #expect(throws: BackgroundItemActions.Failure.turnedOffInSystemSettings) {+ try await BackgroundItemActions.restart(read)+ }+ }+ LoginItemsStatus.$standIn.withValue({ _ in .allowed }) {+ #expect(BackgroundItemActions.refusal(toStart: read) == nil)+ }+ }++ @Test func theScanReadsWhatSystemSettingsSaysOfEachJobFile() async throws {+ let directory = try TemporaryDirectory()+ func job(_ label: String) -> Data {+ Data("""+ <?xml version="1.0" encoding="UTF-8"?>+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+ <plist version="1.0"><dict><key>Label</key><string>\(label)</string></dict></plist>+ """.utf8)+ }+ try directory.file("home/Library/LaunchAgents/org.example.off.plist", contents: job("org.example.off"))+ try directory.file("root/Library/LaunchDaemons/org.example.on.plist", contents: job("org.example.on"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)+ )++ let status: @Sendable (URL) -> LoginItemsStatus = {+ $0.lastPathComponent == "org.example.off.plist" ? .turnedOff : .allowed+ }+ let items = await LoginItemsStatus.$standIn.withValue(status) {+ await BackgroundItems.scan(environment: environment).items+ }++ #expect(items.first { $0.label == "org.example.off" }?.loginItemsStatus == .turnedOff)+ #expect(items.first { $0.label == "org.example.on" }?.loginItemsStatus == .allowed)+ }++ @Test func asksSystemSettingsOnlyAboutAFileInTheFoldersItReads() {+ func job(_ source: BackgroundItem.Source, at path: String?) -> BackgroundItem {+ BackgroundItem(+ label: "org.example.agent", kind: .agent, source: source, plistURL: path.map { URL(filePath: $0) },+ program: "/usr/local/bin/agent", runsAtLoad: true, keepsAlive: false, ownerBundleIdentifier: nil,+ ownerName: nil, ownerURL: nil, isOrphan: false, state: .notLoaded, isDisabled: false+ )+ }+ let agents = URL.homeDirectory.appending(path: "Library/LaunchAgents/org.example.agent.plist")++ #expect(LoginItemsStatus.of(job(.userLibrary, at: agents.path(percentEncoded: false))) != nil)+ #expect(LoginItemsStatus.of(job(.otherFile, at: "/Users/Shared/org.example.agent.plist")) == nil)+ #expect(LoginItemsStatus.of(job(.app, at: nil)) == nil)+ }+}diff --git a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swiftindex cb423101..34364b2f 100644--- a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift+++ b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift@@ -11,16 +11,8 @@ struct BackgroundItemDetailView: View {@Environment(\.openSettings) private var openSettings@State private var isConfirmingTrash = false@State private var isEditing = false- /// Reading this asks macOS, so it is read once per item and scan rather than on every evaluation of `body`.- @State private var legacyStatus: LocalizedStringResource?let item: BackgroundItem- /// The id of the task that reads `legacyStatus`: the item, and the scans that finished, so Rescan asks again.- private struct Look: Hashable {- let item: BackgroundItem.ID- let scans: Int- }-var body: some View {Form {Section {@@ -51,10 +43,10 @@ struct BackgroundItemDetailView: View {}}}- if Self.hasLoginItemsStatus(item) {+ if let status = item.loginItemsStatus {LabeledContent("Login Items & Extensions") {HStack(spacing: 8) {- Text(legacyStatus ?? "Checking…")+ Text(status.words)Button {PrivilegedHelper.openLoginItemsSettings()} label: {@@ -220,6 +212,16 @@ struct BackgroundItemDetailView: View {}}+ if item.isKeptOffBySystemSettings {+ Section {+ Notice(+ title: Text("Its switch is in System Settings"),+ detail: Text(.keptOffBySystemSettings),+ kind: .note+ ) {}+ }+ }+if item.isSubmittedByItsApp {Section {Notice(@@ -304,9 +306,6 @@ struct BackgroundItemDetailView: View {}}.formStyle(.grouped)- .task(id: Look(item: item.id, scans: backgroundItems.scans)) {- legacyStatus = await Self.legacyStatus(of: item)- }.navigationTitle(item.label).toolbar(removing: .title).sheet(isPresented: $isEditing) {@@ -361,27 +360,6 @@ struct BackgroundItemDetailView: View {backgroundItems.runningActionItemIDs.contains(item.id)}- /// Returns the job's status in System Settings (Login Items & Extensions), or nil when it has no plist file in a- /// folder launchd reads (`hasLoginItemsStatus`), the only ones `SMAppService.h` gives a status for. Per that- /// header, `.requiresApproval` also means the user turned the job off, so the text says both. Off the main thread:- /// `SMAppService` asks Background Task Management over XPC.- @concurrent- static func legacyStatus(of item: BackgroundItem) async -> LocalizedStringResource? {- guard let plistURL = item.plistURL, hasLoginItemsStatus(item) else { return nil }- return switch SMAppService.statusForLegacyPlist(at: plistURL) {- case .enabled: "Allowed"- case .requiresApproval: "Needs approval, or was turned off"- // Background Task Management lists a job once it has seen its file, which launchd loads meanwhile anyway.- case .notRegistered: "Not listed in System Settings yet"- case .notFound: "Not found"- @unknown default: "Unknown"- }- }-- nonisolated static func hasLoginItemsStatus(_ item: BackgroundItem) -> Bool {- item.plistURL != nil && (item.source == .userLibrary || item.source == .systemLibrary)- }-private var header: some View {HStack(spacing: 18) {if let ownerURL = item.ownerURL {@@ -547,6 +525,18 @@ private extension BackgroundItem.Control {}}+extension LoginItemsStatus {+ var words: LocalizedStringResource {+ switch self {+ case .allowed: "Allowed"+ case .turnedOff: "Needs approval, or was turned off"+ case .notListedYet: "Not listed in System Settings yet"+ case .notFound: "Not found"+ case .unknown: "Unknown"+ }+ }+}+extension UnusualCommand {var explanation: LocalizedStringResource {switch self {diff --git a/Peel/Views/BackgroundItems/BackgroundItemList.swift b/Peel/Views/BackgroundItems/BackgroundItemList.swiftindex 0d6545ca..6ac5585a 100644--- a/Peel/Views/BackgroundItems/BackgroundItemList.swift+++ b/Peel/Views/BackgroundItems/BackgroundItemList.swift@@ -184,6 +184,7 @@ struct BackgroundItemList: View {case .trash(let reason): Text(verbatim: reason.explanation)case .disabled: Text("macOS won’t load this while it is disabled. Enable it first, then start it.")case .quarantinedPlist: Text("macOS won’t load this: its configuration file carries the mark macOS puts on downloads. Reinstalling the app that put it there may write it again without the mark.")+ case .turnedOffInSystemSettings: Text(.keptOffBySystemSettings)}}@@ -354,4 +355,6 @@ extension LocalizedStringResource {"Unknown (background item state)",defaultValue: "Unknown")++ static let keptOffBySystemSettings: LocalizedStringResource = "It needs approval in System Settings > General > Login Items & Extensions, or was turned off there, so macOS doesn’t run it, and Peel doesn’t start it either."}diff --git a/PeelTests/BackgroundItemLoginItemsTests.swift b/PeelTests/BackgroundItemLoginItemsTests.swiftdeleted file mode 100644index f4979dc4..00000000--- a/PeelTests/BackgroundItemLoginItemsTests.swift+++ /dev/null@@ -1,24 +0,0 @@-import Foundation-@testable import Peel-@testable import PeelCore-import Testing--struct BackgroundItemLoginItemsTests {- private func job(_ source: BackgroundItem.Source, at path: String) -> BackgroundItem {- BackgroundItem(- label: "org.example.agent", kind: .agent, source: source, plistURL: URL(filePath: path),- program: "/usr/local/bin/agent", runsAtLoad: true, keepsAlive: false, ownerBundleIdentifier: nil,- ownerName: nil, ownerURL: nil, isOrphan: false, state: .notLoaded, isDisabled: false- )- }-- @Test func asksSystemSettingsOnlyAboutAFileInTheFoldersItReads() async {- let agents = URL.homeDirectory.appending(path: "Library/LaunchAgents/org.example.agent.plist")-- let elsewhere = await BackgroundItemDetailView.legacyStatus(of: job(.otherFile, at: "/Users/Shared/org.example.agent.plist"))- let documented = await BackgroundItemDetailView.legacyStatus(of: job(.userLibrary, at: agents.path))-- #expect(elsewhere == nil)- #expect(documented != nil)- }-}