diff --git a/CITATION.cff b/CITATION.cff
index af4e781..ac66e85 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -7,8 +7,8 @@ message: >-
permission or a Commercial License from the author.
type: software
title: MacOS Cleaner
-version: "3.0.0"
-date-released: "2026-11-16"
+version: "3.0.1"
+date-released: "2026-11-20"
url: "https://github.com/AlexTkDev/MacOSCleaner"
repository-code: "https://github.com/AlexTkDev/MacOSCleaner"
# Custom non-SPDX source-available license; CFF 1.2.0 uses license-url instead of license.
diff --git a/MacOSCleaner/App/MacOSCleanerApp.swift b/MacOSCleaner/App/MacOSCleanerApp.swift
index 9d7f235..513cacb 100644
--- a/MacOSCleaner/App/MacOSCleanerApp.swift
+++ b/MacOSCleaner/App/MacOSCleanerApp.swift
@@ -3,10 +3,6 @@
// Licensed under GNU GPLv3 with Commons Clause v1.0 & Non-Commercial Condition (see LICENSE).
import SwiftUI
-import OSLog
-
-
-private let crashLogger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "input.MacOSCleaner", category: "Crash")
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
@@ -45,29 +41,7 @@ struct MacOSCleanerApp: App {
}
private static func installCrashHandlers() {
- NSSetUncaughtExceptionHandler { exception in
- let desc = exception.description
- crashLogger.fault("Uncaught exception: \(exception.name.rawValue): \(desc)")
- crashLogger.fault("Stack trace: \(exception.callStackSymbols.joined(separator: "\n"))")
- fflush(stderr)
- abort()
- }
-
- signal(SIGABRT) { _ in
- crashLogger.fault("Received SIGABRT")
- fflush(stderr)
- _exit(1)
- }
- signal(SIGSEGV) { _ in
- crashLogger.fault("Received SIGSEGV")
- fflush(stderr)
- _exit(1)
- }
- signal(SIGBUS) { _ in
- crashLogger.fault("Received SIGBUS")
- fflush(stderr)
- _exit(1)
- }
+ CrashSignalHandler.install()
}
var body: some Scene {
diff --git a/MacOSCleaner/App/RootView.swift b/MacOSCleaner/App/RootView.swift
index ade92e0..ebeda0f 100644
--- a/MacOSCleaner/App/RootView.swift
+++ b/MacOSCleaner/App/RootView.swift
@@ -8,6 +8,7 @@ import SwiftUI
struct RootView: View {
@State private var selectedItem: NavigationItem = .dashboard
@State private var privacyFilterBundleID: String? = nil
+ @State private var workspaceStore: WorkspaceStore
let cleanupViewModel: CleanupViewModel
let journal: TransactionJournal
let appSettings: AppSettings
@@ -15,6 +16,23 @@ struct RootView: View {
@Bindable var updatePrompt: UpdatePromptController
@Binding var availableUpdate: AvailableUpdate?
+ init(
+ cleanupViewModel: CleanupViewModel,
+ journal: TransactionJournal,
+ appSettings: AppSettings,
+ permissionsManager: PermissionsManager,
+ updatePrompt: UpdatePromptController,
+ availableUpdate: Binding
+ ) {
+ self.cleanupViewModel = cleanupViewModel
+ self.journal = journal
+ self.appSettings = appSettings
+ self.permissionsManager = permissionsManager
+ self.updatePrompt = updatePrompt
+ self._availableUpdate = availableUpdate
+ self._workspaceStore = State(initialValue: WorkspaceStore(journal: journal))
+ }
+
@Environment(\.colorScheme) private var colorScheme
@Environment(\.layoutDirection) private var layoutDirection
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
@@ -101,6 +119,9 @@ struct RootView: View {
presentUpdateIfReady()
}
}
+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
+ permissionsManager.refresh()
+ }
}
private func presentUpdateIfReady() {
@@ -186,28 +207,30 @@ struct RootView: View {
private func contentView(for item: NavigationItem) -> some View {
switch item {
case .dashboard:
- DashboardView(journal: journal)
+ DashboardView(viewModel: workspaceStore.dashboardViewModel)
case .cleanup:
CleanupView(
viewModel: cleanupViewModel,
scanLimited: !permissionsManager.hasFullDiskAccess
)
case .diskSpace:
- DiskAnalyzerView(settings: appSettings)
+ DiskAnalyzerView(settings: appSettings, viewModel: workspaceStore.diskAnalyzerViewModel)
case .duplicates:
- DuplicatesView(settings: appSettings)
+ DuplicatesView(settings: appSettings, viewModel: workspaceStore.duplicatesViewModel)
case .processes:
- ProcessesView(settings: appSettings)
+ ProcessesView(settings: appSettings, viewModel: workspaceStore.processesViewModel)
case .startupServices:
- StartupServicesView(settings: appSettings)
+ StartupServicesView(settings: appSettings, viewModel: workspaceStore.startupServicesViewModel)
case .privacy:
PrivacyView(
permissionsManager: permissionsManager,
- initialBundleIDFilter: $privacyFilterBundleID
+ initialBundleIDFilter: $privacyFilterBundleID,
+ viewModel: workspaceStore.privacyViewModel
)
case .uninstaller:
UninstallerView(
settings: appSettings,
+ viewModel: workspaceStore.uninstallerViewModel,
navigateToCleanup: { selectedItem = .cleanup },
navigateToPrivacy: { bundleID in
privacyFilterBundleID = bundleID
diff --git a/MacOSCleaner/App/WorkspaceStore.swift b/MacOSCleaner/App/WorkspaceStore.swift
new file mode 100644
index 0000000..470254c
--- /dev/null
+++ b/MacOSCleaner/App/WorkspaceStore.swift
@@ -0,0 +1,26 @@
+import Foundation
+import Observation
+
+/// Long-lived workspace state container anchored in `RootView` so tab switches
+/// and language reloads preserve cached scan results without re-scanning.
+@MainActor
+@Observable
+final class WorkspaceStore {
+ let dashboardViewModel: DashboardViewModel
+ let diskAnalyzerViewModel: DiskAnalyzerViewModel
+ let duplicatesViewModel: DuplicatesViewModel
+ let processesViewModel: ProcessesViewModel
+ let startupServicesViewModel: StartupServicesViewModel
+ let privacyViewModel: PrivacyViewModel
+ let uninstallerViewModel: UninstallerViewModel
+
+ init(journal: TransactionJournal) {
+ self.dashboardViewModel = DashboardViewModel(journal: journal)
+ self.diskAnalyzerViewModel = DiskAnalyzerViewModel()
+ self.duplicatesViewModel = DuplicatesViewModel()
+ self.processesViewModel = ProcessesViewModel()
+ self.startupServicesViewModel = StartupServicesViewModel()
+ self.privacyViewModel = PrivacyViewModel()
+ self.uninstallerViewModel = UninstallerViewModel()
+ }
+}
diff --git a/MacOSCleaner/Domains/Cleanup/CleanupCoordinator.swift b/MacOSCleaner/Domains/Cleanup/CleanupCoordinator.swift
index 102c5eb..b2f8036 100644
--- a/MacOSCleaner/Domains/Cleanup/CleanupCoordinator.swift
+++ b/MacOSCleaner/Domains/Cleanup/CleanupCoordinator.swift
@@ -28,6 +28,7 @@ public final class CleanupCoordinator {
public var totalFreedBytes: Int64 = 0
public var apfsDeltaBytes: Int64? = nil
public var usedPermanentDeletion: Bool = false
+ public var cleanedFontCache: Bool = false
public var cleanedItems: [CleanupResultItem] = []
public var skippedItems: [SkippedCleanupItem] = []
public var lastError: String? = nil
@@ -135,6 +136,7 @@ public final class CleanupCoordinator {
try self.stateMachine.transition(to: .executing)
self.totalFreedBytes = 0
self.apfsDeltaBytes = nil
+ self.cleanedFontCache = false
let isImmediatePermanent = self.settings.bypassTrashOnUninstall || self.settings.emptyTrashDuringCleanup
self.usedPermanentDeletion = isImmediatePermanent
let sessionDeletionMode: OperationRecord.DeletionMode = isImmediatePermanent ? .permanent : .trash
@@ -166,6 +168,7 @@ public final class CleanupCoordinator {
let categories = self.itemManager.selectedCleanupCategories(from: options.categories())
// Review-only categories — never run category-level wipe.
let safeCategories = categories.filter { !CleanupCategory.reviewOnly.contains($0) }
+ self.cleanedFontCache = safeCategories.contains(.fontCache)
var records: [OperationRecord] = []
var hadPartialFailure = false
@@ -440,6 +443,7 @@ public final class CleanupCoordinator {
totalFreedBytes = 0
apfsDeltaBytes = nil
usedPermanentDeletion = false
+ cleanedFontCache = false
currentStep = 0
stepTitle = ""
lastError = nil
diff --git a/MacOSCleaner/Domains/Cleanup/CleanupEngine.swift b/MacOSCleaner/Domains/Cleanup/CleanupEngine.swift
index 1bf0812..adc139d 100644
--- a/MacOSCleaner/Domains/Cleanup/CleanupEngine.swift
+++ b/MacOSCleaner/Domains/Cleanup/CleanupEngine.swift
@@ -1,3 +1,4 @@
+import AppKit
import Foundation
import OSLog
import CoreServices
@@ -810,11 +811,100 @@ extension CleanupEngine {
func cleanAppCaches(dryRun: Bool, progress: (@Sendable (CleanupEngineEvent) -> Void)?) async throws -> [CleanupEngineResult] {
// Only purpose:cache paths from the generated registry — never shared updaters / Keystone.
var results = try await cleanFromEmbeddedPaths(.appCaches, label: "App caches", dryRun: dryRun, progress: progress)
+ let thirdParty = try await cleanDiscoveredThirdPartyAppCaches(dryRun: dryRun, progress: progress)
+ results.append(contentsOf: thirdParty)
let sparkle = try await cleanSparkleUpdateDownloads(dryRun: dryRun, progress: progress)
results.append(contentsOf: sparkle)
return results
}
+ private func cleanDiscoveredThirdPartyAppCaches(dryRun: Bool, progress: (@Sendable (CleanupEngineEvent) -> Void)?) async throws -> [CleanupEngineResult] {
+ let home = fileSystemContext.homePath
+ let cachesDir = "\(home)/Library/Caches"
+ let label = "Third-party app caches"
+ guard fm.fileExists(atPath: cachesDir) else {
+ return [CleanupEngineResult(label: label, freedMB: 0)]
+ }
+
+ let dedicatedCategories: [CleanupCategory] = [
+ .appCaches, .browserCaches, .ideCaches, .systemCaches, .cloudKitCache, .photosCache,
+ ]
+ var alreadyCovered = Set()
+ for category in dedicatedCategories {
+ for entry in EmbeddedCleanupPaths.paths(for: category) {
+ for expanded in CleanupPathExpander.expand(entry.path, home: home, fileManager: fm) {
+ alreadyCovered.insert(NormalizedPath.lowercaseKey(expanded))
+ }
+ }
+ }
+
+ let excludedEntries: Set = [
+ "apple", "google", "cloudkit", "geoservices", "familycircle",
+ "homebrew", "pip", "yarn", "cocoapods", "npm", "go-build",
+ "firefox", "org.mozilla.firefox", "org.mozilla.firefoxdeveloperedition", "org.mozilla.nightly",
+ "bravesoftware", "com.google.chrome", "com.google.chrome.beta",
+ "com.google.chrome.canary", "com.google.chrome.dev",
+ "com.brave.browser", "com.brave.browser.beta", "com.brave.browser.nightly",
+ "com.operasoftware.opera", "com.operasoftware.operagx", "com.operasoftware.operadeveloperedition",
+ "com.microsoft.edge", "com.microsoft.edgemac", "com.microsoft.edgemac.beta",
+ "com.microsoft.edgemac.canary", "com.microsoft.edgemac.dev",
+ "com.vivaldi.vivaldi", "company.thebrowser.browser",
+ "com.kagi.kagimacos", "com.duckduckgo.macos.browser",
+ "ru.yandex.desktop.yandex-browser",
+ "com.google.softwareupdate", "com.google.googleupdater", "com.google.keystone",
+ ]
+
+ var totalFreed: Int64 = 0
+ var removed = 0
+ var skipped = 0
+ let entries = (try? fm.contentsOfDirectory(atPath: cachesDir)) ?? []
+
+ for entry in entries {
+ try Task.checkCancellation()
+ let lower = entry.lowercased()
+ if entry.hasPrefix(".") || lower.hasPrefix("com.apple.") || excludedEntries.contains(lower) {
+ continue
+ }
+ if lower.contains("googleupdater") || lower.contains("softwareupdate") || lower.contains("keystone") {
+ continue
+ }
+ if Self.isHeavyContainer(entry) {
+ continue
+ }
+
+ let entryPath = "\(cachesDir)/\(entry)"
+ guard !alreadyCovered.contains(NormalizedPath.lowercaseKey(entryPath)) else { continue }
+ var isDir: ObjCBool = false
+ guard fm.fileExists(atPath: entryPath, isDirectory: &isDir), isDir.boolValue else { continue }
+ let entryURL = URL(fileURLWithPath: entryPath)
+ guard !safetyManager.isSymlinkDirectory(entryURL),
+ (try? safetyManager.validate(url: entryURL, policy: .cleanup)) != nil else {
+ continue
+ }
+
+ let (freed, item) = try await cleanContents(of: entryPath, dryRun: dryRun, progress: progress)
+ if freed > 0 || item != nil {
+ removed += 1
+ totalFreed += freed
+ if dryRun {
+ emitFileItem(item, category: "App caches", parentName: label, progress: progress)
+ }
+ } else {
+ skipped += 1
+ }
+ }
+
+ let mb = Int(totalFreed / (1024 * 1024))
+ return [CleanupEngineResult(
+ label: label,
+ freedMB: mb,
+ freedBytes: totalFreed,
+ removedCount: removed,
+ skippedCount: skipped,
+ failedCount: 0
+ )]
+ }
+
/// Stale Sparkle / Electron updater downloads under ~/Library/Caches — regenerable, safe.
func cleanSparkleUpdateDownloads(dryRun: Bool, progress: (@Sendable (CleanupEngineEvent) -> Void)?) async throws -> [CleanupEngineResult] {
let home = fileSystemContext.homePath
@@ -1264,7 +1354,10 @@ extension CleanupEngine {
freed += cf
if dryRun { emitFileItem(ci, category: "iOS Simulators", parentName: nil, isSelected: false, progress: progress) }
- if await commandRunner.commandExists("xcrun") {
+ // Guard against macOS /usr/bin/xcrun shim triggering the "Install Command Line Developer Tools"
+ // modal on Macs without Xcode: require CoreSimulator on disk AND a configured Xcode developer dir.
+ let coreSimulatorRoot = "\(home)/Library/Developer/CoreSimulator"
+ if fm.fileExists(atPath: coreSimulatorRoot), await hasInstalledXcodeDeveloperTools() {
let deleteUnavailable = "command://simctl/delete-unavailable"
let deleteRuntimes = "command://simctl/delete-old-runtimes"
let result = try? await commandRunner.run(command: "/bin/bash", arguments: ["-c", "xcrun simctl list devices 2>/dev/null | grep -c 'unavailable' || echo 0"])
@@ -2153,6 +2246,56 @@ extension CleanupEngine {
// MARK: 22. Dynamic Cache Discovery
+ private func dedicatedCacheDirectoryNames(for planned: Set, home: String) -> Set {
+ // ~/Library/Caches/Google houses updater/Keystone alongside Chrome caches and is
+ // handled via exact sub-paths rather than top-level review/auto-clean.
+ var names: Set = ["google"]
+ let otherPlanned = planned.subtracting([.dynamicCacheDiscovery])
+
+ if otherPlanned.contains(.packageManagers) {
+ names.formUnion(["homebrew", "yarn", "cocoapods"])
+ }
+ if otherPlanned.contains(.languageCaches) {
+ names.insert("go-build")
+ }
+ if otherPlanned.contains(.cloudKitCache) {
+ names.insert("cloudkit")
+ }
+ if otherPlanned.contains(.adobeCaches) {
+ names.insert("adobe")
+ }
+ if otherPlanned.contains(.teamsCache) {
+ names.formUnion(["com.microsoft.teams", "com.microsoft.teams2"])
+ }
+ if otherPlanned.contains(.garminFitbit) {
+ names.formUnion(["com.garmin.connectiq", "com.fitbit.fitbit-os-simulator"])
+ }
+
+ let tildePrefix = "~/library/caches/"
+ let homePrefix = (home.hasSuffix("/") ? home : home + "/").lowercased() + "library/caches/"
+
+ for category in otherPlanned {
+ for entry in EmbeddedCleanupPaths.paths(for: category) {
+ let lower = entry.path.lowercased()
+ let remainder: Substring?
+ if lower.hasPrefix(tildePrefix) {
+ remainder = lower.dropFirst(tildePrefix.count)
+ } else if lower.hasPrefix(homePrefix) {
+ remainder = lower.dropFirst(homePrefix.count)
+ } else {
+ remainder = nil
+ }
+ guard let remainder else { continue }
+ let firstComponent = remainder.split(separator: "/", maxSplits: 1).first.map(String.init) ?? ""
+ if !firstComponent.isEmpty, !firstComponent.contains("*"), !firstComponent.contains("?") {
+ names.insert(firstComponent)
+ }
+ }
+ }
+
+ return names
+ }
+
func cleanDynamicCacheDiscovery(dryRun: Bool, progress: (@Sendable (CleanupEngineEvent) -> Void)?) async throws -> [CleanupEngineResult] {
let home = fileSystemContext.homePath
let cachesDir = "\(home)/Library/Caches"
@@ -2165,10 +2308,15 @@ extension CleanupEngine {
return [CleanupEngineResult(label: "Dynamic cache discovery", freedMB: 0)]
}
+ let coveredCaches = dedicatedCacheDirectoryNames(for: CleanupEngine.currentPlannedCategories, home: home)
let entries = (try? fm.contentsOfDirectory(atPath: cachesDir)) ?? []
for entry in entries {
try Task.checkCancellation()
+ if coveredCaches.contains(entry.lowercased()) {
+ continue
+ }
+
// Skip heavy containers (Docker, VMs) — virtual disks cause timeouts
if Self.isHeavyContainer(entry) {
progress?(.log(" \(entry) — skipped (heavy container)"))
@@ -2598,9 +2746,27 @@ extension CleanupEngine {
return [CleanupEngineResult(label: "Chrome Extra Caches", freedMB: mb)]
}
+ private func hasInstalledXcodeDeveloperTools() async -> Bool {
+ // `xcode-select -p` never triggers the interactive CLT install prompt.
+ guard let result = try? await commandRunner.run(
+ command: "/usr/bin/xcode-select",
+ arguments: ["-p"],
+ timeout: .seconds(5)
+ ), result.exitCode == 0 else {
+ return false
+ }
+ let devDir = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !devDir.isEmpty, fm.fileExists(atPath: devDir) else { return false }
+ // simctl ships only with full Xcode, not bare CommandLineTools.
+ return fm.fileExists(atPath: "\(devDir)/usr/bin/simctl")
+ }
+
private func isAppRunning(bundleIdentifier: String) async -> Bool {
- let result = try? await commandRunner.run(command: "/bin/bash", arguments: ["-c", "pgrep -x \(bundleIdentifier) >/dev/null 2>&1"])
- return result?.exitCode == 0
+ await MainActor.run {
+ NSWorkspace.shared.runningApplications.contains {
+ $0.bundleIdentifier?.caseInsensitiveCompare(bundleIdentifier) == .orderedSame && !$0.isTerminated
+ }
+ }
}
// MARK: 36. Launch Agents (user)
diff --git a/MacOSCleaner/Domains/Cleanup/DuplicateFinderEngine.swift b/MacOSCleaner/Domains/Cleanup/DuplicateFinderEngine.swift
index 6552bfb..7dcc9e2 100644
--- a/MacOSCleaner/Domains/Cleanup/DuplicateFinderEngine.swift
+++ b/MacOSCleaner/Domains/Cleanup/DuplicateFinderEngine.swift
@@ -86,12 +86,16 @@ public actor DuplicateFinderEngine {
}
/// Checks if a file path is safe to scan and recommend for user duplicate removal.
- private func isSafeUserFilePath(_ path: String) -> Bool {
+ func isSafeUserFilePath(_ path: String, allowExternalVolumes: Bool = false) -> Bool {
// User temp (`/var/folders/…`, `/private/var/folders/…`) is a valid scan root.
if path.hasPrefix("/var/folders/") || path.hasPrefix("/private/var/folders/") {
return true
}
+ if allowExternalVolumes && SafetyManager.isAllowedExternalVolumePath(path, policy: .userSelected) {
+ return true
+ }
+
let forbiddenPrefixes = [
"/System", "/Library", "/Applications", "/usr", "/bin", "/sbin",
"/private", "/etc", "/var", "/tmp", "/opt", "/dev", "/Volumes", "/Network", "/cores"
@@ -118,6 +122,15 @@ public actor DuplicateFinderEngine {
return true
}
+ private static func isExplicitExternalVolumeRoot(_ directory: URL) -> Bool {
+ let normalized = NormalizedPath.string(directory.standardizedFileURL.path)
+ let components = normalized.split(separator: "/", omittingEmptySubsequences: true).map(String.init)
+ guard components.count >= 2, components[0].lowercased() == "volumes" else { return false }
+ guard SafetyManager.isAllowedExternalVolumeName(components[1]) else { return false }
+ let resolved = NormalizedPath.resolvedString(normalized)
+ return resolved.lowercased().hasPrefix("/volumes/")
+ }
+
/// Scans a directory for duplicate files using multi-stage comparison (Size -> Header SHA256 -> Full SHA256).
public func scan(
directory: URL,
@@ -126,6 +139,7 @@ public actor DuplicateFinderEngine {
) async throws -> [DuplicateGroup] {
try Task.checkCancellation()
+ let allowExternalVolumes = Self.isExplicitExternalVolumeRoot(directory)
progress?(Progress(stage: .collectingFiles, filesScanned: 0, duplicateGroupsFound: 0))
var filesBySize: [Int64: [URL]] = [:]
@@ -137,6 +151,7 @@ public actor DuplicateFinderEngine {
.isPackageKey,
.isSymbolicLinkKey,
.contentModificationDateKey,
+ .isUbiquitousItemKey,
.ubiquitousItemDownloadingStatusKey
]
@@ -160,7 +175,7 @@ public actor DuplicateFinderEngine {
// Skip system & excluded directories immediately
if resourceValues.isDirectory == true {
- if Self.excludedDirectoryNames.contains(dirName) || Self.excludedDirectoryExtensions.contains(dirExt) || !isSafeUserFilePath(path) {
+ if Self.excludedDirectoryNames.contains(dirName) || Self.excludedDirectoryExtensions.contains(dirExt) || !isSafeUserFilePath(path, allowExternalVolumes: allowExternalVolumes) {
enumerator.skipDescendants()
}
continue
@@ -175,7 +190,7 @@ public actor DuplicateFinderEngine {
}
// Enforce system path safety check
- guard isSafeUserFilePath(path) else { continue }
+ guard isSafeUserFilePath(path, allowExternalVolumes: allowExternalVolumes) else { continue }
// Skip excluded file extensions
let pathExt = fileURL.pathExtension.lowercased()
@@ -388,7 +403,7 @@ public actor DuplicateFinderEngine {
progress?(index + 1, total)
let url = item.url
- guard isSafeUserFilePath(url.path) else {
+ guard isSafeUserFilePath(url.path, allowExternalVolumes: true) else {
Logger.duplicateEngine.warning("Refused to trash unsafe path: \(url.path, privacy: .public)")
continue
}
diff --git a/MacOSCleaner/Domains/Cleanup/GeneratedCleanupPaths.swift b/MacOSCleaner/Domains/Cleanup/GeneratedCleanupPaths.swift
index 00e2d2c..add42bc 100644
--- a/MacOSCleaner/Domains/Cleanup/GeneratedCleanupPaths.swift
+++ b/MacOSCleaner/Domains/Cleanup/GeneratedCleanupPaths.swift
@@ -33,8 +33,11 @@ public enum GeneratedCleanupPaths {
public static var systemCaches: [CleanupPath] { cachePaths(for: .systemCaches) }
public static func appPaths(forBundleID bundleID: String) -> AppPaths? {
- let lower = bundleID.lowercased()
- guard !lower.isEmpty, !lower.hasPrefix("unknown.") else { return nil }
+ let lower = bundleID.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ guard !lower.isEmpty,
+ !lower.hasPrefix("unknown."),
+ !BrowserRule.isBrowserPWAShimBundleID(lower)
+ else { return nil }
let snapshot = PrivateCatalogStore.snapshot
if let key = snapshot.bundleIDToRegistryKey[lower], let paths = snapshot.registry[key] {
return paths
diff --git a/MacOSCleaner/Domains/Cleanup/SystemMaintenanceService.swift b/MacOSCleaner/Domains/Cleanup/SystemMaintenanceService.swift
index b489426..d63db59 100644
--- a/MacOSCleaner/Domains/Cleanup/SystemMaintenanceService.swift
+++ b/MacOSCleaner/Domains/Cleanup/SystemMaintenanceService.swift
@@ -3,6 +3,8 @@
// Licensed under GNU GPLv3 with Commons Clause v1.0 & Non-Commercial Condition (see LICENSE).
import Foundation
+import AppKit
+import Carbon
import LocalAuthentication
import os.log
@@ -87,4 +89,41 @@ public final class SystemMaintenanceService {
throw error
}
}
+
+ @MainActor
+ @discardableResult
+ public static func requestSystemRestart() -> Bool {
+ // Send kAERestart to loginwindow so macOS displays its standard confirmation dialog
+ // with countdown and open-windows preservation instead of forcing an abrupt reboot.
+ let target = NSAppleEventDescriptor(bundleIdentifier: "com.apple.loginwindow")
+ let event = NSAppleEventDescriptor(
+ eventClass: AEEventClass(kCoreEventClass),
+ eventID: AEEventID(kAERestart),
+ targetDescriptor: target,
+ returnID: AEReturnID(kAutoGenerateReturnID),
+ transactionID: AETransactionID(kAnyTransactionID)
+ )
+
+ if let aeDesc = event.aeDesc {
+ let status = AESendMessage(aeDesc, nil, AESendMode(kAENoReply), kAEDefaultTimeout)
+ if status == noErr {
+ Logger.maintenance.info("Requested standard system restart via loginwindow AppleEvent")
+ return true
+ }
+ Logger.maintenance.warning("AESendMessage restart failed with OSStatus \(status, privacy: .public), falling back to NSAppleScript")
+ }
+
+ guard let script = NSAppleScript(source: "tell application \"loginwindow\" to «event aevtrrst»") else {
+ Logger.maintenance.error("Failed to create loginwindow restart NSAppleScript")
+ return false
+ }
+ var errorInfo: NSDictionary?
+ script.executeAndReturnError(&errorInfo)
+ if let errorInfo {
+ Logger.maintenance.error("NSAppleScript restart failed: \(String(describing: errorInfo), privacy: .public)")
+ return false
+ }
+ Logger.maintenance.info("Requested standard system restart via NSAppleScript fallback")
+ return true
+ }
}
diff --git a/MacOSCleaner/Domains/Cleanup/TimeMachineScanner.swift b/MacOSCleaner/Domains/Cleanup/TimeMachineScanner.swift
index ad1b5cb..23b369a 100644
--- a/MacOSCleaner/Domains/Cleanup/TimeMachineScanner.swift
+++ b/MacOSCleaner/Domains/Cleanup/TimeMachineScanner.swift
@@ -11,51 +11,33 @@ public enum TimeMachineScanner {
}
/// Queries tmutil to list local snapshots and estimates their size.
- public static func listLocalSnapshots() async -> [Snapshot] {
+ public static func listLocalSnapshots(
+ commandRunner: any CommandRunning = CommandRunner()
+ ) async -> [Snapshot] {
guard !Task.isCancelled else { return [] }
- let runnerTask = Task.detached {
- guard !Task.isCancelled else { return [Snapshot]() }
- let task = Process()
- task.launchPath = "/usr/bin/tmutil"
- task.arguments = ["listlocalsnapshots", "/"]
-
- let pipe = Pipe()
- task.standardOutput = pipe
-
- do {
- try task.run()
- let data = pipe.fileHandleForReading.readDataToEndOfFile()
- task.waitUntilExit()
-
- guard !Task.isCancelled else { return [Snapshot]() }
- guard let output = String(data: data, encoding: .utf8) else {
- return []
- }
-
- // tmutil listlocalsnapshots /
- // Snapshots for disk /:
- // com.apple.TimeMachine.2023-10-05-152433.local
-
- var snapshots: [Snapshot] = []
- let lines = output.components(separatedBy: .newlines)
- for line in lines {
- let trimmed = line.trimmingCharacters(in: .whitespaces)
- if trimmed.hasPrefix("com.apple.TimeMachine") {
- snapshots.append(Snapshot(name: trimmed))
- }
+ guard FileManager.default.fileExists(atPath: "/usr/bin/tmutil") else { return [] }
+ do {
+ let result = try await commandRunner.run(
+ command: "/usr/bin/tmutil",
+ arguments: ["listlocalsnapshots", "/"],
+ timeout: .seconds(10)
+ )
+ guard !Task.isCancelled, result.exitCode == 0 else { return [] }
+
+ // tmutil listlocalsnapshots /
+ // Snapshots for disk /:
+ // com.apple.TimeMachine.2023-10-05-152433.local
+ var snapshots: [Snapshot] = []
+ for line in result.stdout.components(separatedBy: .newlines) {
+ let trimmed = line.trimmingCharacters(in: .whitespaces)
+ if trimmed.hasPrefix("com.apple.TimeMachine") {
+ snapshots.append(Snapshot(name: trimmed))
}
-
- return snapshots
- } catch {
- Logger.tmScanner.error("Failed to run tmutil listlocalsnapshots: \(error.localizedDescription, privacy: .public)")
- return []
}
- }
-
- return await withTaskCancellationHandler {
- await runnerTask.value
- } onCancel: {
- runnerTask.cancel()
+ return snapshots
+ } catch {
+ Logger.tmScanner.error("Failed to run tmutil listlocalsnapshots: \(error.localizedDescription, privacy: .public)")
+ return []
}
}
diff --git a/MacOSCleaner/Domains/ProcessManagement/AppQuitter.swift b/MacOSCleaner/Domains/ProcessManagement/AppQuitter.swift
index 84fdb90..4575f60 100644
--- a/MacOSCleaner/Domains/ProcessManagement/AppQuitter.swift
+++ b/MacOSCleaner/Domains/ProcessManagement/AppQuitter.swift
@@ -71,12 +71,17 @@ public enum AppQuitter {
return Outcome(forced: forced, stillRunning: stillRunning)
}
+ nonisolated public static var isRunningUnderTests: Bool {
+ NSClassFromString("XCTestCase") != nil
+ || ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
+ || ProcessInfo.processInfo.environment["XCTestBundlePath"] != nil
+ }
+
/// Regular, non-Apple, policy-allowed apps. Shared by cleanup so the policy filter lives in one place.
public static func cleanupTargets(policy: ProcessSafetyPolicy = ProcessSafetyPolicy()) -> [Handle] {
// Unit tests call executeCleanup against an isolated filesystem. Quitting live apps there
// would kill the developer's session.
- guard NSClassFromString("XCTestCase") == nil,
- ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else {
+ guard !isRunningUnderTests else {
return []
}
return NSWorkspace.shared.runningApplications.compactMap { application in
diff --git a/MacOSCleaner/Features/About/AboutView.swift b/MacOSCleaner/Features/About/AboutView.swift
index ecc54e8..a19de76 100644
--- a/MacOSCleaner/Features/About/AboutView.swift
+++ b/MacOSCleaner/Features/About/AboutView.swift
@@ -262,5 +262,5 @@ private struct AboutTransparencySheet: View {
}
#Preview {
- AboutView(availableUpdate: AvailableUpdate(version: "3.0.0", dmgURL: nil))
+ AboutView(availableUpdate: AvailableUpdate(version: "3.0.1", dmgURL: nil))
}
diff --git a/MacOSCleaner/Features/Cleanup/AnimatedScanView.swift b/MacOSCleaner/Features/Cleanup/AnimatedScanView.swift
index 49f5b8d..fd3e36f 100644
--- a/MacOSCleaner/Features/Cleanup/AnimatedScanView.swift
+++ b/MacOSCleaner/Features/Cleanup/AnimatedScanView.swift
@@ -159,14 +159,13 @@ struct AnimatedScanView: View {
Text(subtitle)
.font(.headline)
+ .monospacedDigit()
.foregroundColor(.primary)
.multilineTextAlignment(.center)
+ .lineLimit(2)
+ .frame(minHeight: isCompact ? 32 : 40, alignment: .top)
.padding(.horizontal, 40)
- .id(subtitle)
- .transition(.asymmetric(
- insertion: .move(edge: .bottom).combined(with: .opacity).animation(.spring(response: 0.35, dampingFraction: 0.8)),
- removal: .move(edge: .top).combined(with: .opacity).animation(.spring(response: 0.25, dampingFraction: 0.9))
- ))
+ .transaction { $0.animation = nil }
if totalSteps > 1 {
GeometryReader { geo in
diff --git a/MacOSCleaner/Features/Cleanup/CleanupView.swift b/MacOSCleaner/Features/Cleanup/CleanupView.swift
index db60906..2758d90 100644
--- a/MacOSCleaner/Features/Cleanup/CleanupView.swift
+++ b/MacOSCleaner/Features/Cleanup/CleanupView.swift
@@ -551,6 +551,10 @@ public struct CleanupView: View {
}
}
+ if !viewModel.cleanedItems.isEmpty || viewModel.cleanedFontCache {
+ restartRecommendationCard
+ }
+
HStack(spacing: 12) {
Button("dashboard_view_all_history".localized) {
openWindow(id: "cleanup-history")
@@ -573,6 +577,51 @@ public struct CleanupView: View {
}
.transition(.opacity.combined(with: .scale(scale: 0.95)))
}
+
+ @ViewBuilder
+ private var restartRecommendationCard: some View {
+ let isRequired = viewModel.cleanedFontCache
+ let accentColor: Color = isRequired ? .orange : .accentColor
+ let iconName = isRequired ? "exclamationmark.triangle.fill" : "arrow.trianglehead.2.clockwise.rotate.90"
+ let titleKey = isRequired ? "cleanup_restart_required_title" : "cleanup_restart_recommended_title"
+ let bodyKey = isRequired ? "cleanup_restart_font_cache_body" : "cleanup_restart_recommended_body"
+
+ HStack(alignment: .center, spacing: 14) {
+ Image(systemName: iconName)
+ .font(.system(size: 20, weight: .semibold))
+ .foregroundStyle(accentColor)
+ .frame(width: 28, height: 28)
+
+ VStack(alignment: .leading, spacing: 3) {
+ Text(titleKey.localized)
+ .font(.subheadline.weight(.semibold))
+ Text(bodyKey.localized)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ Spacer(minLength: 8)
+
+ Button {
+ SystemMaintenanceService.requestSystemRestart()
+ } label: {
+ Label("restart_mac_button".localized, systemImage: "power")
+ .font(.subheadline.weight(.medium))
+ }
+ .buttonStyle(.glass)
+ .tint(accentColor)
+ }
+ .padding(14)
+ .background(
+ RoundedRectangle(cornerRadius: 14, style: .continuous)
+ .fill(accentColor.opacity(isRequired ? 0.10 : 0.06))
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: 14, style: .continuous)
+ .strokeBorder(accentColor.opacity(isRequired ? 0.30 : 0.18), lineWidth: 1)
+ )
+ }
private func statusView(
icon: String,
diff --git a/MacOSCleaner/Features/Cleanup/CleanupViewModel.swift b/MacOSCleaner/Features/Cleanup/CleanupViewModel.swift
index c38ef5f..353ab09 100644
--- a/MacOSCleaner/Features/Cleanup/CleanupViewModel.swift
+++ b/MacOSCleaner/Features/Cleanup/CleanupViewModel.swift
@@ -18,6 +18,7 @@ public final class CleanupViewModel {
public var totalFreedBytes: Int64 { coordinator.totalFreedBytes }
public var apfsDeltaBytes: Int64? { coordinator.apfsDeltaBytes }
public var usedPermanentDeletion: Bool { coordinator.usedPermanentDeletion }
+ public var cleanedFontCache: Bool { coordinator.cleanedFontCache }
public var cleanedItems: [CleanupResultItem] { coordinator.cleanedItems }
public var skippedItems: [SkippedCleanupItem] { coordinator.skippedItems }
public var lastError: String? { coordinator.lastError }
diff --git a/MacOSCleaner/Features/Dashboard/DashboardView.swift b/MacOSCleaner/Features/Dashboard/DashboardView.swift
index 22cd92b..3b928a2 100644
--- a/MacOSCleaner/Features/Dashboard/DashboardView.swift
+++ b/MacOSCleaner/Features/Dashboard/DashboardView.swift
@@ -3,17 +3,32 @@ import Charts
struct DashboardView: View {
@Environment(\.openWindow) private var openWindow
- @StateObject private var viewModel: DashboardViewModel
- private let journal: TransactionJournal
-
+ @ObservedObject private var viewModel: DashboardViewModel
+
+ init(viewModel: DashboardViewModel) {
+ self.viewModel = viewModel
+ }
+
init(journal: TransactionJournal) {
- self.journal = journal
- _viewModel = StateObject(wrappedValue: DashboardViewModel(journal: journal))
+ self.viewModel = DashboardViewModel(journal: journal)
}
-
+
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 24) {
+ HStack(spacing: 8) {
+ Spacer()
+ ScanStatusPill(lastUpdatedAt: viewModel.lastUpdatedAt)
+ Button {
+ Task { await viewModel.refresh() }
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ }
+ .glassButtonStyle()
+ .disabled(viewModel.isCategoriesLoading)
+ .help("uninstaller_reload".localized)
+ }
+
HStack(spacing: 20) {
diskUsageCard
rightColumn
@@ -23,10 +38,10 @@ struct DashboardView: View {
}
.padding(.horizontal, 20)
.padding(.bottom, 20)
- .padding(.top, 16)
+ .padding(.top, 12)
}
.task {
- await viewModel.refresh()
+ await viewModel.refreshIfNeeded()
}
}
@@ -58,22 +73,15 @@ struct DashboardView: View {
private var diskUsageCard: some View {
VStack(alignment: .leading, spacing: 16) {
- if viewModel.isCategoriesLoading {
- VStack(spacing: 12) {
- LiquidGlassLoaderView(size: 48)
- Text("disk_analyzer_scanning".localized)
- .font(.subheadline)
- .foregroundColor(.secondary)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- } else {
- DiskRingsChartView(
- items: viewModel.diskCategories,
- totalUsed: viewModel.usedDiskSpace,
- totalDisk: viewModel.totalDiskSpace
- )
- .frame(maxHeight: .infinity)
- }
+ DiskRingsChartView(
+ items: viewModel.diskCategories,
+ totalUsed: viewModel.usedDiskSpace,
+ totalDisk: viewModel.totalDiskSpace,
+ isScanning: viewModel.isCategoriesLoading,
+ completedCategories: viewModel.completedCategoriesCount,
+ totalCategories: viewModel.totalScanCategoriesCount
+ )
+ .frame(maxHeight: .infinity)
}
.padding()
.frame(maxHeight: .infinity)
diff --git a/MacOSCleaner/Features/Dashboard/DashboardViewModel.swift b/MacOSCleaner/Features/Dashboard/DashboardViewModel.swift
index 7ce1c02..2fa057e 100644
--- a/MacOSCleaner/Features/Dashboard/DashboardViewModel.swift
+++ b/MacOSCleaner/Features/Dashboard/DashboardViewModel.swift
@@ -19,18 +19,45 @@ class DashboardViewModel: ObservableObject {
// Disk Categories (Donut Chart)
@Published var isCategoriesLoading: Bool = true
@Published var diskCategories: [DiskCategoryItem] = []
-
+ @Published var completedCategoriesCount: Int = 0
+ @Published var lastUpdatedAt: Date? = nil
+ let totalScanCategoriesCount: Int = 5
+ private var isRefreshing: Bool = false
+
+ private struct CategorySpec: Sendable {
+ let id: String
+ let labelKey: String
+ let color: Color
+ let gradientColors: [Color]
+ let iconName: String
+ let paths: [String]
+ }
+
private let journal: TransactionJournal
-
+
init(journal: TransactionJournal) {
self.journal = journal
}
-
+
+ func refreshIfNeeded() async {
+ if lastUpdatedAt == nil && !isRefreshing {
+ await refresh()
+ } else {
+ systemInfo = .current
+ await fetchDiskUsage()
+ await fetchHistory()
+ }
+ }
+
func refresh() async {
+ guard !isRefreshing else { return }
+ isRefreshing = true
+ defer { isRefreshing = false }
systemInfo = .current
await fetchDiskUsage()
await fetchHistory()
await fetchCategoryData()
+ lastUpdatedAt = Date()
}
private func fetchDiskUsage() async {
@@ -60,142 +87,254 @@ class DashboardViewModel: ObservableObject {
Logger.dashboard.error("Failed to load history: \(error.localizedDescription, privacy: .public)")
}
}
-
- private func fetchCategoryData() async {
- isCategoriesLoading = true
- let home = NSHomeDirectory()
-
- let categoryPaths: [(key: String, paths: [String])] = [
- ("caches", ["\(home)/Library/Caches", "/Library/Caches"]),
- ("logs", ["\(home)/Library/Logs", "/Library/Logs"]),
- ("dev", ["\(home)/Library/Developer"]),
- ("apps", ["/Applications", "\(home)/Applications", "/System/Applications"]),
- ("media", ["\(home)/Music", "\(home)/Pictures", "\(home)/Movies"])
- ]
-
- var calculatedSizes: [String: Int64] = [:]
-
- await withTaskGroup(of: (String, Int64).self) { group in
- for entry in categoryPaths {
- let paths = entry.paths
- let key = entry.key
- group.addTask {
- var total: Int64 = 0
- for path in paths {
- total += await Self.calculatePathSize(path)
- }
- return (key, total)
- }
- }
- for await (key, size) in group {
- calculatedSizes[key] = size
- }
- }
-
- let cachesSize = calculatedSizes["caches", default: 0]
- let logsSize = calculatedSizes["logs", default: 0]
- let devSize = calculatedSizes["dev", default: 0]
- let appsSize = calculatedSizes["apps", default: 0]
- let mediaSize = calculatedSizes["media", default: 0]
- let identifiedSum = cachesSize + logsSize + devSize + appsSize + mediaSize
- // "Other" = used space not accounted for by the 5 categories
- // Free space is shown as a separate explicit segment
- let otherUsed = max(0, usedDiskSpace - identifiedSum)
-
- var items: [DiskCategoryItem] = []
- if cachesSize > 0 {
- items.append(DiskCategoryItem(
- label: "dashboard_radar_caches".localized,
- bytes: cachesSize,
+
+ private static func allCategorySpecs(home: String) -> [CategorySpec] {
+ [
+ CategorySpec(
+ id: "caches",
+ labelKey: "dashboard_radar_caches",
color: Color(red: 0.0, green: 0.75, blue: 0.95),
gradientColors: [Color(red: 0.0, green: 0.75, blue: 0.95), Color(red: 0.0, green: 0.55, blue: 0.85)],
- iconName: "archivebox.fill"
- ))
- }
- if logsSize > 0 {
- items.append(DiskCategoryItem(
- label: "dashboard_radar_logs".localized,
- bytes: logsSize,
+ iconName: "archivebox.fill",
+ paths: ["\(home)/Library/Caches", "/Library/Caches"]
+ ),
+ CategorySpec(
+ id: "logs",
+ labelKey: "dashboard_radar_logs",
color: Color(red: 1.0, green: 0.6, blue: 0.0),
gradientColors: [Color(red: 1.0, green: 0.6, blue: 0.0), Color(red: 0.95, green: 0.45, blue: 0.0)],
- iconName: "doc.text.fill"
- ))
- }
- if devSize > 0 {
- items.append(DiskCategoryItem(
- label: "dashboard_radar_dev".localized,
- bytes: devSize,
+ iconName: "doc.text.fill",
+ paths: ["\(home)/Library/Logs", "/Library/Logs"]
+ ),
+ CategorySpec(
+ id: "dev",
+ labelKey: "dashboard_radar_dev",
color: Color(red: 0.15, green: 0.55, blue: 1.0),
gradientColors: [Color(red: 0.15, green: 0.55, blue: 1.0), Color(red: 0.35, green: 0.35, blue: 0.95)],
- iconName: "hammer.fill"
- ))
- }
- if appsSize > 0 {
- items.append(DiskCategoryItem(
- label: "dashboard_radar_apps".localized,
- bytes: appsSize,
+ iconName: "hammer.fill",
+ paths: ["\(home)/Library/Developer"]
+ ),
+ CategorySpec(
+ id: "apps",
+ labelKey: "dashboard_radar_apps",
color: Color(red: 0.65, green: 0.35, blue: 0.95),
gradientColors: [Color(red: 0.65, green: 0.35, blue: 0.95), Color(red: 0.45, green: 0.2, blue: 0.85)],
- iconName: "app.badge.fill"
- ))
- }
- if mediaSize > 0 {
- items.append(DiskCategoryItem(
- label: "dashboard_radar_media".localized,
- bytes: mediaSize,
+ iconName: "app.badge.fill",
+ paths: ["/Applications", "\(home)/Applications", "/System/Applications"]
+ ),
+ CategorySpec(
+ id: "media",
+ labelKey: "dashboard_radar_media",
color: Color(red: 0.95, green: 0.3, blue: 0.55),
gradientColors: [Color(red: 0.95, green: 0.3, blue: 0.55), Color(red: 0.9, green: 0.2, blue: 0.35)],
- iconName: "photo.stack.fill"
- ))
- }
- if otherUsed > 0 {
- items.append(DiskCategoryItem(
- label: "dashboard_radar_other".localized,
- bytes: otherUsed,
+ iconName: "photo.stack.fill",
+ paths: ["\(home)/Music", "\(home)/Pictures", "\(home)/Movies"]
+ ),
+ CategorySpec(
+ id: "other",
+ labelKey: "dashboard_radar_other",
color: Color(red: 0.45, green: 0.5, blue: 0.6),
gradientColors: [Color(red: 0.45, green: 0.5, blue: 0.6), Color(red: 0.3, green: 0.35, blue: 0.45)],
- iconName: "square.grid.2x2.fill"
- ))
- }
-
- self.diskCategories = items
- self.isCategoriesLoading = false
+ iconName: "square.grid.2x2.fill",
+ paths: []
+ ),
+ ]
}
-
- nonisolated static func calculatePathSize(_ path: String) async -> Int64 {
- let fm = FileManager.default
- let url = URL(fileURLWithPath: path)
- var isDirectory: ObjCBool = false
-
- guard fm.fileExists(atPath: path, isDirectory: &isDirectory) else { return 0 }
- if !isDirectory.boolValue {
- let attribs = try? fm.attributesOfItem(atPath: path)
- return (attribs?[.size] as? Int64) ?? 0
+
+ private static func buildCategoryItems(
+ specs: [CategorySpec],
+ sizes: [String: Int64],
+ completedKeys: Set,
+ otherBytes: Int64,
+ isScanning: Bool
+ ) -> [DiskCategoryItem] {
+ specs.compactMap { spec in
+ if spec.id == "other" {
+ if !isScanning && otherBytes <= 0 { return nil }
+ return DiskCategoryItem(
+ id: spec.id,
+ label: spec.labelKey.localized,
+ bytes: isScanning ? 0 : otherBytes,
+ color: spec.color,
+ gradientColors: spec.gradientColors,
+ iconName: spec.iconName,
+ isScanning: isScanning
+ )
+ }
+ let bytes = sizes[spec.id, default: 0]
+ if !isScanning && bytes <= 0 { return nil }
+ let itemScanning = isScanning && !completedKeys.contains(spec.id)
+ return DiskCategoryItem(
+ id: spec.id,
+ label: spec.labelKey.localized,
+ bytes: bytes,
+ color: spec.color,
+ gradientColors: spec.gradientColors,
+ iconName: spec.iconName,
+ isScanning: itemScanning
+ )
}
-
- let keys: [URLResourceKey] = [.fileSizeKey, .isDirectoryKey]
- guard let enumerator = fm.enumerator(
- at: url,
- includingPropertiesForKeys: keys,
- options: [.skipsHiddenFiles]
- ) else { return 0 }
-
- var totalSize: Int64 = 0
- var yieldCount = 0
-
- while let fileURL = enumerator.nextObject() as? URL {
- guard let values = try? fileURL.resourceValues(forKeys: Set(keys)) else { continue }
- if let isDir = values.isDirectory, isDir {
- continue
+ }
+
+ private func fetchCategoryData() async {
+ isCategoriesLoading = true
+ completedCategoriesCount = 0
+
+ let home = NSHomeDirectory()
+ let specs = Self.allCategorySpecs(home: home)
+ let scanSpecs = specs.filter { !$0.paths.isEmpty }
+
+ var liveSizes: [String: Int64] = [:]
+ var completedKeys = Set()
+ diskCategories = Self.buildCategoryItems(
+ specs: specs,
+ sizes: liveSizes,
+ completedKeys: completedKeys,
+ otherBytes: 0,
+ isScanning: true
+ )
+
+ let stream = AsyncStream<(key: String, bytes: Int64, finished: Bool)> { continuation in
+ let producer = Task {
+ await withTaskGroup(of: Void.self) { group in
+ for spec in scanSpecs {
+ group.addTask {
+ var completedPathBytes: Int64 = 0
+ for path in spec.paths {
+ let baseBytes = completedPathBytes
+ let pathSize = await Self.calculatePathSize(path) { partial in
+ continuation.yield((spec.id, baseBytes + partial, false))
+ }
+ completedPathBytes += pathSize
+ continuation.yield((spec.id, completedPathBytes, false))
+ }
+ continuation.yield((spec.id, completedPathBytes, true))
+ }
+ }
+ }
+ continuation.finish()
}
- totalSize += Int64(values.fileSize ?? 0)
- yieldCount += 1
- if yieldCount % 1000 == 0 {
- await Task.yield()
+ continuation.onTermination = { _ in
+ producer.cancel()
}
}
-
- return totalSize
+
+ for await event in stream {
+ liveSizes[event.key] = event.bytes
+ if event.finished {
+ completedKeys.insert(event.key)
+ completedCategoriesCount = completedKeys.count
+ }
+ diskCategories = Self.buildCategoryItems(
+ specs: specs,
+ sizes: liveSizes,
+ completedKeys: completedKeys,
+ otherBytes: 0,
+ isScanning: true
+ )
+ }
+
+ // "Other" = used space not accounted for by the 5 scanned categories.
+ let identifiedSum = scanSpecs.reduce(Int64(0)) { $0 + liveSizes[$1.id, default: 0] }
+ let otherUsed = max(0, usedDiskSpace - identifiedSum)
+ diskCategories = Self.buildCategoryItems(
+ specs: specs,
+ sizes: liveSizes,
+ completedKeys: completedKeys,
+ otherBytes: otherUsed,
+ isScanning: false
+ )
+ isCategoriesLoading = false
+ }
+
+ nonisolated static func calculatePathSize(_ path: String) async -> Int64 {
+ await calculatePathSize(path, onProgress: nil)
+ }
+
+ nonisolated static func calculatePathSize(
+ _ path: String,
+ onProgress: (@Sendable (Int64) -> Void)?
+ ) async -> Int64 {
+ await Task.detached(priority: .utility) {
+ let fm = FileManager.default
+ let url = URL(fileURLWithPath: path)
+ var isDirectory: ObjCBool = false
+
+ guard fm.fileExists(atPath: path, isDirectory: &isDirectory) else { return 0 }
+ if !isDirectory.boolValue {
+ let attribs = try? fm.attributesOfItem(atPath: path)
+ return (attribs?[.size] as? Int64) ?? 0
+ }
+
+ let keys: Set = [
+ .fileSizeKey,
+ .isDirectoryKey,
+ .isSymbolicLinkKey,
+ .isUbiquitousItemKey,
+ .ubiquitousItemDownloadingStatusKey,
+ ]
+ guard let enumerator = fm.enumerator(
+ at: url,
+ includingPropertiesForKeys: Array(keys),
+ options: [.skipsHiddenFiles]
+ ) else { return 0 }
+
+ var totalSize: Int64 = 0
+ var yieldCount = 0
+ let clock = ContinuousClock()
+ var lastReport = clock.now
+ var finished = false
+
+ while !finished {
+ if Task.isCancelled { break }
+ autoreleasepool {
+ var batchCount = 0
+ while batchCount < 256 {
+ guard let fileURL = enumerator.nextObject() as? URL else {
+ finished = true
+ return
+ }
+ batchCount += 1
+
+ if FileManager.shouldExclude(url: fileURL) {
+ if (try? fileURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true {
+ enumerator.skipDescendants()
+ }
+ continue
+ }
+ guard let values = try? fileURL.resourceValues(forKeys: keys) else { continue }
+ if values.isSymbolicLink == true {
+ if values.isDirectory == true {
+ enumerator.skipDescendants()
+ }
+ continue
+ }
+ if FileManager.isNotDownloadedUbiquitous(values) {
+ if values.isDirectory == true {
+ enumerator.skipDescendants()
+ }
+ continue
+ }
+ if values.isDirectory == true {
+ continue
+ }
+ totalSize += Int64(values.fileSize ?? 0)
+ yieldCount += 1
+ }
+ }
+
+ if let onProgress, clock.now - lastReport >= .milliseconds(180) {
+ lastReport = clock.now
+ onProgress(totalSize)
+ }
+ if yieldCount >= 2000 {
+ yieldCount = 0
+ await Task.yield()
+ }
+ }
+
+ return totalSize
+ }.value
}
var usedDiskSpace: Int64 {
diff --git a/MacOSCleaner/Features/Dashboard/DiskRingsChartView.swift b/MacOSCleaner/Features/Dashboard/DiskRingsChartView.swift
index 4e2ac9d..0a55a60 100644
--- a/MacOSCleaner/Features/Dashboard/DiskRingsChartView.swift
+++ b/MacOSCleaner/Features/Dashboard/DiskRingsChartView.swift
@@ -6,33 +6,47 @@ public struct DiskRingsChartView: View {
let items: [DiskCategoryItem]
let totalUsed: Int64
let totalDisk: Int64
-
- @State private var hoveredID: UUID? = nil
- @State private var selectedID: UUID? = nil
-
- public init(items: [DiskCategoryItem], totalUsed: Int64, totalDisk: Int64) {
+ let isScanning: Bool
+ let completedCategories: Int
+ let totalCategories: Int
+
+ @State private var hoveredID: String? = nil
+ @State private var selectedID: String? = nil
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ public init(
+ items: [DiskCategoryItem],
+ totalUsed: Int64,
+ totalDisk: Int64,
+ isScanning: Bool = false,
+ completedCategories: Int = 0,
+ totalCategories: Int = 0
+ ) {
self.items = items
self.totalUsed = totalUsed
self.totalDisk = totalDisk
+ self.isScanning = isScanning
+ self.completedCategories = completedCategories
+ self.totalCategories = totalCategories
}
-
- private var usedCategoryItems: [DiskCategoryItem] {
- items.filter { $0.bytes > 0 }
- }
-
- private var sortedItems: [DiskCategoryItem] {
- usedCategoryItems.sorted { $0.bytes > $1.bytes }
+
+ private var displayItems: [DiskCategoryItem] {
+ // Keep category order fixed while scanning so live size updates do not reorder rows.
+ if isScanning {
+ return items
+ }
+ return items.filter { $0.bytes > 0 }.sorted { $0.bytes > $1.bytes }
}
-
+
private var freeDisk: Int64 {
max(0, totalDisk - totalUsed)
}
-
+
private var usedPercent: Int {
guard totalDisk > 0 else { return 0 }
return Int((Double(totalUsed) / Double(totalDisk)) * 100)
}
-
+
private func formattedCategoryPercent(for bytes: Int64) -> String {
guard totalUsed > 0, bytes > 0 else { return "0%" }
let raw = (Double(bytes) / Double(totalUsed)) * 100.0
@@ -43,74 +57,82 @@ public struct DiskRingsChartView: View {
return "\(rounded)%"
}
}
-
- private var activeID: UUID? {
+
+ private var activeID: String? {
hoveredID ?? selectedID
}
private var hoveredItem: DiskCategoryItem? {
- sortedItems.first { $0.id == activeID }
+ displayItems.first { $0.id == activeID }
}
-
+
public var body: some View {
VStack(alignment: .leading, spacing: 14) {
cardHeader
-
+
Spacer(minLength: 0)
-
+
HStack(alignment: .center, spacing: 24) {
legendGrid
.frame(width: 250)
-
+
Spacer()
-
+
ringsChart
.frame(width: 270, height: 270)
-
+
Spacer()
}
-
+
Spacer(minLength: 0)
}
.frame(maxHeight: .infinity)
}
-
+
// MARK: - Card Header
-
+
private var cardHeader: some View {
- HStack(alignment: .center) {
+ HStack(alignment: .center, spacing: 10) {
HStack(spacing: 8) {
Image(systemName: "internaldrive.fill")
.font(.title3)
.foregroundColor(.accentColor)
-
+
Text("dashboard_disk_usage".localized)
.font(.headline)
+
+ if isScanning {
+ scanningBadge
+ .transition(.opacity)
+ }
}
-
+ .animation(.easeInOut(duration: 0.2), value: isScanning)
+
Spacer()
-
+
HStack(spacing: 12) {
VStack(alignment: .trailing, spacing: 2) {
Text("dashboard_free".localized)
.font(.caption2)
.foregroundColor(.secondary)
- Text(freeDisk.formattedByteCount())
+ Text(totalDisk > 0 ? freeDisk.formattedByteCount() : "—")
.font(.subheadline)
.fontWeight(.semibold)
+ .monospacedDigit()
.foregroundColor(.primary)
}
-
+
Divider()
.frame(height: 20)
-
+
VStack(alignment: .trailing, spacing: 2) {
Text("dashboard_total".localized)
.font(.caption2)
.foregroundColor(.secondary)
- Text(totalDisk.formattedByteCount())
+ Text(totalDisk > 0 ? totalDisk.formattedByteCount() : "—")
.font(.subheadline)
.fontWeight(.semibold)
+ .monospacedDigit()
.foregroundColor(.primary)
}
}
@@ -126,141 +148,293 @@ public struct DiskRingsChartView: View {
)
}
}
-
+
+ private var scanningBadge: some View {
+ TimelineView(.animation(minimumInterval: 1.0 / 30.0, paused: !isScanning || reduceMotion)) { timeline in
+ let pulse = reduceMotion
+ ? 0.9
+ : 0.45 + 0.55 * (0.5 + 0.5 * sin(timeline.date.timeIntervalSince1970 * 4.0))
+
+ HStack(spacing: 6) {
+ Circle()
+ .fill(Color.accentColor)
+ .frame(width: 6, height: 6)
+ .opacity(pulse)
+
+ Text("disk_analyzer_scanning".localized)
+ .font(.caption)
+ .fontWeight(.medium)
+ .foregroundColor(.accentColor)
+
+ if totalCategories > 0 {
+ Text("\(completedCategories)/\(totalCategories)")
+ .font(.caption)
+ .fontWeight(.semibold)
+ .monospacedDigit()
+ .foregroundColor(.accentColor.opacity(0.85))
+ }
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 3)
+ .background(
+ Capsule()
+ .fill(Color.accentColor.opacity(0.12))
+ )
+ .overlay(
+ Capsule()
+ .strokeBorder(Color.accentColor.opacity(0.25), lineWidth: 1)
+ )
+ }
+ }
+
// MARK: - Rings Chart
-
+
private var ringsChart: some View {
GeometryReader { geo in
let size = min(geo.size.width, geo.size.height)
- let centerHoleRadius: CGFloat = 28
+ let centerHoleRadius: CGFloat = 31
let availableRadius = (size / 2) - centerHoleRadius
- let ringCount = CGFloat(max(1, sortedItems.count))
+ let ringCount = CGFloat(max(1, displayItems.count))
let spacing: CGFloat = 3.0
let ringWidth = max(10, min(30, (availableRadius - spacing * ringCount) / ringCount))
-
- ZStack {
- // Center Interactive Text
- VStack(spacing: 1) {
- if let hovered = hoveredItem {
- let pctString = formattedCategoryPercent(for: hovered.bytes)
- Text(pctString)
- .font(.system(size: 22, weight: .bold, design: .rounded))
- .foregroundColor(hovered.color)
- .transition(.opacity)
- Text(hovered.label)
- .font(.system(size: 9, weight: .medium))
- .foregroundColor(.secondary)
- .lineLimit(1)
- .minimumScaleFactor(0.7)
- .frame(maxWidth: centerHoleRadius * 1.7)
- .transition(.opacity)
- } else {
- Text("\(usedPercent)%")
- .font(.system(size: 22, weight: .bold, design: .rounded))
- .foregroundColor(.primary)
- .transition(.opacity)
- Text("dashboard_used".localized)
- .font(.system(size: 10, weight: .medium))
- .foregroundColor(.secondary.opacity(0.9))
- .lineLimit(1)
- .minimumScaleFactor(0.7)
- .frame(maxWidth: centerHoleRadius * 1.7)
- .transition(.opacity)
+
+ TimelineView(.animation(minimumInterval: 1.0 / 30.0, paused: !isScanning || reduceMotion)) { timeline in
+ let elapsed = timeline.date.timeIntervalSince1970
+
+ ZStack {
+ ringCenterContent(centerHoleRadius: centerHoleRadius)
+
+ ForEach(Array(displayItems.enumerated()), id: \.element.id) { index, item in
+ let radius = (size / 2) - CGFloat(index) * (ringWidth + spacing) - ringWidth / 2
+ ringRow(
+ index: index,
+ item: item,
+ radius: radius,
+ ringWidth: ringWidth,
+ elapsed: elapsed
+ )
}
}
- .animation(.easeInOut(duration: 0.15), value: activeID)
-
- // Concentric Activity Rings
- ForEach(Array(sortedItems.enumerated()), id: \.element.id) { index, item in
- let radius = (size / 2) - CGFloat(index) * (ringWidth + spacing) - ringWidth / 2
- let progress = totalUsed > 0 ? max(0.015, Double(item.bytes) / Double(totalUsed)) : 0.0
- let isHovered = activeID == item.id
- let isDimmed = activeID != nil && !isHovered
-
- ZStack {
- // Background Track
- Circle()
- .stroke(item.color.opacity(0.12), lineWidth: ringWidth)
-
- // Progress Arc
- Circle()
- .trim(from: 0, to: CGFloat(progress))
- .stroke(
- LinearGradient(colors: item.gradientColors, startPoint: .topLeading, endPoint: .bottomTrailing),
- style: StrokeStyle(lineWidth: ringWidth, lineCap: .round)
- )
- .rotationEffect(.degrees(-90))
- .shadow(color: isHovered ? item.color.opacity(0.65) : item.color.opacity(0.15), radius: isHovered ? 5 : 1, x: 0, y: 1)
- }
- .frame(width: max(10, radius * 2), height: max(10, radius * 2))
- .opacity(isDimmed ? 0.35 : 1.0)
- .scaleEffect(isHovered ? 1.03 : 1.0)
- .animation(.spring(response: 0.25, dampingFraction: 0.7), value: isHovered)
- .contentShape(Circle().stroke(lineWidth: ringWidth + 4))
- .onHover { hover in
- withAnimation(.easeInOut(duration: 0.15)) {
- hoveredID = hover ? item.id : nil
- }
- }
- .onTapGesture {
- withAnimation(.easeInOut(duration: 0.15)) {
- selectedID = (selectedID == item.id) ? nil : item.id
- }
- }
+ .frame(width: size, height: size)
+ .position(x: geo.size.width / 2, y: geo.size.height / 2)
+ }
+ }
+ }
+
+ @ViewBuilder
+ private func ringCenterContent(centerHoleRadius: CGFloat) -> some View {
+ ZStack {
+ if isScanning && totalCategories > 0 && hoveredItem == nil {
+ let scanFraction = CGFloat(completedCategories) / CGFloat(totalCategories)
+ let innerDiameter = max(20, (centerHoleRadius * 2) - 4)
+ Circle()
+ .stroke(Color.accentColor.opacity(0.16), lineWidth: 2.5)
+ .frame(width: innerDiameter, height: innerDiameter)
+ Circle()
+ .trim(from: 0, to: max(0.04, scanFraction))
+ .stroke(Color.accentColor, style: StrokeStyle(lineWidth: 2.5, lineCap: .round))
+ .frame(width: innerDiameter, height: innerDiameter)
+ .rotationEffect(.degrees(-90))
+ .animation(.spring(response: 0.35, dampingFraction: 0.8), value: scanFraction)
+ }
+
+ VStack(spacing: 1) {
+ if let hovered = hoveredItem {
+ let valueText = hovered.isScanning && hovered.bytes == 0
+ ? "..."
+ : formattedCategoryPercent(for: hovered.bytes)
+ Text(valueText)
+ .font(.system(size: 21, weight: .bold, design: .rounded))
+ .monospacedDigit()
+ .foregroundColor(hovered.color)
+ .transition(.opacity)
+ Text(hovered.label)
+ .font(.system(size: 9, weight: .medium))
+ .foregroundColor(.secondary)
+ .lineLimit(1)
+ .minimumScaleFactor(0.7)
+ .frame(maxWidth: centerHoleRadius * 1.6)
+ .transition(.opacity)
+ } else {
+ Text("\(usedPercent)%")
+ .font(.system(size: 21, weight: .bold, design: .rounded))
+ .monospacedDigit()
+ .foregroundColor(.primary)
+ .transition(.opacity)
+ Text("dashboard_used".localized)
+ .font(.system(size: 10, weight: .medium))
+ .foregroundColor(.secondary.opacity(0.9))
+ .lineLimit(1)
+ .minimumScaleFactor(0.7)
+ .frame(maxWidth: centerHoleRadius * 1.6)
+ .transition(.opacity)
+ }
+ }
+ .animation(.easeInOut(duration: 0.15), value: activeID)
+ }
+ }
+
+ private func ringRow(
+ index: Int,
+ item: DiskCategoryItem,
+ radius: CGFloat,
+ ringWidth: CGFloat,
+ elapsed: TimeInterval
+ ) -> some View {
+ let progress = totalUsed > 0 ? max(0.015, Double(item.bytes) / Double(totalUsed)) : 0.0
+ let isHovered = activeID == item.id
+ let isDimmed = activeID != nil && !isHovered
+
+ return ZStack {
+ Circle()
+ .stroke(item.color.opacity(item.isScanning ? 0.16 : 0.12), lineWidth: ringWidth)
+
+ if item.isScanning {
+ if item.bytes > 0 && totalUsed > 0 {
+ let liveProgress = min(1.0, max(0.02, Double(item.bytes) / Double(totalUsed)))
+ Circle()
+ .trim(from: 0, to: CGFloat(liveProgress))
+ .stroke(
+ LinearGradient(colors: item.gradientColors, startPoint: .topLeading, endPoint: .bottomTrailing),
+ style: StrokeStyle(lineWidth: ringWidth, lineCap: .round)
+ )
+ .rotationEffect(.degrees(-90))
+ .opacity(0.65)
+ .animation(.easeOut(duration: 0.25), value: liveProgress)
+ }
+
+ if !reduceMotion {
+ scanningRingSweep(index: index, item: item, ringWidth: ringWidth, elapsed: elapsed)
}
+ } else {
+ Circle()
+ .trim(from: 0, to: CGFloat(progress))
+ .stroke(
+ LinearGradient(colors: item.gradientColors, startPoint: .topLeading, endPoint: .bottomTrailing),
+ style: StrokeStyle(lineWidth: ringWidth, lineCap: .round)
+ )
+ .rotationEffect(.degrees(-90))
+ .shadow(color: isHovered ? item.color.opacity(0.65) : item.color.opacity(0.15), radius: isHovered ? 5 : 1, x: 0, y: 1)
+ .animation(.spring(response: 0.5, dampingFraction: 0.82), value: progress)
+ }
+ }
+ .frame(width: max(10, radius * 2), height: max(10, radius * 2))
+ .opacity(isDimmed ? 0.35 : 1.0)
+ .scaleEffect(isHovered ? 1.03 : 1.0)
+ .animation(.spring(response: 0.25, dampingFraction: 0.7), value: isHovered)
+ .contentShape(Circle().stroke(lineWidth: ringWidth + 4))
+ .onHover { hover in
+ withAnimation(.easeInOut(duration: 0.15)) {
+ hoveredID = hover ? item.id : nil
}
- .frame(width: size, height: size)
- .position(x: geo.size.width / 2, y: geo.size.height / 2)
}
+ .onTapGesture {
+ withAnimation(.easeInOut(duration: 0.15)) {
+ selectedID = (selectedID == item.id) ? nil : item.id
+ }
+ }
+ }
+
+ private func scanningRingSweep(
+ index: Int,
+ item: DiskCategoryItem,
+ ringWidth: CGFloat,
+ elapsed: TimeInterval
+ ) -> some View {
+ let sweepAngle = (elapsed * (95 + Double(index) * 18) + Double(index) * 55).truncatingRemainder(dividingBy: 360)
+ return Circle()
+ .trim(from: 0, to: 0.18)
+ .stroke(
+ AngularGradient(
+ gradient: Gradient(colors: [
+ item.color.opacity(0.0),
+ (item.gradientColors.first ?? item.color).opacity(0.45),
+ item.gradientColors.last ?? item.color
+ ]),
+ center: .center,
+ startAngle: .degrees(0),
+ endAngle: .degrees(65)
+ ),
+ style: StrokeStyle(lineWidth: ringWidth, lineCap: .round)
+ )
+ .rotationEffect(.degrees(sweepAngle))
}
-
+
// MARK: - Legend Grid (Single Column Left Layout)
-
+
private var legendGrid: some View {
VStack(spacing: 6) {
- ForEach(sortedItems) { item in
+ ForEach(displayItems) { item in
legendCard(item: item)
}
}
}
-
+
private func legendCard(item: DiskCategoryItem) -> some View {
let isHovered = activeID == item.id
let isDimmed = activeID != nil && !isHovered
let pctString = formattedCategoryPercent(for: item.bytes)
-
- return HStack(spacing: 8) {
- RoundedRectangle(cornerRadius: 6)
- .fill(LinearGradient(colors: item.gradientColors, startPoint: .topLeading, endPoint: .bottomTrailing))
- .frame(width: 24, height: 24)
- .overlay(
- Image(systemName: item.iconName)
- .font(.system(size: 11, weight: .bold))
- .foregroundColor(.white)
- )
-
- VStack(alignment: .leading, spacing: 2) {
- HStack(spacing: 4) {
- Text(item.label)
- .font(.subheadline)
- .fontWeight(.semibold)
- .foregroundColor(.primary)
- .lineLimit(1)
- .minimumScaleFactor(0.8)
-
- Spacer(minLength: 0)
-
- Text(pctString)
- .font(.subheadline)
- .fontWeight(.bold)
- .foregroundColor(isHovered ? item.color : .primary)
+
+ return VStack(alignment: .leading, spacing: 5) {
+ HStack(spacing: 8) {
+ RoundedRectangle(cornerRadius: 6)
+ .fill(LinearGradient(colors: item.gradientColors, startPoint: .topLeading, endPoint: .bottomTrailing))
+ .frame(width: 24, height: 24)
+ .overlay(
+ Image(systemName: item.iconName)
+ .font(.system(size: 11, weight: .bold))
+ .foregroundColor(.white)
+ )
+
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 4) {
+ Text(item.label)
+ .font(.subheadline)
+ .fontWeight(.semibold)
+ .foregroundColor(.primary)
+ .lineLimit(1)
+ .minimumScaleFactor(0.8)
+
+ Spacer(minLength: 0)
+
+ if item.isScanning {
+ if reduceMotion {
+ Circle()
+ .fill(item.color.opacity(0.75))
+ .frame(width: 7, height: 7)
+ } else {
+ ProgressView()
+ .controlSize(.mini)
+ .scaleEffect(0.65)
+ .frame(width: 14, height: 14)
+ }
+ } else {
+ Text(pctString)
+ .font(.subheadline)
+ .fontWeight(.bold)
+ .monospacedDigit()
+ .foregroundColor(isHovered ? item.color : .primary)
+ }
+ }
+
+ if item.isScanning && item.bytes == 0 {
+ Text("disk_analyzer_scanning".localized)
+ .font(.caption)
+ .foregroundColor(.secondary.opacity(0.75))
+ .lineLimit(1)
+ } else {
+ Text(item.formattedValue)
+ .font(.caption)
+ .monospacedDigit()
+ .foregroundColor(.secondary.opacity(0.95))
+ .lineLimit(1)
+ .minimumScaleFactor(0.8)
+ }
}
-
- Text(item.formattedValue)
- .font(.caption)
- .foregroundColor(.secondary.opacity(0.95))
- .lineLimit(1)
- .minimumScaleFactor(0.8)
+ }
+
+ if item.isScanning {
+ scanningBar(color: item.color)
}
}
.padding(.horizontal, 8)
@@ -274,6 +448,7 @@ public struct DiskRingsChartView: View {
RoundedRectangle(cornerRadius: 8, style: .continuous)
.stroke(isHovered ? item.color.opacity(0.65) : Color.white.opacity(0.09), lineWidth: 1)
)
+ .animation(.easeInOut(duration: 0.2), value: item.isScanning)
.contentShape(Rectangle())
.onHover { isHover in
withAnimation(.easeInOut(duration: 0.15)) {
@@ -286,4 +461,34 @@ public struct DiskRingsChartView: View {
}
}
}
+
+ private func scanningBar(color: Color) -> some View {
+ TimelineView(.animation(minimumInterval: 1.0 / 30.0, paused: !isScanning || reduceMotion)) { timeline in
+ GeometryReader { geo in
+ let width = max(1, geo.size.width)
+ let barWidth = width * 0.42
+ let phase = reduceMotion
+ ? 0.3
+ : (timeline.date.timeIntervalSince1970 * 0.75).truncatingRemainder(dividingBy: 1.0)
+ let offsetX = (width + barWidth) * CGFloat(phase) - barWidth
+
+ ZStack(alignment: .leading) {
+ Capsule()
+ .fill(color.opacity(0.15))
+ Capsule()
+ .fill(
+ LinearGradient(
+ colors: [color.opacity(0.15), color.opacity(0.85), color.opacity(0.15)],
+ startPoint: .leading,
+ endPoint: .trailing
+ )
+ )
+ .frame(width: reduceMotion ? width * 0.35 : barWidth)
+ .offset(x: reduceMotion ? 0 : offsetX)
+ }
+ .clipShape(Capsule())
+ }
+ .frame(height: 2)
+ }
+ }
}
diff --git a/MacOSCleaner/Features/DiskAnalyzer/DiskAnalyzerView.swift b/MacOSCleaner/Features/DiskAnalyzer/DiskAnalyzerView.swift
index d0fcbb5..872273d 100644
--- a/MacOSCleaner/Features/DiskAnalyzer/DiskAnalyzerView.swift
+++ b/MacOSCleaner/Features/DiskAnalyzer/DiskAnalyzerView.swift
@@ -3,12 +3,13 @@ import QuickLook
public struct DiskAnalyzerView: View {
let settings: AppSettings
- @State private var viewModel = DiskAnalyzerViewModel()
-
- public init(settings: AppSettings) {
+ @Bindable var viewModel: DiskAnalyzerViewModel
+
+ public init(settings: AppSettings, viewModel: DiskAnalyzerViewModel = DiskAnalyzerViewModel()) {
self.settings = settings
+ self.viewModel = viewModel
}
-
+
public var body: some View {
VStack(spacing: 0) {
headerControlsView
@@ -22,6 +23,8 @@ public struct DiskAnalyzerView: View {
if viewModel.isScanning {
scanningView
+ } else if viewModel.rootURL == nil {
+ idlePromptView
} else if viewModel.displayedItems.isEmpty {
emptyView
} else {
@@ -35,9 +38,6 @@ public struct DiskAnalyzerView: View {
if settings.enableAI {
AIExplanationService.shared.prewarm()
}
- if viewModel.rootURL == nil {
- viewModel.startScan(for: FileManager.default.homeDirectoryForCurrentUser)
- }
}
}
@@ -79,8 +79,16 @@ public struct DiskAnalyzerView: View {
width: 170
)
+ ScanStatusPill(lastUpdatedAt: viewModel.lastUpdatedAt)
+
// Scan Action Button
- Button(action: { viewModel.selectFolderAndScan() }) {
+ Button(action: {
+ if let root = viewModel.rootURL {
+ viewModel.startScan(for: root)
+ } else {
+ viewModel.selectFolderAndScan()
+ }
+ }) {
HStack(spacing: 6) {
Image(systemName: "arrow.clockwise")
Text("disk_analyzer_scan".localized)
@@ -202,6 +210,45 @@ public struct DiskAnalyzerView: View {
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
+ private var idlePromptView: some View {
+ VStack(spacing: 18) {
+ Spacer()
+ Image(systemName: "internaldrive")
+ .font(.system(size: 48))
+ .foregroundStyle(Color.accentColor.gradient)
+
+ Text("disk_analyzer_select_folder".localized)
+ .font(.title3.weight(.semibold))
+
+ HStack(spacing: 10) {
+ Button {
+ viewModel.startScan(for: FileManager.default.homeDirectoryForCurrentUser)
+ } label: {
+ Label("duplicate_folder_home".localized, systemImage: "house")
+ }
+ .prominentGlassButtonStyle(tint: .accentColor)
+
+ Button {
+ let downloads = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first
+ ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Downloads")
+ viewModel.startScan(for: downloads)
+ } label: {
+ Label("duplicate_folder_downloads".localized, systemImage: "arrow.down.circle")
+ }
+ .secondaryGlassButtonStyle()
+
+ Button {
+ viewModel.selectFolderAndScan()
+ } label: {
+ Label("duplicate_folder_custom".localized, systemImage: "folder.badge.plus")
+ }
+ .secondaryGlassButtonStyle()
+ }
+ Spacer()
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+
private var emptyView: some View {
VStack(spacing: 12) {
Spacer()
diff --git a/MacOSCleaner/Features/DiskAnalyzer/DiskAnalyzerViewModel.swift b/MacOSCleaner/Features/DiskAnalyzer/DiskAnalyzerViewModel.swift
index b37f4c0..5d9f0c4 100644
--- a/MacOSCleaner/Features/DiskAnalyzer/DiskAnalyzerViewModel.swift
+++ b/MacOSCleaner/Features/DiskAnalyzer/DiskAnalyzerViewModel.swift
@@ -20,7 +20,8 @@ public final class DiskAnalyzerViewModel {
public var quickLookURL: URL?
public var selectedCategory: FileCategory = .all
public var searchQuery: String = ""
-
+ public var lastUpdatedAt: Date?
+
private var scanTask: Task?
public init() {}
@@ -87,6 +88,7 @@ public final class DiskAnalyzerViewModel {
self.rootItem = scannedRoot
self.pathTrail = [scannedRoot]
+ self.lastUpdatedAt = Date()
self.isScanning = false
} catch {
self.logger.error("Scan failed: \(error.localizedDescription)")
diff --git a/MacOSCleaner/Features/DiskAnalyzer/DiskScanner.swift b/MacOSCleaner/Features/DiskAnalyzer/DiskScanner.swift
index 29a3fb5..cabb5c4 100644
--- a/MacOSCleaner/Features/DiskAnalyzer/DiskScanner.swift
+++ b/MacOSCleaner/Features/DiskAnalyzer/DiskScanner.swift
@@ -215,6 +215,7 @@ public actor DiskScanner {
.isDirectoryKey,
.isSymbolicLinkKey,
.linkCountKey,
+ .isUbiquitousItemKey,
.ubiquitousItemDownloadingStatusKey,
]
diff --git a/MacOSCleaner/Features/Duplicates/DuplicatesView.swift b/MacOSCleaner/Features/Duplicates/DuplicatesView.swift
index 0968969..653ae46 100644
--- a/MacOSCleaner/Features/Duplicates/DuplicatesView.swift
+++ b/MacOSCleaner/Features/Duplicates/DuplicatesView.swift
@@ -11,12 +11,13 @@ import ImageIO
public struct DuplicatesView: View {
let settings: AppSettings
- @State private var viewModel = DuplicatesViewModel()
+ @Bindable var viewModel: DuplicatesViewModel
@State private var selectedGroupId: UUID?
@State private var quickLookURL: URL?
- public init(settings: AppSettings) {
+ public init(settings: AppSettings, viewModel: DuplicatesViewModel = DuplicatesViewModel()) {
self.settings = settings
+ self.viewModel = viewModel
}
private var selectedGroup: DuplicateGroup? {
@@ -317,11 +318,12 @@ public struct DuplicatesView: View {
}
.help("disk_analyzer_quick_look".localized)
} else {
- Image(nsImage: NSWorkspace.shared.icon(forFile: fileURL.path))
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 48, height: 48)
- .padding(.top, 4)
+ CachedFileIconView(path: fileURL.path, size: 48) {
+ Image(systemName: "doc.fill")
+ .font(.system(size: 28))
+ .foregroundStyle(.secondary)
+ }
+ .padding(.top, 4)
}
VStack(spacing: 3) {
@@ -358,9 +360,11 @@ public struct DuplicatesView: View {
quickLookURL = item.url
}
}) {
- Image(nsImage: NSWorkspace.shared.icon(forFile: item.path))
- .resizable()
- .frame(width: 22, height: 22)
+ CachedFileIconView(path: item.path, size: 22) {
+ Image(systemName: isImage ? "photo" : "doc")
+ .font(.system(size: 14))
+ .foregroundStyle(.secondary)
+ }
}
.buttonStyle(.plain)
.help(isImage ? "disk_analyzer_quick_look".localized : "")
@@ -536,9 +540,11 @@ private struct DuplicateThumbnailView: View {
.resizable()
.aspectRatio(contentMode: .fit)
} else {
- Image(nsImage: NSWorkspace.shared.icon(forFile: url.path))
- .resizable()
- .aspectRatio(contentMode: .fit)
+ CachedFileIconView(path: url.path, size: 48) {
+ Image(systemName: "doc")
+ .font(.system(size: 24))
+ .foregroundStyle(.secondary)
+ }
}
}
.task(id: url) {
diff --git a/MacOSCleaner/Features/Privacy/PrivacyNetworkView.swift b/MacOSCleaner/Features/Privacy/PrivacyNetworkView.swift
index 50f4f9f..e4f574a 100644
--- a/MacOSCleaner/Features/Privacy/PrivacyNetworkView.swift
+++ b/MacOSCleaner/Features/Privacy/PrivacyNetworkView.swift
@@ -87,9 +87,11 @@ struct PrivacyNetworkView: View {
VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 10) {
if let url = item.bundleURL {
- Image(nsImage: NSWorkspace.shared.icon(forFile: url.path))
- .resizable()
- .frame(width: 24, height: 24)
+ CachedFileIconView(path: url.path, size: 24, cornerRadius: 5) {
+ Image(systemName: item.isRestrictedByPermissions ? "lock.shield" : "terminal")
+ .font(.title3)
+ .foregroundStyle(.secondary)
+ }
} else {
Image(systemName: item.isRestrictedByPermissions ? "lock.shield" : "terminal")
.font(.title3)
diff --git a/MacOSCleaner/Features/Privacy/PrivacyTCCView.swift b/MacOSCleaner/Features/Privacy/PrivacyTCCView.swift
index 2601db6..4ee5f51 100644
--- a/MacOSCleaner/Features/Privacy/PrivacyTCCView.swift
+++ b/MacOSCleaner/Features/Privacy/PrivacyTCCView.swift
@@ -162,9 +162,11 @@ struct PrivacyTCCView: View {
VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 10) {
if let url = group.appURL {
- Image(nsImage: NSWorkspace.shared.icon(forFile: url.path))
- .resizable()
- .frame(width: 28, height: 28)
+ CachedFileIconView(path: url.path, size: 28, cornerRadius: 6) {
+ Image(systemName: "app.dashed")
+ .font(.title2)
+ .foregroundStyle(.secondary)
+ }
} else {
Image(systemName: "app.dashed")
.font(.title2)
diff --git a/MacOSCleaner/Features/Privacy/PrivacyView.swift b/MacOSCleaner/Features/Privacy/PrivacyView.swift
index 3fd1f4e..9b161da 100644
--- a/MacOSCleaner/Features/Privacy/PrivacyView.swift
+++ b/MacOSCleaner/Features/Privacy/PrivacyView.swift
@@ -4,9 +4,19 @@ struct PrivacyView: View {
let permissionsManager: PermissionsManager
@Binding var initialBundleIDFilter: String?
- @State private var viewModel = PrivacyViewModel()
+ @Bindable var viewModel: PrivacyViewModel
@FocusState private var isSearchFocused: Bool
+ init(
+ permissionsManager: PermissionsManager,
+ initialBundleIDFilter: Binding,
+ viewModel: PrivacyViewModel = PrivacyViewModel()
+ ) {
+ self.permissionsManager = permissionsManager
+ self._initialBundleIDFilter = initialBundleIDFilter
+ self.viewModel = viewModel
+ }
+
var body: some View {
GlassEffectContainer {
VStack(spacing: 0) {
diff --git a/MacOSCleaner/Features/Privacy/TCCService.swift b/MacOSCleaner/Features/Privacy/TCCService.swift
index 9bfbe14..689ab80 100644
--- a/MacOSCleaner/Features/Privacy/TCCService.swift
+++ b/MacOSCleaner/Features/Privacy/TCCService.swift
@@ -439,20 +439,26 @@ public actor TCCService {
return map
}
+ private struct BundleEntry: Sendable {
+ let bundleID: String
+ let url: URL
+ }
+
+ private struct ResolvedIdentity: Sendable {
+ let bundleID: String
+ let identity: AppIdentity
+ }
+
private func resolveIdentities(for bundleIndex: [String: URL]) async -> [String: AppIdentity] {
let runner = (commandRunner as? CommandRunner) ?? CommandRunner()
- return await withTaskGroup(of: (String, AppIdentity).self) { group in
- for (bundleID, url) in bundleIndex {
- group.addTask {
- let identity = await AppIdentity.resolve(from: url, commandRunner: runner)
- return (bundleID, identity)
- }
- }
- var result: [String: AppIdentity] = [:]
- for await (bundleID, identity) in group {
- result[bundleID] = identity
- }
- return result
- }
+ let entries = bundleIndex.map { BundleEntry(bundleID: $0.key, url: $0.value) }
+ let resolved: [ResolvedIdentity] = (try? await UninstallerService.mapWithBoundedConcurrency(
+ items: entries,
+ maxConcurrent: UninstallerService.maxConcurrentDiscoveryTasks
+ ) { entry in
+ let identity = await AppIdentity.resolve(from: entry.url, commandRunner: runner)
+ return ResolvedIdentity(bundleID: entry.bundleID, identity: identity)
+ }) ?? []
+ return Dictionary(uniqueKeysWithValues: resolved.map { ($0.bundleID, $0.identity) })
}
}
diff --git a/MacOSCleaner/Features/Processes/ProcessRow.swift b/MacOSCleaner/Features/Processes/ProcessRow.swift
index 5e95d78..0d21057 100644
--- a/MacOSCleaner/Features/Processes/ProcessRow.swift
+++ b/MacOSCleaner/Features/Processes/ProcessRow.swift
@@ -9,7 +9,6 @@ struct ProcessRow: View {
let onForceKill: () -> Void
let onToggleSelection: () -> Void
- @State private var appIcon: NSImage?
@State private var isExpanded = false
@State private var aiExplanation = ""
@State private var verdict: AIExplanationResult.Verdict? = nil
@@ -25,15 +24,10 @@ struct ProcessRow: View {
}
.buttonStyle(.plain)
- if let icon = appIcon {
- Image(nsImage: icon)
- .resizable()
- .frame(width: 20, height: 20)
- } else {
+ CachedFileIconView(path: process.path, size: 20) {
Image(systemName: iconName)
.font(.system(size: 18))
.foregroundColor(iconColor)
- .frame(width: 24)
}
VStack(alignment: .leading, spacing: 3) {
@@ -186,14 +180,6 @@ struct ProcessRow: View {
}
}
.padding(.vertical, 10)
- .task {
- await loadAppIcon()
- }
- }
-
- private func loadAppIcon() async {
- guard let path = process.path else { return }
- appIcon = NSWorkspace.shared.icon(forFile: path)
}
private var iconName: String {
diff --git a/MacOSCleaner/Features/Processes/ProcessesView.swift b/MacOSCleaner/Features/Processes/ProcessesView.swift
index 0a6e71f..cd87ede 100644
--- a/MacOSCleaner/Features/Processes/ProcessesView.swift
+++ b/MacOSCleaner/Features/Processes/ProcessesView.swift
@@ -2,12 +2,13 @@ import SwiftUI
public struct ProcessesView: View {
let settings: AppSettings
- @State private var viewModel = ProcessesViewModel()
+ @Bindable var viewModel: ProcessesViewModel
@State private var isEditMode = false
@State private var expandedGroupIDs: Set = []
- public init(settings: AppSettings) {
+ public init(settings: AppSettings, viewModel: ProcessesViewModel = ProcessesViewModel()) {
self.settings = settings
+ self.viewModel = viewModel
}
public var body: some View {
@@ -22,7 +23,7 @@ public struct ProcessesView: View {
.transition(.move(edge: .top).combined(with: .opacity))
}
- if viewModel.isLoading {
+ if viewModel.isLoading && viewModel.processes.isEmpty {
AnimatedScanView(
title: "processes_scanning".localized,
subtitle: "",
@@ -30,7 +31,7 @@ public struct ProcessesView: View {
totalSteps: 1
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
- } else if let error = viewModel.lastError {
+ } else if let error = viewModel.lastError, viewModel.processes.isEmpty {
errorView(error)
} else if viewModel.filteredProcesses.isEmpty && !viewModel.searchText.isEmpty {
emptySearchView
@@ -57,7 +58,10 @@ public struct ProcessesView: View {
if settings.enableAI {
AIExplanationService.shared.prewarm()
}
- Task { await viewModel.scan() }
+ Task { await viewModel.scanIfNeeded() }
+ if settings.processRefreshInterval != .manual {
+ viewModel.startAutoRefresh(interval: settings.processRefreshInterval)
+ }
}
.onDisappear {
viewModel.stopAutoRefresh()
@@ -149,6 +153,8 @@ public struct ProcessesView: View {
.glassButtonStyle()
.help("processes_tooltip_whitelist".localized)
+ ScanStatusPill(lastUpdatedAt: viewModel.lastUpdatedAt)
+
Button(action: { Task { await viewModel.scan() } }) {
Image(systemName: "arrow.clockwise")
}
@@ -476,26 +482,14 @@ public struct ProcessesView: View {
private struct AppIconView: View {
let path: String?
- @State private var icon: NSImage?
var body: some View {
- if let icon {
- Image(nsImage: icon)
- .resizable()
- .frame(width: 20, height: 20)
- } else {
+ CachedFileIconView(path: path, size: 20) {
Image(systemName: "app.fill")
.font(.system(size: 18))
.foregroundColor(.secondary)
- .frame(width: 24)
- .task { await loadIcon() }
}
}
-
- private func loadIcon() async {
- guard let path else { return }
- icon = NSWorkspace.shared.icon(forFile: path)
- }
}
#Preview {
diff --git a/MacOSCleaner/Features/Processes/ProcessesViewModel.swift b/MacOSCleaner/Features/Processes/ProcessesViewModel.swift
index a795468..bb8150e 100644
--- a/MacOSCleaner/Features/Processes/ProcessesViewModel.swift
+++ b/MacOSCleaner/Features/Processes/ProcessesViewModel.swift
@@ -13,6 +13,7 @@ public final class ProcessesViewModel {
}
public var isLoading: Bool = false
public var lastError: String? = nil
+ public var lastUpdatedAt: Date? = nil
public var blacklist: [String] = []
public var whitelist: [String] = []
public var showBlacklistAlert = false
@@ -166,6 +167,11 @@ public final class ProcessesViewModel {
self.processManager = processManager
}
+ public func scanIfNeeded() async {
+ guard lastUpdatedAt == nil, !isLoading else { return }
+ await scan()
+ }
+
public func scan() async {
isLoading = true
lastError = nil
@@ -176,6 +182,7 @@ public final class ProcessesViewModel {
let wl = Array(await processManager.getWhitelist()).sorted()
blacklist = bl
whitelist = wl
+ lastUpdatedAt = Date()
} catch {
lastError = error.localizedDescription
logger.error("Scan failed: \(error.localizedDescription)")
diff --git a/MacOSCleaner/Features/Settings/SettingsGeneralView.swift b/MacOSCleaner/Features/Settings/SettingsGeneralView.swift
index a2db1d2..87a5369 100644
--- a/MacOSCleaner/Features/Settings/SettingsGeneralView.swift
+++ b/MacOSCleaner/Features/Settings/SettingsGeneralView.swift
@@ -104,7 +104,7 @@ struct SettingsGeneralView: View {
VStack(alignment: .leading, spacing: 12) {
SettingsLabeledControl(
"settings_current_version".localized,
- subtitle: "v\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "3.0.0")"
+ subtitle: "v\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "3.0.1")"
) {
if isCheckingForUpdates {
ProgressView().controlSize(.small)
diff --git a/MacOSCleaner/Features/Settings/SettingsView.swift b/MacOSCleaner/Features/Settings/SettingsView.swift
index e9961de..10cd07d 100644
--- a/MacOSCleaner/Features/Settings/SettingsView.swift
+++ b/MacOSCleaner/Features/Settings/SettingsView.swift
@@ -188,6 +188,6 @@ struct SettingsView: View {
settings: AppSettings(),
permissionsManager: PermissionsManager(),
onForget: {},
- availableUpdate: .constant(AvailableUpdate(version: "3.0.0", dmgURL: nil))
+ availableUpdate: .constant(AvailableUpdate(version: "3.0.1", dmgURL: nil))
)
}
diff --git a/MacOSCleaner/Features/StartupServices/StartupServicesView.swift b/MacOSCleaner/Features/StartupServices/StartupServicesView.swift
index b947d68..cc01777 100644
--- a/MacOSCleaner/Features/StartupServices/StartupServicesView.swift
+++ b/MacOSCleaner/Features/StartupServices/StartupServicesView.swift
@@ -2,9 +2,14 @@ import SwiftUI
public struct StartupServicesView: View {
let settings: AppSettings
- @State private var viewModel = StartupServicesViewModel()
+ @Bindable var viewModel: StartupServicesViewModel
@State private var serviceToDelete: StartupService? = nil
+ public init(settings: AppSettings, viewModel: StartupServicesViewModel = StartupServicesViewModel()) {
+ self.settings = settings
+ self.viewModel = viewModel
+ }
+
public var body: some View {
GlassEffectContainer {
VStack(spacing: 0) {
@@ -12,6 +17,7 @@ public struct StartupServicesView: View {
Spacer()
filterPicker
Spacer()
+ ScanStatusPill(lastUpdatedAt: viewModel.lastUpdatedAt)
Button(action: { Task { await viewModel.scan() } }) {
Image(systemName: "arrow.clockwise")
}
@@ -21,7 +27,7 @@ public struct StartupServicesView: View {
Divider()
- if viewModel.isLoading {
+ if viewModel.isLoading && viewModel.services.isEmpty {
AnimatedScanView(
title: "startup_scanning".localized,
subtitle: "",
@@ -64,7 +70,7 @@ public struct StartupServicesView: View {
if settings.enableAI {
AIExplanationService.shared.prewarm()
}
- Task { await viewModel.scan() }
+ Task { await viewModel.scanIfNeeded() }
}
}
diff --git a/MacOSCleaner/Features/StartupServices/StartupServicesViewModel.swift b/MacOSCleaner/Features/StartupServices/StartupServicesViewModel.swift
index 2d289eb..1c1f36e 100644
--- a/MacOSCleaner/Features/StartupServices/StartupServicesViewModel.swift
+++ b/MacOSCleaner/Features/StartupServices/StartupServicesViewModel.swift
@@ -10,6 +10,7 @@ public final class StartupServicesViewModel {
public var loginItemsAccess: BackgroundItemsAccessStatus = .available
public var isLoading: Bool = false
public var lastError: String? = nil
+ public var lastUpdatedAt: Date? = nil
public var filter: StartupFilter = .all
public var filteredServices: [StartupService] {
@@ -53,6 +54,12 @@ public final class StartupServicesViewModel {
self.manager = manager
}
+ @MainActor
+ public func scanIfNeeded() async {
+ guard lastUpdatedAt == nil, !isLoading else { return }
+ await scan()
+ }
+
@MainActor
public func scan() async {
isLoading = true
@@ -62,6 +69,7 @@ public final class StartupServicesViewModel {
services = result.services
loginItems = result.loginItems
loginItemsAccess = result.loginItemsAccess
+ lastUpdatedAt = Date()
} catch {
lastError = error.localizedDescription
}
diff --git a/MacOSCleaner/Features/Uninstaller/AIExplanationService.swift b/MacOSCleaner/Features/Uninstaller/AIExplanationService.swift
index e385ee1..a805333 100644
--- a/MacOSCleaner/Features/Uninstaller/AIExplanationService.swift
+++ b/MacOSCleaner/Features/Uninstaller/AIExplanationService.swift
@@ -82,11 +82,34 @@ public actor AIExplanationService {
availabilityState == .ready
}
+ private var didPrewarm = false
+ private var prewarmAttempts = 0
+
public nonisolated func prewarm() {
+ guard isAvailable else { return }
+ Task.detached(priority: .background) {
+ await self.prewarmIfNeeded()
+ }
+ }
+
+ public func prewarmIfNeeded() {
+ guard !didPrewarm else { return }
+ didPrewarm = true
+ prewarmAttempts += 1
+ guard isAvailable else { return }
let session = LanguageModelSession(model: SystemLanguageModel.default)
session.prewarm()
}
+ func prewarmAttemptCountForTesting() -> Int {
+ prewarmAttempts
+ }
+
+ func resetPrewarmForTesting() {
+ didPrewarm = false
+ prewarmAttempts = 0
+ }
+
// MARK: - Localized Instructions via Swift switch (No "Respond in X" in instructions)
private func instructionForRelation(language: AppLanguage) -> String {
switch language {
diff --git a/MacOSCleaner/Features/Uninstaller/AppDiscovery.swift b/MacOSCleaner/Features/Uninstaller/AppDiscovery.swift
index cd3ab30..a324170 100644
--- a/MacOSCleaner/Features/Uninstaller/AppDiscovery.swift
+++ b/MacOSCleaner/Features/Uninstaller/AppDiscovery.swift
@@ -12,20 +12,42 @@ public actor AppDiscovery {
private let fileManager: FileManager
private let commandRunner: CommandRunner
private let homebrewCellarDirectories: [URL]
+ private let customSearchDirectories: [URL]?
+ private let customExternalVolumesRoot: URL?
public init(
fileManager: FileManager = .default,
commandRunner: CommandRunner = CommandRunner(),
- homebrewCellarDirectories: [URL] = AppDiscovery.defaultHomebrewCellarDirectories
+ homebrewCellarDirectories: [URL] = AppDiscovery.defaultHomebrewCellarDirectories,
+ searchDirectories: [URL]? = nil,
+ externalVolumesRoot: URL? = nil
) {
self.fileManager = fileManager
self.commandRunner = commandRunner
self.homebrewCellarDirectories = homebrewCellarDirectories
+ self.customSearchDirectories = searchDirectories
+ self.customExternalVolumesRoot = externalVolumesRoot
}
public func findAll() async -> [URL] {
var urls: [URL] = []
+ if let customSearchDirectories {
+ for dir in customSearchDirectories {
+ urls.append(contentsOf: Self.applicationBundles(in: dir, fileManager: fileManager))
+ }
+ if let customExternalVolumesRoot {
+ for dir in Self.externalVolumeApplicationDirectories(fileManager: fileManager, volumesRoot: customExternalVolumesRoot) {
+ urls.append(contentsOf: Self.applicationBundles(in: dir, fileManager: fileManager))
+ }
+ }
+ urls.append(contentsOf: Self.homebrewApplications(
+ in: homebrewCellarDirectories,
+ fileManager: fileManager
+ ))
+ return NormalizedPath.unique(urls).filter { !Self.isUndeletableSystemApp($0) }
+ }
+
// Standard app directories
let appDirs = [
NormalizedPath.url("/Applications", isDirectory: true),
@@ -37,6 +59,12 @@ public actor AppDiscovery {
urls.append(contentsOf: Self.applicationBundles(in: dir, fileManager: fileManager))
}
+ // Mounted local writable external volumes (e.g. macOS App Store external SSD installs
+ // at /Volumes//Applications). Skips network shares, read-only DMGs, and Time Machine.
+ for dir in Self.externalVolumeApplicationDirectories(fileManager: fileManager, volumesRoot: customExternalVolumesRoot) {
+ urls.append(contentsOf: Self.applicationBundles(in: dir, fileManager: fileManager))
+ }
+
// Homebrew formulae can expose user-facing apps directly inside a keg
// (for example python@3.x/3.x.y/IDLE 3.app). Scan only the fixed
// Cellar/formula/version/*.app shape; never recurse through formula contents.
@@ -82,19 +110,73 @@ public actor AppDiscovery {
return NormalizedPath.unique(urls).filter { !Self.isUndeletableSystemApp($0) }
}
- /// Top-level `.app` plus one nested level (e.g. `/Applications/Utilities/*.app`).
+ /// Discovers `/Applications` directories on mounted local, writable,
+ /// browsable non-root volumes (skips read-only DMG installers, SMB/NFS shares, Time Machine).
+ static func externalVolumeApplicationDirectories(
+ fileManager: FileManager = .default,
+ volumesRoot: URL? = nil
+ ) -> [URL] {
+ var result: [URL] = []
+
+ if let volumesRoot {
+ guard let volumes = directoryContents(at: volumesRoot, fileManager: fileManager) else {
+ return []
+ }
+ for volume in volumes where isDirectory(volume) {
+ guard SafetyManager.isAllowedExternalVolumeName(volume.lastPathComponent) else { continue }
+ let appsDir = volume.appendingPathComponent("Applications", isDirectory: true)
+ var isDir: ObjCBool = false
+ if fileManager.fileExists(atPath: appsDir.path, isDirectory: &isDir), isDir.boolValue {
+ result.append(NormalizedPath.url(appsDir.path, isDirectory: true))
+ }
+ }
+ return result
+ }
+
+ let keys: [URLResourceKey] = [
+ .volumeIsLocalKey,
+ .volumeIsReadOnlyKey,
+ .volumeIsBrowsableKey,
+ .volumeIsRootFileSystemKey,
+ ]
+ guard let mountedVolumes = fileManager.mountedVolumeURLs(
+ includingResourceValuesForKeys: keys,
+ options: [.skipHiddenVolumes]
+ ) else {
+ return []
+ }
+
+ for volume in mountedVolumes {
+ guard let values = try? volume.resourceValues(forKeys: Set(keys)) else { continue }
+ guard values.volumeIsRootFileSystem != true else { continue }
+ guard values.volumeIsLocal == true else { continue }
+ guard values.volumeIsReadOnly != true else { continue }
+ guard values.volumeIsBrowsable != false else { continue }
+ guard SafetyManager.isAllowedExternalVolumeName(volume.lastPathComponent) else { continue }
+
+ let appsDir = volume.appendingPathComponent("Applications", isDirectory: true)
+ var isDir: ObjCBool = false
+ if fileManager.fileExists(atPath: appsDir.path, isDirectory: &isDir), isDir.boolValue {
+ result.append(NormalizedPath.url(appsDir.path, isDirectory: true))
+ }
+ }
+ return result
+ }
+
+ /// Top-level `.app` (including valid symlinks to `.app` bundles on external SSDs)
+ /// plus one nested level (e.g. `/Applications/Utilities/*.app`).
static func applicationBundles(in directory: URL, fileManager: FileManager = .default) -> [URL] {
guard let contents = directoryContents(at: directory, fileManager: fileManager) else { return [] }
var apps: [URL] = []
for item in contents {
- if item.pathExtension.lowercased() == "app", isDirectory(item) {
+ if item.pathExtension.lowercased() == "app", isAppDirectory(item, fileManager: fileManager) {
apps.append(item)
continue
}
guard isDirectory(item),
let nested = directoryContents(at: item, fileManager: fileManager)
else { continue }
- for child in nested where child.pathExtension.lowercased() == "app" && isDirectory(child) {
+ for child in nested where child.pathExtension.lowercased() == "app" && isAppDirectory(child, fileManager: fileManager) {
apps.append(child)
}
}
@@ -207,4 +289,13 @@ public actor AppDiscovery {
(try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true
}
+ /// True for a real `.app` bundle directory OR a valid symlink resolving to an existing directory
+ /// (e.g. an app offloaded to an external SSD and symlinked into `/Applications`).
+ /// Broken symlinks (unplugged drive) return `false`.
+ private static func isAppDirectory(_ url: URL, fileManager: FileManager) -> Bool {
+ if isDirectory(url) { return true }
+ var isDir: ObjCBool = false
+ return fileManager.fileExists(atPath: url.path, isDirectory: &isDir) && isDir.boolValue
+ }
+
}
diff --git a/MacOSCleaner/Features/Uninstaller/AppIdentity.swift b/MacOSCleaner/Features/Uninstaller/AppIdentity.swift
index ef1f0c1..f9701f8 100644
--- a/MacOSCleaner/Features/Uninstaller/AppIdentity.swift
+++ b/MacOSCleaner/Features/Uninstaller/AppIdentity.swift
@@ -1,4 +1,5 @@
import Foundation
+import Security
public struct AppIdentity: Sendable, Hashable {
public let bundleID: String
@@ -32,20 +33,22 @@ public struct AppIdentity: Sendable, Hashable {
public extension AppIdentity {
static func resolve(from url: URL, commandRunner: CommandRunner = CommandRunner()) async -> AppIdentity {
- let bundle = Bundle(url: url)
- let bundleID = bundle?.bundleIdentifier ?? "unknown.\(url.deletingPathExtension().lastPathComponent)"
- let appName = url.deletingPathExtension().lastPathComponent
- let bundleName = bundle?.infoDictionary?["CFBundleName"] as? String
- let bundleVersion = bundle?.infoDictionary?["CFBundleShortVersionString"] as? String
- let executableName = bundle?.infoDictionary?["CFBundleExecutable"] as? String ?? appName
-
- let teamID = await extractTeamID(url: url, commandRunner: commandRunner)
- let authority = await extractSigningAuthority(url: url, commandRunner: commandRunner)
- let isAdHoc = authority?.contains("Ad Hoc") == true || authority?.contains("not signed") == true
- let isAppStore = fileExists(at: url.appendingPathComponent("Contents/_MASReceipt"))
- let entitlements = await extractEntitlements(url: url, commandRunner: commandRunner)
- let isSandboxed = entitlements?["com.apple.security.app-sandbox"] as? Bool ?? false
- let appGroups = Set(entitlements?["com.apple.security.application-groups"] as? [String] ?? [])
+ let (bundleID, appName, bundleName, bundleVersion, executableName, signing, isAppStore) = autoreleasepool {
+ let bundle = Bundle(url: url)
+ let bid = bundle?.bundleIdentifier ?? "unknown.\(url.deletingPathExtension().lastPathComponent)"
+ let name = url.deletingPathExtension().lastPathComponent
+ let bName = bundle?.infoDictionary?["CFBundleName"] as? String
+ let bVersion = bundle?.infoDictionary?["CFBundleShortVersionString"] as? String
+ let execName = bundle?.infoDictionary?["CFBundleExecutable"] as? String ?? name
+ let signMeta = extractSigningMetadata(url: url)
+ let mas = fileExists(at: url.appendingPathComponent("Contents/_MASReceipt"))
+ return (bid, name, bName, bVersion, execName, signMeta, mas)
+ }
+ let teamID = signing.teamID
+ let authority = signing.authority
+ let isAdHoc = signing.isAdHoc
+ let isSandboxed = signing.isSandboxed
+ let appGroups = signing.appGroups
let frameworkNames = await scanFrameworks(url: url)
let xpcServiceNames = await scanXPCServices(url: url)
@@ -95,35 +98,61 @@ public extension AppIdentity {
// MARK: - Private helpers
-private func extractTeamID(url: URL, commandRunner: CommandRunner) async -> String? {
- let result = try? await commandRunner.run(command: "/usr/bin/codesign", arguments: ["-dv", "--verbose=4", url.path])
- guard let output = result?.stderr else { return nil }
- if let range = output.range(of: "TeamIdentifier=") {
- let start = range.upperBound
- let end = output[start...].firstIndex(where: { $0.isWhitespace || $0.isNewline }) ?? output.endIndex
- return String(output[start..
+
+ static let unsigned = SigningMetadata(
+ teamID: nil,
+ authority: nil,
+ isAdHoc: false,
+ isSandboxed: false,
+ appGroups: []
+ )
}
-private func extractSigningAuthority(url: URL, commandRunner: CommandRunner) async -> String? {
- let result = try? await commandRunner.run(command: "/usr/bin/codesign", arguments: ["-dv", "--verbose=4", url.path])
- guard let output = result?.stderr else { return nil }
- if let range = output.range(of: "Authority=") {
- let start = range.upperBound
- let end = output[start...].firstIndex(where: { $0.isWhitespace || $0.isNewline }) ?? output.endIndex
- return String(output[start.. SigningMetadata {
+ var staticCode: SecStaticCode?
+ guard SecStaticCodeCreateWithPath(url as CFURL, SecCSFlags(), &staticCode) == errSecSuccess,
+ let code = staticCode else {
+ return .unsigned
+ }
+
+ var infoRef: CFDictionary?
+ let flags = SecCSFlags(rawValue: kSecCSSigningInformation)
+ guard SecCodeCopySigningInformation(code, flags, &infoRef) == errSecSuccess,
+ let info = infoRef as? [String: Any] else {
+ return .unsigned
+ }
+
+ let rawTeam = (info[kSecCodeInfoTeamIdentifier as String] as? String)?
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ let teamID = (rawTeam?.isEmpty == false) ? rawTeam : nil
+
+ let rawFlags = (info[kSecCodeInfoFlags as String] as? NSNumber)?.uint32Value ?? 0
+ let isAdHoc = (rawFlags & SecCodeSignatureFlags.adhoc.rawValue) != 0
+
+ var authority: String?
+ if let certs = info[kSecCodeInfoCertificates as String] as? [SecCertificate],
+ let leaf = certs.first {
+ authority = SecCertificateCopySubjectSummary(leaf) as String?
}
- return nil
-}
-private func extractEntitlements(url: URL, commandRunner: CommandRunner) async -> [String: Any]? {
- let result = try? await commandRunner.run(command: "/usr/bin/codesign", arguments: ["-d", "--entitlements", ":-", "--xml", url.path])
- guard let output = result?.stdout, !output.isEmpty,
- let data = output.data(using: .utf8),
- let plist = try? PropertyListSerialization.propertyList(from: data, format: nil)
- else { return nil }
- return plist as? [String: Any]
+ let entitlements = info[kSecCodeInfoEntitlementsDict as String] as? [String: Any]
+ let isSandboxed = entitlements?["com.apple.security.app-sandbox"] as? Bool ?? false
+ let appGroups = Set(entitlements?["com.apple.security.application-groups"] as? [String] ?? [])
+
+ return SigningMetadata(
+ teamID: teamID,
+ authority: authority,
+ isAdHoc: isAdHoc,
+ isSandboxed: isSandboxed,
+ appGroups: appGroups
+ )
}
private func fileExists(at path: URL) -> Bool {
diff --git a/MacOSCleaner/Features/Uninstaller/Caches/CodesignCache.swift b/MacOSCleaner/Features/Uninstaller/Caches/CodesignCache.swift
index 42021dd..00e2dd6 100644
--- a/MacOSCleaner/Features/Uninstaller/Caches/CodesignCache.swift
+++ b/MacOSCleaner/Features/Uninstaller/Caches/CodesignCache.swift
@@ -1,27 +1,90 @@
import Foundation
+import Security
public actor CodesignCache {
- private var cache: [String: String] = [:]
+ public struct SigningInfo: Sendable {
+ public let teamID: String?
+ public let authorities: [String]
+
+ public static let unsigned = SigningInfo(teamID: nil, authorities: [])
+ }
+
+ private static let signableExtensions: Set = [
+ "app", "bundle", "kext", "framework", "xpc", "plugin", "appex",
+ "driver", "component", "prefpane", "qlgenerator", "saver",
+ "mdimporter", "systemextension", "dylib", "so"
+ ]
+
+ private var cache: [String: SigningInfo] = [:]
+ private let maxEntries = 2048
public init() {}
- public func getTeamID(url: URL, commandRunner: any CommandRunning) async -> String? {
- let key = url.standardizedFileURL.path
- if let cached = cache[key] { return cached.isEmpty ? nil : cached }
+ public static func isSignableCandidate(url: URL) -> Bool {
+ let ext = url.pathExtension.lowercased()
+ if signableExtensions.contains(ext) {
+ return true
+ }
+ if ext.isEmpty {
+ var isDir: ObjCBool = false
+ guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) else {
+ return false
+ }
+ // Plain data directories without bundle extensions are never Mach-O/bundle code objects.
+ return !isDir.boolValue
+ }
+ return false
+ }
- let result = try? await commandRunner.run(command: "/usr/bin/codesign", arguments: ["-dv", "--verbose=4", key])
- guard let output = result?.stderr else {
- cache[key] = ""
- return nil
+ public func getSigningInfo(url: URL) -> SigningInfo {
+ let key = NormalizedPath.key(url)
+ if let cached = cache[key] {
+ return cached
+ }
+ guard Self.isSignableCandidate(url: url) else {
+ return .unsigned
}
- if let range = output.range(of: "TeamIdentifier=") {
- let start = range.upperBound
- let end = output[start...].firstIndex(where: { $0.isWhitespace || $0.isNewline }) ?? output.endIndex
- let teamID = String(output[start..= maxEntries {
+ cache.removeAll(keepingCapacity: true)
+ }
+ cache[key] = info
+ return info
+ }
+
+ public func getTeamID(url: URL, commandRunner: any CommandRunning) async -> String? {
+ getSigningInfo(url: url).teamID
+ }
+
+ private static func readSigningInfo(at url: URL) -> SigningInfo {
+ autoreleasepool {
+ var staticCode: SecStaticCode?
+ guard SecStaticCodeCreateWithPath(url as CFURL, SecCSFlags(), &staticCode) == errSecSuccess,
+ let code = staticCode else {
+ return .unsigned
+ }
+ var infoRef: CFDictionary?
+ let flags = SecCSFlags(rawValue: kSecCSSigningInformation)
+ guard SecCodeCopySigningInformation(code, flags, &infoRef) == errSecSuccess,
+ let info = infoRef as? [String: Any] else {
+ return .unsigned
+ }
+
+ let rawTeam = (info[kSecCodeInfoTeamIdentifier as String] as? String)?
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ let teamID = (rawTeam?.isEmpty == false) ? rawTeam : nil
+
+ var authorities: [String] = []
+ if let certs = info[kSecCodeInfoCertificates as String] as? [SecCertificate] {
+ authorities.reserveCapacity(certs.count)
+ for cert in certs {
+ if let summary = SecCertificateCopySubjectSummary(cert) as String?, !summary.isEmpty {
+ authorities.append(summary)
+ }
+ }
+ }
+
+ return SigningInfo(teamID: teamID, authorities: authorities)
}
- cache[key] = ""
- return nil
}
}
diff --git a/MacOSCleaner/Features/Uninstaller/Caches/LSRegisterCache.swift b/MacOSCleaner/Features/Uninstaller/Caches/LSRegisterCache.swift
index 038bdbe..f5e7c71 100644
--- a/MacOSCleaner/Features/Uninstaller/Caches/LSRegisterCache.swift
+++ b/MacOSCleaner/Features/Uninstaller/Caches/LSRegisterCache.swift
@@ -13,9 +13,15 @@ public actor LSRegisterCache {
let timestamp: Date
}
+ private struct IndexedPathEntry: Sendable {
+ let path: String
+ let lower: String
+ }
+
private var cache: [String: Entry] = [:]
private let ttl: TimeInterval = 86400
- private var dumpedPaths: [String]? = nil
+ private var dumpedEntries: [IndexedPathEntry]? = nil
+ private var inFlightDump: Task<[IndexedPathEntry], Never>? = nil
public init() {}
@@ -23,32 +29,42 @@ public actor LSRegisterCache {
let bundleIDLower = bundleID.lowercased()
guard !bundleIDLower.isEmpty, !bundleIDLower.hasPrefix("unknown.") else { return [] }
- if dumpedPaths == nil {
- let lsregister = "/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"
- guard FileManager.default.fileExists(atPath: lsregister),
- let result = try? await commandRunner.run(command: lsregister, arguments: ["-dump"]) else {
- dumpedPaths = []
- return []
- }
- var paths: [String] = []
- for line in result.stdout.components(separatedBy: .newlines) {
- let trimmed = line.trimmingCharacters(in: .whitespaces)
- guard trimmed.hasPrefix("path:") else { continue }
- let p = String(trimmed.dropFirst(5)).trimmingCharacters(in: .whitespaces)
- if !p.isEmpty {
- paths.append(p)
+ let entries: [IndexedPathEntry]
+ if let cached = dumpedEntries {
+ entries = cached
+ } else if let existingTask = inFlightDump {
+ entries = await existingTask.value
+ } else {
+ let task = Task<[IndexedPathEntry], Never> {
+ let lsregister = "/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"
+ guard FileManager.default.fileExists(atPath: lsregister),
+ let result = try? await commandRunner.run(command: lsregister, arguments: ["-dump"]) else {
+ return []
}
+ var parsed: [IndexedPathEntry] = []
+ autoreleasepool {
+ result.stdout.enumerateLines { line, _ in
+ let trimmed = line.trimmingCharacters(in: .whitespaces)
+ guard trimmed.hasPrefix("path:") else { return }
+ let p = String(trimmed.dropFirst(5)).trimmingCharacters(in: .whitespaces)
+ if !p.isEmpty {
+ parsed.append(IndexedPathEntry(path: p, lower: p.lowercased()))
+ }
+ }
+ }
+ Logger.lsCache.info("Cached \(parsed.count) path entries from lsregister -dump")
+ return parsed
}
- dumpedPaths = paths
- Logger.lsCache.info("Cached \(paths.count) path entries from lsregister -dump")
+ inFlightDump = task
+ let parsed = await task.value
+ dumpedEntries = parsed
+ inFlightDump = nil
+ entries = parsed
}
- guard let paths = dumpedPaths else { return [] }
var found = Set()
- for path in paths {
- if path.lowercased().contains(bundleIDLower) {
- found.insert(NormalizedPath.url(path))
- }
+ for entry in entries where entry.lower.contains(bundleIDLower) {
+ found.insert(NormalizedPath.url(entry.path))
}
return found
}
diff --git a/MacOSCleaner/Features/Uninstaller/Caches/PlistContentCache.swift b/MacOSCleaner/Features/Uninstaller/Caches/PlistContentCache.swift
index 152b39a..178c9e6 100644
--- a/MacOSCleaner/Features/Uninstaller/Caches/PlistContentCache.swift
+++ b/MacOSCleaner/Features/Uninstaller/Caches/PlistContentCache.swift
@@ -2,6 +2,7 @@ import Foundation
public actor PlistContentCache {
private var cache: [String: String] = [:]
+ private let maxEntries = 512
public init() {}
@@ -9,18 +10,22 @@ public actor PlistContentCache {
let key = url.standardizedFileURL.path
if let cached = cache[key] { return cached }
- do {
- let data = try Data(contentsOf: url)
- var format = PropertyListSerialization.PropertyListFormat.xml
- let plist = try PropertyListSerialization.propertyList(from: data, format: &format)
- let serialized = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
- if let str = String(data: serialized, encoding: .utf8) {
- cache[key] = str
- return str
+ let decoded: String? = autoreleasepool {
+ do {
+ let data = try Data(contentsOf: url)
+ var format = PropertyListSerialization.PropertyListFormat.xml
+ let plist = try PropertyListSerialization.propertyList(from: data, format: &format)
+ let serialized = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
+ return String(data: serialized, encoding: .utf8)
+ } catch {
+ return nil
}
- } catch {
- return nil
}
- return nil
+ guard let str = decoded else { return nil }
+ if cache.count >= maxEntries {
+ cache.removeAll(keepingCapacity: true)
+ }
+ cache[key] = str
+ return str
}
}
diff --git a/MacOSCleaner/Features/Uninstaller/CandidateCollector.swift b/MacOSCleaner/Features/Uninstaller/CandidateCollector.swift
index c186a6d..76626bb 100644
--- a/MacOSCleaner/Features/Uninstaller/CandidateCollector.swift
+++ b/MacOSCleaner/Features/Uninstaller/CandidateCollector.swift
@@ -22,6 +22,18 @@ public actor CandidateCollector {
private let tmpScanDirectory: URL
private let fileSystemContext: FileSystemContext
private let lsRegisterCache: LSRegisterCache
+ private let safetyManager: SafetyManager
+ private let scanIndex: ResidualScanIndex?
+
+ private static let maxMatchedSubdirVisits = 128
+ private static let heavyNestedSkipDirectoryNames: Set = [
+ "node_modules", ".git", "cache_data", "code cache", "gpucache",
+ "indexeddb", "blob_storage", "service worker", "local storage",
+ "session storage", "file system", "dawncache", "graphitedawncache",
+ "grshadercache", "shadercache", "crashpad", "dictionaries",
+ "webstorage", "partitions", "extensions", "extension state",
+ "deriveddata", "coresimulator", "virtualmachines", "vms"
+ ]
private static let homeResidualDenyList: Set = [
".ssh", ".gnupg", ".Trash", ".trash", ".CFUserTextEncoding",
@@ -37,13 +49,17 @@ public actor CandidateCollector {
receiptsDirectory: URL? = nil,
tmpScanDirectory: URL? = nil,
fileSystemContext: FileSystemContext = .production,
- lsRegisterCache: LSRegisterCache = .shared
+ lsRegisterCache: LSRegisterCache = .shared,
+ safetyManager: SafetyManager? = nil,
+ scanIndex: ResidualScanIndex? = nil
) {
self.fileManager = fileManager
self.commandRunner = commandRunner
self.homebrewCellarDirectories = homebrewCellarDirectories
self.fileSystemContext = fileSystemContext
self.lsRegisterCache = lsRegisterCache
+ self.safetyManager = safetyManager ?? SafetyManager(homeDirectory: fileSystemContext.homePath, fileSystemContext: fileSystemContext)
+ self.scanIndex = scanIndex
if let darwinCacheDirectory {
self.darwinUserDirectories = [darwinCacheDirectory.resolvingSymlinksInPath()]
} else {
@@ -66,13 +82,8 @@ public actor CandidateCollector {
await collectDetailed(identity: identity, mode: mode).candidates
}
- public func collectDetailed(identity: AppIdentity, mode: ScanMode = .balanced) async -> CandidateCollection {
- var candidates = Set()
- let home = fileSystemContext.homePath
- let maxDepth = mode == .safe ? 3 : 5
-
- // 1. Fixed popular paths
- let basePaths = [
+ public static func basePaths(home: String) -> [String] {
+ [
NormalizedPath.joinHome(home, "Library/Application Support"),
NormalizedPath.joinHome(home, "Library/Caches"),
NormalizedPath.joinHome(home, "Library/Containers"),
@@ -129,18 +140,33 @@ public actor CandidateCollector {
"/Library/Extensions",
"/Library/Services",
]
+ }
- for base in basePaths {
- let url = NormalizedPath.url(base, isDirectory: true)
- candidates.formUnion(await shallowScan(url, identity: identity, mode: mode))
- }
+ public func collectDetailed(identity: AppIdentity, mode: ScanMode = .balanced) async -> CandidateCollection {
+ var candidates = Set()
+ let home = fileSystemContext.homePath
+ let maxDepth = mode == .safe ? 3 : 5
- // XDG dirs — CLI/Electron app configs (heuristic — public fallback)
- for relative in [".config", ".cache", ".local/share"] {
- let xdgPath = NormalizedPath.joinHome(home, relative)
- if fileManager.fileExists(atPath: xdgPath) {
- let xdgURL = NormalizedPath.url(xdgPath, isDirectory: true)
- candidates.formUnion(await shallowScan(xdgURL, identity: identity, mode: mode))
+ // 1. Fixed popular paths + XDG dirs
+ if let scanIndex {
+ for entry in scanIndex.candidateBaseEntries(for: identity) {
+ if matchCandidate(entry.url, identity: identity, mode: mode) {
+ candidates.insert(entry.url)
+ }
+ }
+ } else {
+ for base in Self.basePaths(home: home) {
+ let url = NormalizedPath.url(base, isDirectory: true)
+ candidates.formUnion(await shallowScan(url, identity: identity, mode: mode))
+ }
+
+ // XDG dirs — CLI/Electron app configs (heuristic — public fallback)
+ for relative in [".config", ".cache", ".local/share"] {
+ let xdgPath = NormalizedPath.joinHome(home, relative)
+ if fileManager.fileExists(atPath: xdgPath) {
+ let xdgURL = NormalizedPath.url(xdgPath, isDirectory: true)
+ candidates.formUnion(await shallowScan(xdgURL, identity: identity, mode: mode))
+ }
}
}
@@ -148,27 +174,51 @@ public actor CandidateCollector {
candidates.formUnion(collectDarwinUserDirs(identity: identity))
// Installer receipt metadata on disk (.plist / .bom), in addition to pkgutil.
- candidates.formUnion(collectReceiptFiles(identity: identity))
+ let receiptFiles = collectReceiptFiles(identity: identity)
+ candidates.formUnion(receiptFiles)
// 2. Deep scan critical folders
- let deepFolders = [
- NormalizedPath.joinHome(home, "Library/Application Support"),
- NormalizedPath.joinHome(home, "Library/Caches"),
- NormalizedPath.joinHome(home, "Library/Containers"),
- NormalizedPath.joinHome(home, "Library/Group Containers"),
- NormalizedPath.joinHome(home, "Library/HTTPStorages"),
- NormalizedPath.joinHome(home, "Library/WebKit"),
- NormalizedPath.joinHome(home, "Library/Preferences"),
- NormalizedPath.joinHome(home, "Library/Application Scripts"),
- ]
- for dir in deepFolders {
- let url = NormalizedPath.url(dir, isDirectory: true)
- candidates.formUnion(await deepScan(url, identity: identity, depth: 0, maxDepth: maxDepth, mode: mode))
+ if let scanIndex {
+ let deepFolders = [
+ NormalizedPath.joinHome(home, "Library/Application Support"),
+ NormalizedPath.joinHome(home, "Library/Caches"),
+ NormalizedPath.joinHome(home, "Library/Preferences"),
+ ]
+ for dir in deepFolders {
+ let url = NormalizedPath.url(dir, isDirectory: true)
+ var visits = 0
+ candidates.formUnion(deepScanIndexed(
+ url,
+ identity: identity,
+ depth: 0,
+ maxDepth: maxDepth,
+ mode: mode,
+ scanIndex: scanIndex,
+ alreadyMatchedRoots: candidates,
+ matchedSubdirVisits: &visits
+ ))
+ }
+ } else {
+ let deepFolders = [
+ NormalizedPath.joinHome(home, "Library/Application Support"),
+ NormalizedPath.joinHome(home, "Library/Caches"),
+ NormalizedPath.joinHome(home, "Library/Containers"),
+ NormalizedPath.joinHome(home, "Library/Group Containers"),
+ NormalizedPath.joinHome(home, "Library/HTTPStorages"),
+ NormalizedPath.joinHome(home, "Library/WebKit"),
+ NormalizedPath.joinHome(home, "Library/Preferences"),
+ NormalizedPath.joinHome(home, "Library/Application Scripts"),
+ ]
+ for dir in deepFolders {
+ let url = NormalizedPath.url(dir, isDirectory: true)
+ var visits = 0
+ candidates.formUnion(await deepScan(url, identity: identity, depth: 0, maxDepth: maxDepth, mode: mode, matchedSubdirVisits: &visits))
+ }
}
// 3. Package-manager receipts. Homebrew can keep the same app bundle in
// several versioned formulae (python@3.12 and python@3.14).
- let receiptPaths = await collectPkgutilReceiptPaths(identity: identity)
+ let receiptPaths = await collectPkgutilReceiptPaths(identity: identity, receiptFiles: receiptFiles)
candidates.formUnion(receiptPaths)
// Homebrew sibling kegs: discover as candidates, never elevate to receiptPaths
@@ -201,7 +251,21 @@ public actor CandidateCollector {
if fileManager.fileExists(atPath: jbPath) {
let jbURL = NormalizedPath.url(jbPath, isDirectory: true)
candidates.formUnion(await shallowScan(jbURL, identity: identity, mode: mode))
- candidates.formUnion(await deepScan(jbURL, identity: identity, depth: 0, maxDepth: maxDepth, mode: mode))
+ var jbVisits = 0
+ if let scanIndex {
+ candidates.formUnion(deepScanIndexed(
+ jbURL,
+ identity: identity,
+ depth: 0,
+ maxDepth: maxDepth,
+ mode: mode,
+ scanIndex: scanIndex,
+ alreadyMatchedRoots: candidates,
+ matchedSubdirVisits: &jbVisits
+ ))
+ } else {
+ candidates.formUnion(await deepScan(jbURL, identity: identity, depth: 0, maxDepth: maxDepth, mode: mode, matchedSubdirVisits: &jbVisits))
+ }
}
}
@@ -305,13 +369,21 @@ public actor CandidateCollector {
}
candidates = NormalizedPath.urls(
- Set(candidates.filter { !Self.isForeignDeveloperTree($0, identity: identity) })
+ Set(candidates.filter {
+ !Self.isForeignDeveloperTree($0, identity: identity)
+ && !safetyManager.isProtectedBrowserTarget($0.path, uninstallingBundleID: identity.bundleID)
+ })
+ )
+ let safeCatalogPaths = NormalizedPath.urls(
+ Set(registry.catalogPaths.filter {
+ !safetyManager.isProtectedBrowserTarget($0.path, uninstallingBundleID: identity.bundleID)
+ })
)
return CandidateCollection(
candidates: candidates,
receiptPaths: NormalizedPath.urls(Set(receiptPaths)),
- catalogPaths: NormalizedPath.urls(registry.catalogPaths),
+ catalogPaths: safeCatalogPaths,
sharedPaths: NormalizedPath.urls(registry.sharedPaths),
informationalPaths: NormalizedPath.urls(registry.informationalPaths)
)
@@ -319,14 +391,16 @@ public actor CandidateCollector {
private func collectDarwinUserDirs(identity: AppIdentity) -> Set {
var found = Set()
+ if let scanIndex {
+ for entry in scanIndex.darwinEntries where matchesDarwinEntry(entry.name, identity: identity) {
+ found.insert(entry.url)
+ }
+ return NormalizedPath.urls(found)
+ }
for directory in darwinUserDirectories {
- guard let contents = try? fileManager.contentsOfDirectory(
- at: directory,
- includingPropertiesForKeys: nil,
- options: [.skipsHiddenFiles]
- ) else { continue }
- for item in contents where matchesDarwinEntry(item.lastPathComponent, identity: identity) {
- found.insert(NormalizedPath.canonicalize(item))
+ for entry in ResidualScanIndex.readDirectory(at: directory, options: [.skipsHiddenFiles], fileManager: fileManager)
+ where matchesDarwinEntry(entry.name, identity: identity) {
+ found.insert(entry.url)
}
}
return NormalizedPath.urls(found)
@@ -365,26 +439,27 @@ public actor CandidateCollector {
private func collectReceiptFiles(identity: AppIdentity) -> Set {
let bundleID = identity.bundleID.lowercased()
guard !bundleID.isEmpty, !bundleID.hasPrefix("unknown.") else { return [] }
- guard let contents = try? fileManager.contentsOfDirectory(
- at: receiptsDirectory,
- includingPropertiesForKeys: nil,
- options: [.skipsHiddenFiles]
- ) else { return [] }
+ let entries: [ResidualScanIndex.IndexedEntry]
+ if let scanIndex {
+ entries = scanIndex.receiptEntries
+ } else {
+ entries = ResidualScanIndex.readDirectory(at: receiptsDirectory, options: [.skipsHiddenFiles], fileManager: fileManager)
+ }
let sanitizedApp = identity.appName
.replacingOccurrences(of: " ", with: "_")
.lowercased()
var found = Set()
- for item in contents {
- let lower = item.lastPathComponent.lowercased()
+ for entry in entries {
+ let lower = entry.lowerName
let stem = (lower as NSString).deletingPathExtension
guard lower.hasSuffix(".plist") || lower.hasSuffix(".bom") else { continue }
if stem == bundleID || stem.hasPrefix(bundleID + ".") || lower.contains(bundleID) {
- found.insert(NormalizedPath.canonicalize(item))
+ found.insert(entry.url)
continue
}
if sanitizedApp.count >= 2, stem == sanitizedApp || stem.hasPrefix(sanitizedApp + ".") || stem.hasPrefix(sanitizedApp + "_") || stem.hasPrefix(sanitizedApp + "-") {
- found.insert(NormalizedPath.canonicalize(item))
+ found.insert(entry.url)
}
}
return NormalizedPath.urls(found)
@@ -392,18 +467,19 @@ public actor CandidateCollector {
/// Shallow home entries (dotdirs / top-level app folders). No curated private path list.
private func collectHomeResiduals(identity: AppIdentity, home: String) -> Set {
- let homeURL = NormalizedPath.url(home, isDirectory: true)
- guard let contents = try? fileManager.contentsOfDirectory(
- at: homeURL,
- includingPropertiesForKeys: nil,
- options: []
- ) else { return [] }
+ let entries: [ResidualScanIndex.IndexedEntry]
+ if let scanIndex {
+ entries = scanIndex.homeEntries
+ } else {
+ let homeURL = NormalizedPath.url(home, isDirectory: true)
+ entries = ResidualScanIndex.readDirectory(at: homeURL, options: [], fileManager: fileManager)
+ }
var found = Set()
- for item in contents {
- let name = item.lastPathComponent
+ for entry in entries {
+ let name = entry.name
if Self.homeResidualDenyList.contains(name) { continue }
- let lower = name.lowercased()
+ let lower = entry.lowerName
let bare = lower.hasPrefix(".") ? String(lower.dropFirst()) : lower
guard bare.count >= 3 else { continue }
@@ -423,7 +499,7 @@ public actor CandidateCollector {
}
}
if matched {
- found.insert(NormalizedPath.canonicalize(item))
+ found.insert(entry.url)
}
}
return NormalizedPath.urls(found)
@@ -446,32 +522,32 @@ public actor CandidateCollector {
) async -> Set {
guard depth <= maxDepth else { return [] }
var found = Set()
- guard let contents = try? fileManager.contentsOfDirectory(
- at: url,
- includingPropertiesForKeys: [.isDirectoryKey],
- options: [.skipsHiddenFiles]
- ) else { return found }
+ let entries: [ResidualScanIndex.IndexedEntry]
+ if let scanIndex {
+ entries = (depth == 0)
+ ? scanIndex.tmpTopLevelEntries
+ : scanIndex.entries(inDirectory: url, options: [.skipsHiddenFiles], fileManager: fileManager)
+ } else {
+ entries = ResidualScanIndex.readDirectory(at: url, options: [.skipsHiddenFiles], fileManager: fileManager)
+ }
- for item in contents {
- let lower = item.lastPathComponent.lowercased()
+ for entry in entries {
+ let lower = entry.lowerName
if lower == targetApp {
- found.insert(NormalizedPath.canonicalize(item))
- continue
- }
- var isDir: ObjCBool = false
- guard fileManager.fileExists(atPath: item.path, isDirectory: &isDir), isDir.boolValue else {
+ found.insert(entry.url)
continue
}
+ guard entry.isDirectory else { continue }
if appName.count >= 2, EvidenceProbe.wordBoundaryMatch(lower, appName) {
// Descend into name-matching project folders (e.g. MacOSCleaner-Polish/…).
found.formUnion(
- await scanTmpDir(item, targetApp: targetApp, appName: appName, depth: depth + 1, maxDepth: maxDepth)
+ await scanTmpDir(entry.url, targetApp: targetApp, appName: appName, depth: depth + 1, maxDepth: maxDepth)
)
} else if depth < maxDepth {
// Shallow walk only a couple levels for Build/Products/Debug layouts.
if lower == "build" || lower == "products" || lower == "debug" || lower == "release" {
found.formUnion(
- await scanTmpDir(item, targetApp: targetApp, appName: appName, depth: depth + 1, maxDepth: maxDepth)
+ await scanTmpDir(entry.url, targetApp: targetApp, appName: appName, depth: depth + 1, maxDepth: maxDepth)
)
}
}
@@ -548,10 +624,23 @@ public actor CandidateCollector {
/// Sibling `.app` bundles in configured Homebrew Cellar directories that share
/// the same bundle name. Returned as candidates only — never receiptPaths.
private func collectHomebrewSiblingApps(identity: AppIdentity) -> Set {
- guard !homebrewCellarDirectories.isEmpty else { return [] }
let targetName = identity.bundleURL.lastPathComponent.lowercased()
guard targetName.hasSuffix(".app") else { return [] }
+ let targetBundleID = identity.bundleID.lowercased()
+
+ if let scanIndex {
+ guard let entries = scanIndex.homebrewAppsByLowerName[targetName] else { return [] }
+ var found = Set()
+ for entry in entries {
+ if let bid = entry.bundleIDLower, !bid.isEmpty, bid != targetBundleID {
+ continue
+ }
+ found.insert(entry.url)
+ }
+ return found
+ }
+ guard !homebrewCellarDirectories.isEmpty else { return [] }
var found = Set()
for cellar in homebrewCellarDirectories {
guard let formulae = try? fileManager.contentsOfDirectory(
@@ -575,7 +664,7 @@ public actor CandidateCollector {
let resolved = app.resolvingSymlinksInPath()
if let bundleID = Bundle(url: resolved)?.bundleIdentifier?.lowercased(),
!bundleID.isEmpty,
- bundleID != identity.bundleID.lowercased() {
+ bundleID != targetBundleID {
continue
}
found.insert(resolved)
@@ -588,22 +677,41 @@ public actor CandidateCollector {
/// Files recorded in installer receipts for packages whose id matches the bundle ID.
/// Paths inside the app bundle are skipped — the bundle is removed as a whole anyway.
- private func collectPkgutilReceiptPaths(identity: AppIdentity) async -> Set {
+ private func collectPkgutilReceiptPaths(identity: AppIdentity, receiptFiles: Set? = nil) async -> Set {
let bundleID = identity.bundleID.lowercased()
guard !bundleID.isEmpty, !bundleID.hasPrefix("unknown.") else { return [] }
- let receiptFiles = collectReceiptFiles(identity: identity)
- let receiptStems = Set(receiptFiles.map { ($0.deletingPathExtension().lastPathComponent).lowercased() })
-
- var packageIDs: Set = [identity.bundleID]
- if let result = try? await commandRunner.run(command: "/usr/sbin/pkgutil", arguments: ["--pkgs"]) {
- for line in result.stdout.components(separatedBy: .newlines) where !line.isEmpty {
- let lowerLine = line.lowercased()
- if lowerLine == bundleID {
- packageIDs.insert(line)
- } else if lowerLine.hasPrefix(bundleID + ".") {
- if receiptStems.isEmpty || receiptStems.contains(lowerLine) || receiptStems.contains(where: { lowerLine.hasPrefix($0) }) {
+ let resolvedReceipts = receiptFiles ?? collectReceiptFiles(identity: identity)
+ let receiptStems = Set(resolvedReceipts.map { ($0.deletingPathExtension().lastPathComponent).lowercased() })
+
+ var packageIDs: Set = []
+ if let scanIndex {
+ if let packages = scanIndex.pkgutilPackages {
+ for line in packages {
+ let lowerLine = line.lowercased()
+ if lowerLine == bundleID {
packageIDs.insert(line)
+ } else if lowerLine.hasPrefix(bundleID + ".") {
+ if receiptStems.isEmpty || receiptStems.contains(lowerLine) || receiptStems.contains(where: { lowerLine.hasPrefix($0) }) {
+ packageIDs.insert(line)
+ }
+ }
+ }
+ } else {
+ // Fallback when pkgutil --pkgs returned empty (e.g. mock test runners)
+ packageIDs.insert(identity.bundleID)
+ }
+ } else {
+ packageIDs.insert(identity.bundleID)
+ if let result = try? await commandRunner.run(command: "/usr/sbin/pkgutil", arguments: ["--pkgs"]) {
+ for line in result.stdout.components(separatedBy: .newlines) where !line.isEmpty {
+ let lowerLine = line.lowercased()
+ if lowerLine == bundleID {
+ packageIDs.insert(line)
+ } else if lowerLine.hasPrefix(bundleID + ".") {
+ if receiptStems.isEmpty || receiptStems.contains(lowerLine) || receiptStems.contains(where: { lowerLine.hasPrefix($0) }) {
+ packageIDs.insert(line)
+ }
}
}
}
@@ -612,9 +720,16 @@ public actor CandidateCollector {
var found = Set()
let bundlePrefix = identity.bundleURL.standardizedFileURL.path + "/"
for packageID in packageIDs {
- guard let result = try? await commandRunner.run(command: "/usr/sbin/pkgutil", arguments: ["--files", packageID]),
- result.exitCode == 0 else { continue }
- for line in result.stdout.components(separatedBy: .newlines) where !line.isEmpty {
+ let lines: [String]
+ if let scanIndex {
+ lines = await scanIndex.pkgutilFiles(for: packageID, commandRunner: commandRunner)
+ } else if let result = try? await commandRunner.run(command: "/usr/sbin/pkgutil", arguments: ["--files", packageID]),
+ result.exitCode == 0 {
+ lines = result.stdout.components(separatedBy: .newlines).filter { !$0.isEmpty }
+ } else {
+ continue
+ }
+ for line in lines where !line.isEmpty {
let path = NormalizedPath.join("/", line)
guard !path.hasPrefix(bundlePrefix), fileManager.fileExists(atPath: path) else { continue }
found.insert(NormalizedPath.url(path))
@@ -625,13 +740,83 @@ public actor CandidateCollector {
private func shallowScan(_ url: URL, identity: AppIdentity, mode: ScanMode = .balanced) async -> Set {
var found = Set()
- guard let contents = try? fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: nil) else {
- return found
+ let entries = scanIndex?.entries(inDirectory: url, fileManager: fileManager)
+ ?? ResidualScanIndex.readDirectory(at: url, fileManager: fileManager)
+ for entry in entries {
+ if matchCandidate(entry.url, identity: identity, mode: mode) {
+ found.insert(entry.url)
+ }
}
- for item in contents {
- if matchCandidate(item, identity: identity, mode: mode) {
- found.insert(NormalizedPath.canonicalize(item))
+ return found
+ }
+
+ private func deepScanIndexed(
+ _ url: URL,
+ identity: AppIdentity,
+ depth: Int,
+ maxDepth: Int,
+ mode: ScanMode,
+ scanIndex: ResidualScanIndex,
+ alreadyMatchedRoots: Set,
+ matchedSubdirVisits: inout Int,
+ insideMatch: Bool = false
+ ) -> Set {
+ guard depth <= maxDepth else { return [] }
+ var found = Set()
+ let entries = scanIndex.entries(inDirectory: url, fileManager: fileManager)
+
+ for entry in entries {
+ if depth == 0 {
+ guard entry.isDirectory else { continue }
+ let matched = alreadyMatchedRoots.contains(entry.url)
+ let descend = matched || Self.shouldDescendForResidualScan(entry.url, identity: identity)
+ guard descend else { continue }
+ if matched {
+ guard matchedSubdirVisits < Self.maxMatchedSubdirVisits else { continue }
+ matchedSubdirVisits += 1
+ }
+ found.formUnion(deepScanIndexed(
+ entry.url,
+ identity: identity,
+ depth: depth + 1,
+ maxDepth: maxDepth,
+ mode: mode,
+ scanIndex: scanIndex,
+ alreadyMatchedRoots: alreadyMatchedRoots,
+ matchedSubdirVisits: &matchedSubdirVisits,
+ insideMatch: matched
+ ))
+ continue
+ }
+
+ if insideMatch, Self.heavyNestedSkipDirectoryNames.contains(entry.lowerName) {
+ continue
+ }
+
+ let matched = matchCandidate(entry.url, identity: identity, mode: mode)
+ if matched {
+ found.insert(entry.url)
+ }
+ guard entry.isDirectory else { continue }
+
+ let nextInside = matched || insideMatch
+ let descend = nextInside || Self.shouldDescendForResidualScan(entry.url, identity: identity)
+ guard descend else { continue }
+ if nextInside {
+ guard matchedSubdirVisits < Self.maxMatchedSubdirVisits else { continue }
+ matchedSubdirVisits += 1
}
+ found.formUnion(deepScanIndexed(
+ entry.url,
+ identity: identity,
+ depth: depth + 1,
+ maxDepth: maxDepth,
+ mode: mode,
+ scanIndex: scanIndex,
+ alreadyMatchedRoots: alreadyMatchedRoots,
+ matchedSubdirVisits: &matchedSubdirVisits,
+ insideMatch: nextInside
+ ))
}
return found
}
@@ -642,33 +827,40 @@ public actor CandidateCollector {
depth: Int,
maxDepth: Int,
mode: ScanMode,
+ matchedSubdirVisits: inout Int,
insideMatch: Bool = false
) async -> Set {
guard depth <= maxDepth else { return [] }
var found = Set()
- guard let contents = try? fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: nil) else {
- return found
- }
- for item in contents {
- let matched = matchCandidate(item, identity: identity, mode: mode)
+ let entries = scanIndex?.entries(inDirectory: url, fileManager: fileManager)
+ ?? ResidualScanIndex.readDirectory(at: url, fileManager: fileManager)
+ for entry in entries {
+ if insideMatch, Self.heavyNestedSkipDirectoryNames.contains(entry.lowerName) {
+ continue
+ }
+ let matched = matchCandidate(entry.url, identity: identity, mode: mode)
if matched {
- found.insert(NormalizedPath.canonicalize(item))
+ found.insert(entry.url)
}
- var isDir: ObjCBool = false
- if fileManager.fileExists(atPath: item.path, isDirectory: &isDir), isDir.boolValue {
+ if entry.isDirectory {
// Walk matched trees fully; for unmatched siblings only descend vendor hubs
// (Google/) so we don't traverse Chrome profiles while scanning Studio.
- let descend = matched
- || insideMatch
- || Self.shouldDescendForResidualScan(item, identity: identity)
+ let nextInside = matched || insideMatch
+ let descend = nextInside
+ || Self.shouldDescendForResidualScan(entry.url, identity: identity)
guard descend else { continue }
+ if nextInside {
+ guard matchedSubdirVisits < Self.maxMatchedSubdirVisits else { continue }
+ matchedSubdirVisits += 1
+ }
let sub = await deepScan(
- item,
+ entry.url,
identity: identity,
depth: depth + 1,
maxDepth: maxDepth,
mode: mode,
- insideMatch: matched || insideMatch
+ matchedSubdirVisits: &matchedSubdirVisits,
+ insideMatch: nextInside
)
found.formUnion(sub)
}
@@ -691,6 +883,9 @@ public actor CandidateCollector {
if Self.isForeignAppLibraryTree(url, identity: identity) {
return false
}
+ if safetyManager.isProtectedBrowserTarget(url.path, uninstallingBundleID: identity.bundleID) {
+ return false
+ }
let name = url.lastPathComponent
let lowerName = name.lowercased()
let lowerBundleID = identity.bundleID.lowercased()
@@ -883,8 +1078,11 @@ public actor CandidateCollector {
guard looksLikeBundle else { continue }
// System holders that store per-app children by our bundle ID / name.
if foreign.hasPrefix("com.apple.") { continue }
+ if BrowserRule.isKnownBrowserBundleID(foreign), foreign != bid {
+ return true
+ }
if foreign == bid || foreign.hasPrefix(bid + ".") { continue }
- if bid.hasPrefix(foreign + ".") { continue }
+ if bid.hasPrefix(foreign + "."), !BrowserRule.isBrowserPWAShimBundleID(bid) { continue }
return true
}
return false
@@ -892,39 +1090,10 @@ public actor CandidateCollector {
// MARK: - Browser vendor paths
- /// Google Chrome lives under ~/Library/.../Google/Chrome, not a top-level "Google Chrome" folder.
+ /// Collect browser vendor roots owned strictly by the exact browser bundle ID (never PWAs or sibling channels).
private func collectBrowserVendorPaths(identity: AppIdentity, home: String, maxDepth: Int) async -> Set {
- let bid = identity.bundleID.lowercased()
- let app = identity.appName.lowercased()
- var vendorRoots: [(vendor: String, product: String?)] = []
-
- if bid.contains("google") && (bid.contains("chrome") || app.contains("chrome")) {
- vendorRoots.append(("Google", "Chrome"))
- } else if bid.contains("mozilla") || app.contains("firefox") {
- vendorRoots.append(("Mozilla", nil))
- vendorRoots.append(("Firefox", nil))
- } else if bid.contains("microsoft.edgemac") || app.contains("edge") {
- vendorRoots.append(("Microsoft Edge", nil))
- } else if bid.contains("brave") || app.contains("brave") {
- vendorRoots.append(("BraveSoftware", nil))
- vendorRoots.append(("BraveSoftware", "Brave-Browser"))
- } else if bid.contains("operasoftware") || app.contains("opera") {
- vendorRoots.append(("com.operasoftware.Opera", nil))
- vendorRoots.append(("Opera Software", nil))
- vendorRoots.append(("Opera", nil))
- } else if bid.contains("vivaldi") || app.contains("vivaldi") {
- vendorRoots.append(("Vivaldi", nil))
- } else if bid.contains("thebrowser") || app == "arc" {
- vendorRoots.append(("Arc", nil))
- } else if bid.contains("chromium") || app.contains("chromium") {
- vendorRoots.append(("Chromium", nil))
- } else if bid.contains("torproject") || app.contains("tor") {
- vendorRoots.append(("TorBrowser-Data", nil))
- } else if bid.contains("duckduckgo") {
- vendorRoots.append(("DuckDuckGo", nil))
- } else if bid.contains("yandex") {
- vendorRoots.append(("Yandex", nil))
- }
+ let vendorRoots = BrowserRule.vendorRoots(forBundleID: identity.bundleID)
+ guard !vendorRoots.isEmpty else { return [] }
var found = Set()
let nestedBases = [
@@ -936,25 +1105,29 @@ public actor CandidateCollector {
for base in nestedBases {
let vendorURL = NormalizedPath.url(base, isDirectory: true).appendingPathComponent(vendor)
guard fileManager.fileExists(atPath: vendorURL.path) else { continue }
+ var visits = 0
if let product {
let productURL = vendorURL.appendingPathComponent(product)
if fileManager.fileExists(atPath: productURL.path) {
found.insert(NormalizedPath.canonicalize(productURL))
- found.formUnion(await deepScan(productURL, identity: identity, depth: 0, maxDepth: maxDepth, mode: .balanced))
+ found.formUnion(await deepScan(productURL, identity: identity, depth: 0, maxDepth: maxDepth, mode: .balanced, matchedSubdirVisits: &visits))
}
} else {
found.insert(NormalizedPath.canonicalize(vendorURL))
- found.formUnion(await deepScan(vendorURL, identity: identity, depth: 0, maxDepth: maxDepth, mode: .balanced))
+ found.formUnion(await deepScan(vendorURL, identity: identity, depth: 0, maxDepth: maxDepth, mode: .balanced, matchedSubdirVisits: &visits))
}
}
- // ~/Library/{Vendor} — e.g. GoogleSoftwareUpdate / Keystone beside Application Support.
- let libraryVendor = NormalizedPath.url(NormalizedPath.joinHome(home, "Library"), isDirectory: true)
- .appendingPathComponent(vendor)
- if fileManager.fileExists(atPath: libraryVendor.path) {
- found.insert(NormalizedPath.canonicalize(libraryVendor))
- found.formUnion(
- await deepScan(libraryVendor, identity: identity, depth: 0, maxDepth: min(maxDepth, 3), mode: .balanced)
- )
+ // ~/Library/{Vendor} — only for single-vendor roots, never mega-vendors like Google.
+ if product == nil {
+ let libraryVendor = NormalizedPath.url(NormalizedPath.joinHome(home, "Library"), isDirectory: true)
+ .appendingPathComponent(vendor)
+ if fileManager.fileExists(atPath: libraryVendor.path) {
+ var visits = 0
+ found.insert(NormalizedPath.canonicalize(libraryVendor))
+ found.formUnion(
+ await deepScan(libraryVendor, identity: identity, depth: 0, maxDepth: min(maxDepth, 3), mode: .balanced, matchedSubdirVisits: &visits)
+ )
+ }
}
}
return found
@@ -1029,6 +1202,10 @@ public actor CandidateCollector {
/// Attribute-scoped Spotlight lookup. Raw text queries are forbidden here: they run a
/// full-content search and match user documents/mail that merely mention the app name.
private func runMdfind(identity: AppIdentity) async -> Set {
+ guard SpotlightMetadata.isIndexingAvailable(at: fileSystemContext.homePath) else {
+ return []
+ }
+
var queries: [(query: String, onlyIn: String?)] = []
if !identity.bundleID.isEmpty, !identity.bundleID.hasPrefix("unknown.") {
diff --git a/MacOSCleaner/Features/Uninstaller/EvidenceProbe.swift b/MacOSCleaner/Features/Uninstaller/EvidenceProbe.swift
index e55b90a..df3b645 100644
--- a/MacOSCleaner/Features/Uninstaller/EvidenceProbe.swift
+++ b/MacOSCleaner/Features/Uninstaller/EvidenceProbe.swift
@@ -41,7 +41,12 @@ public actor EvidenceProbe {
if lowerFileName == lowerBundleID || strippedFileName == lowerBundleID {
evidence.insert(.bundleIDExact)
- } else if lowerFileName.hasPrefix(lowerBundleID + ".") || strippedFileName.hasPrefix(lowerBundleID + ".") || (strippedFileName.contains(".") && lowerBundleID.hasPrefix(strippedFileName)) {
+ } else if lowerFileName.hasPrefix(lowerBundleID + ".") || strippedFileName.hasPrefix(lowerBundleID + ".") {
+ evidence.insert(.bundleIDPrefix)
+ } else if strippedFileName.contains("."),
+ lowerBundleID.hasPrefix(strippedFileName + "."),
+ !BrowserRule.isBrowserPWAShimBundleID(lowerBundleID),
+ !(BrowserRule.isKnownBrowserBundleID(strippedFileName) && strippedFileName != lowerBundleID) {
evidence.insert(.bundleIDPrefix)
}
if url.pathExtension.lowercased() == "app",
@@ -186,18 +191,17 @@ public actor EvidenceProbe {
evidence.insert(.flutterBuild)
}
- // Code signature probe
+ // Code signature probe (in-process Security framework; never spawns codesign subprocesses)
let binaryExts: Set = ["", "app", "bundle", "kext", "framework", "dylib", "xpc"]
- let fileExt = url.pathExtension
+ let fileExt = url.pathExtension.lowercased()
if binaryExts.contains(fileExt) || fileExt.isEmpty {
- if let candidateTeamID = await codesignCache.getTeamID(url: url, commandRunner: commandRunner) {
- if candidateTeamID == identity.teamID && identity.teamID != nil {
+ if CodesignCache.isSignableCandidate(url: url) {
+ let signing = await codesignCache.getSigningInfo(url: url)
+ if let candidateTeamID = signing.teamID, candidateTeamID == identity.teamID, identity.teamID != nil {
evidence.insert(.teamID)
}
- }
- if let auth = identity.signingAuthority {
- let result = try? await commandRunner.run(command: "/usr/bin/codesign", arguments: ["-dv", "--verbose=4", url.path])
- if let output = result?.stderr, output.contains(auth) {
+ if let auth = identity.signingAuthority,
+ signing.authorities.contains(where: { $0.contains(auth) }) {
evidence.insert(.developerSignature)
}
}
@@ -246,15 +250,50 @@ public actor EvidenceProbe {
/// Needle starts a token in haystack: "arc" matches "arc helper"/"arcupdater", not "searchmarquis".
static func tokenPrefixMatch(_ haystack: String, _ needle: String) -> Bool {
guard !needle.isEmpty else { return false }
- let pattern = "(? Bool {
guard !needle.isEmpty else { return false }
- let pattern = "(? String {
+ switch category {
+ case "Caches": return "uninstaller_orphan_cat_caches".localized
+ case "Preferences": return "uninstaller_orphan_cat_preferences".localized
+ case "Application Support": return "uninstaller_orphan_cat_app_support".localized
+ case "Logs": return "uninstaller_orphan_cat_logs".localized
+ case "Containers": return "uninstaller_orphan_cat_containers".localized
+ case "Developer": return "uninstaller_orphan_cat_developer".localized
+ case "Launch Agents", "LaunchAgents": return "uninstaller_orphan_cat_launch_agents".localized
+ case "Other": return "uninstaller_orphan_cat_other".localized
+ default: return category
+ }
+ }
+
+ public var localizedCategory: String {
+ Self.localizedCategoryName(for: category)
+ }
+
public func hash(into hasher: inout Hasher) {
hasher.combine(NormalizedPath.key(url))
}
@@ -57,9 +75,11 @@ public actor OrphanScanner {
private let safetyManager: SafetyManager
private let commandRunner: CommandRunner
private let fileSystemContext: FileSystemContext
+ private let appDiscovery: AppDiscovery
private let codesignCache: CodesignCache
private let plistCache: PlistContentCache
private let ruleRegistry: ApplicationRuleRegistry
+ private let homebrewCellarDirectories: [URL]
private let fileManager = FileManager.default
public init(
@@ -68,36 +88,45 @@ public actor OrphanScanner {
fileSystemContext: FileSystemContext = .production,
codesignCache: CodesignCache = CodesignCache(),
plistCache: PlistContentCache = PlistContentCache(),
- ruleRegistry: ApplicationRuleRegistry = .shared
+ ruleRegistry: ApplicationRuleRegistry = .shared,
+ appDiscovery: AppDiscovery? = nil,
+ homebrewCellarDirectories: [URL] = AppDiscovery.defaultHomebrewCellarDirectories
) {
self.safetyManager = safetyManager
self.commandRunner = commandRunner
self.fileSystemContext = fileSystemContext
+ self.appDiscovery = appDiscovery ?? AppDiscovery(
+ commandRunner: commandRunner,
+ homebrewCellarDirectories: homebrewCellarDirectories
+ )
self.codesignCache = codesignCache
self.plistCache = plistCache
self.ruleRegistry = ruleRegistry
+ self.homebrewCellarDirectories = homebrewCellarDirectories
}
public func scanOrphans(progress: (@Sendable (String) -> Void)? = nil) async throws -> [OrphanItem] {
try Task.checkCancellation()
- progress?("Discovering installed applications...")
+ progress?("uninstaller.progress.discovering".localized)
- // 1. Discover installed apps
- let discovery = AppDiscovery()
- let installedURLs = await discovery.findAll()
- var identities: [AppIdentity] = []
- for url in installedURLs {
- let identity = await AppIdentity.resolve(from: url, commandRunner: commandRunner)
- identities.append(identity)
- }
+ // 1. Discover installed apps & Homebrew formulae
+ let installedURLs = await appDiscovery.findAll()
+ let runner = commandRunner
+ let identities = (try? await UninstallerService.mapWithBoundedConcurrency(
+ items: installedURLs,
+ maxConcurrent: UninstallerService.maxConcurrentDiscoveryTasks
+ ) { url in
+ await AppIdentity.resolve(from: url, commandRunner: runner)
+ }) ?? []
+ let installedHomebrewFormulae = collectInstalledHomebrewFormulae()
try Task.checkCancellation()
- progress?("Scanning target directories...")
+ progress?("uninstaller_orphan_scanning_dirs".localized)
// 2. Collect ALL files from scan directories
let allFiles = await collectAllScanTargets()
- progress?("Analyzing \(allFiles.count) potential orphans...")
+ progress?(String(format: "uninstaller_orphan_analyzing_count".localized, Int64(allFiles.count)))
let probe = EvidenceProbe(
commandRunner: commandRunner,
codesignCache: codesignCache,
@@ -107,26 +136,29 @@ public actor OrphanScanner {
var orphans: [OrphanItem] = []
var processed = 0
let total = allFiles.count
+ var commandExistsCache: [String: Bool] = [:]
for file in allFiles {
try Task.checkCancellation()
processed += 1
if processed % 100 == 0 {
- progress?("Analyzing \(processed)/\(total)...")
+ progress?(String(format: "uninstaller_orphan_analyzing_progress".localized, Int64(processed), Int64(total)))
}
// Basic safety & size filters
guard (try? safetyManager.validate(url: file, policy: .uninstall)) != nil else { continue }
// Skip Apple system items, system daemons, and developer toolchain containers
- if isSystemOrProtected(file: file) {
+ if Self.isSystemOrProtected(file: file) {
continue
}
let isOwned = await checkOwnership(
file: file,
identities: identities,
- probe: probe
+ probe: probe,
+ installedHomebrewFormulae: installedHomebrewFormulae,
+ commandExistsCache: &commandExistsCache
)
if !isOwned {
@@ -148,9 +180,10 @@ public actor OrphanScanner {
else if pathStr.contains("/Application Support/") { category = "Application Support" }
else if pathStr.contains("/Logs/") { category = "Logs" }
else if pathStr.contains("/Containers/") || pathStr.contains("/Group Containers/") { category = "Containers" }
+ else if pathStr.contains("/LaunchAgents/") || pathStr.contains("/LaunchDaemons/") { category = "Launch Agents" }
else if pathStr.contains("/Developer/") || pathStr.contains("CommandLineTools") { category = "Developer" }
- let extracted = extractBundleIDAndName(from: file)
+ let extracted = Self.extractBundleIDAndName(from: file)
// Generic folders without any bundle ID or specific orphan markers are not orphans
if extracted.bundleID == nil {
@@ -192,34 +225,50 @@ public actor OrphanScanner {
return orphans.sorted { $0.sizeBytes > $1.sizeBytes }
}
- private func isSystemOrProtected(file: URL) -> Bool {
+ static func isSystemOrProtected(file: URL) -> Bool {
let rawFilename = file.lastPathComponent.lowercased()
- let filename = stripTeamIDPrefix(from: rawFilename)
+ let filename = Self.stripTeamIDPrefix(from: rawFilename)
.replacingOccurrences(of: "group.", with: "")
.replacingOccurrences(of: "groups.", with: "")
+ let protectedPrefixes = [
+ "com.apple.",
+ "com.mac.",
+ "is.workflow.",
+ "org.swift.",
+ "org.llvm.",
+ "org.gnu.",
+ "org.cups.",
+ "org.sparkle-project.",
+ "org.openldap.",
+ "org.apache.",
+ "tvappservices.",
+ "com.crashlytics.",
+ "io.fabric."
+ ]
+
+ // Shared telemetry/crash SDKs and updaters have no standalone .app bundle.
+ let protectedSharedSDKs = [
+ "io.sentry",
+ "com.plausiblelabs.crashreporter",
+ "com.google.keystone",
+ "sentrycrash"
+ ]
+
// Apple system containers, groups, daemons and system tools
if rawFilename.contains("com.apple.") ||
rawFilename.contains(".apple.") ||
rawFilename.contains("group.com.apple") ||
rawFilename.contains("groups.com.apple") ||
- filename.hasPrefix("com.apple.") ||
- filename.hasPrefix("com.mac.") ||
- filename.hasPrefix("is.workflow.") ||
- filename.hasPrefix("org.swift.") ||
- filename.hasPrefix("org.llvm.") ||
- filename.hasPrefix("org.gnu.") ||
- filename.hasPrefix("org.cups.") ||
- filename.hasPrefix("org.sparkle-project.") ||
- filename.hasPrefix("org.openldap.") ||
- filename.hasPrefix("org.apache.") {
+ protectedPrefixes.contains(where: { filename.hasPrefix($0) }) ||
+ protectedSharedSDKs.contains(where: { filename == $0 || filename.hasPrefix("\($0).") }) {
return true
}
return false
}
- private func stripTeamIDPrefix(from string: String) -> String {
+ private static func stripTeamIDPrefix(from string: String) -> String {
let pattern = #"^[A-Z0-9]{10}\.(?:groups?\.)?"#
if let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) {
let range = NSRange(location: 0, length: string.utf16.count)
@@ -227,19 +276,121 @@ public actor OrphanScanner {
}
return string
}
+
+ private func collectInstalledHomebrewFormulae() -> Set {
+ var formulae = Set()
+ var dirsToScan: [URL] = []
+ for cellar in homebrewCellarDirectories {
+ dirsToScan.append(cellar)
+ let optSibling = cellar.deletingLastPathComponent().appendingPathComponent("opt", isDirectory: true)
+ dirsToScan.append(optSibling)
+ }
+ for dir in dirsToScan {
+ guard let contents = try? fileManager.contentsOfDirectory(
+ at: dir,
+ includingPropertiesForKeys: nil,
+ options: [.skipsHiddenFiles]
+ ) else { continue }
+ for entry in contents {
+ let name = entry.lastPathComponent.lowercased()
+ if !name.isEmpty {
+ formulae.insert(name)
+ }
+ }
+ }
+ return formulae
+ }
+
+ static func extractLaunchdExecutablePaths(from plistURL: URL) -> [String] {
+ autoreleasepool {
+ guard let data = try? Data(contentsOf: plistURL),
+ let dict = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] else {
+ return []
+ }
+ var candidates: [String] = []
+ if let program = dict["Program"] as? String, !program.isEmpty {
+ candidates.append(program)
+ }
+ if let args = dict["ProgramArguments"] as? [String], let first = args.first, !first.isEmpty {
+ let wrappers: Set = [
+ "/bin/sh", "/bin/bash", "/bin/zsh", "/usr/bin/env",
+ "/usr/bin/java", "/opt/homebrew/bin/brew", "/usr/local/bin/brew"
+ ]
+ if !wrappers.contains(first) {
+ candidates.append(first)
+ }
+ for arg in args.dropFirst() where arg.hasPrefix("/") {
+ if !arg.hasPrefix("/bin/") && !arg.hasPrefix("/usr/bin/") && !arg.hasPrefix("/System/") {
+ candidates.append(arg)
+ }
+ }
+ }
+ return candidates
+ }
+ }
+
+ private func cachedCommandExists(_ toolName: String, cache: inout [String: Bool]) async -> Bool {
+ if let cached = cache[toolName] { return cached }
+ let quickPaths = [
+ "/opt/homebrew/bin/\(toolName)",
+ "/usr/local/bin/\(toolName)",
+ "/usr/bin/\(toolName)",
+ "/bin/\(toolName)"
+ ]
+ if quickPaths.contains(where: { fileManager.isExecutableFile(atPath: $0) }) {
+ cache[toolName] = true
+ return true
+ }
+ let exists = await commandRunner.commandExists(toolName)
+ cache[toolName] = exists
+ return exists
+ }
private func checkOwnership(
file: URL,
identities: [AppIdentity],
- probe: EvidenceProbe
+ probe: EvidenceProbe,
+ installedHomebrewFormulae: Set,
+ commandExistsCache: inout [String: Bool]
) async -> Bool {
let rawFilename = file.lastPathComponent.lowercased()
- let filename = stripTeamIDPrefix(from: rawFilename)
+ let filename = Self.stripTeamIDPrefix(from: rawFilename)
.replacingOccurrences(of: "group.", with: "")
.replacingOccurrences(of: "groups.", with: "")
let path = file.path.lowercased()
let cleanName = (filename as NSString).deletingPathExtension.lowercased()
+ // 0. Homebrew / CLI service LaunchAgents & LaunchDaemons (formulae have no .app bundle)
+ if path.contains("/launchagents/") || path.contains("/launchdaemons/") {
+ if (rawFilename.hasPrefix("homebrew.mxcl.") || rawFilename.hasPrefix("homebrew.cask.")),
+ rawFilename.hasSuffix(".plist") {
+ let prefixLen = rawFilename.hasPrefix("homebrew.mxcl.")
+ ? "homebrew.mxcl.".count
+ : "homebrew.cask.".count
+ let formulaName = String(rawFilename.dropFirst(prefixLen).dropLast(".plist".count))
+ if !formulaName.isEmpty, installedHomebrewFormulae.contains(formulaName) {
+ return true
+ }
+ let execPaths = Self.extractLaunchdExecutablePaths(from: file)
+ if execPaths.contains(where: { fileManager.fileExists(atPath: $0) }) {
+ return true
+ }
+ } else if rawFilename.hasSuffix(".plist") {
+ let cliPrefixes = [
+ "/opt/homebrew/", "/usr/local/cellar/", "/usr/local/opt/",
+ "/opt/local/", "/nix/", "/.nix-profile/"
+ ]
+ let execPaths = Self.extractLaunchdExecutablePaths(from: file)
+ if execPaths.contains(where: { exec in
+ let lowerExec = exec.lowercased()
+ return cliPrefixes.contains(where: { lowerExec.contains($0) })
+ && fileManager.fileExists(atPath: exec)
+ }) {
+ return true
+ }
+ }
+ }
+
// 1. Direct identity matching: app name, bundle ID, vendor names
for identity in identities {
let bid = identity.bundleID.lowercased()
@@ -297,15 +448,14 @@ public actor OrphanScanner {
if filename.hasPrefix(".") {
let toolName = String(filename.dropFirst())
if !toolName.isEmpty {
- let exists = await commandRunner.commandExists(toolName)
- if exists {
+ if await cachedCommandExists(toolName, cache: &commandExistsCache) {
return true
}
}
}
if cleanName.contains("java") || cleanName.contains("openjdk") {
- if await commandRunner.commandExists("java") {
+ if await cachedCommandExists("java", cache: &commandExistsCache) {
return true
}
}
@@ -329,7 +479,63 @@ public actor OrphanScanner {
return false
}
- private func extractBundleIDAndName(from file: URL) -> (bundleID: String?, name: String) {
+ private func stripTeamIDPrefix(from string: String) -> String {
+ Self.stripTeamIDPrefix(from: string)
+ }
+
+ public static func displayName(fromDotSeparated base: String) -> String {
+ let rawParts = base.split(separator: ".").map(String.init)
+ guard rawParts.count >= 2 else { return base }
+
+ // Versioned tool/app plists like "python3.8", "python3.12", "app.2.0"
+ if rawParts.dropFirst().allSatisfy({ !$0.isEmpty && $0.allSatisfy(\.isNumber) }) {
+ return base
+ }
+
+ var parts = rawParts
+ let technicalTails: Set = ["lssharedfilelist"]
+ while parts.count > 2, let last = parts.last, technicalTails.contains(last.lowercased()) {
+ parts.removeLast()
+ }
+
+ let last = parts.last ?? base
+ if parts.count >= 2, !last.isEmpty, last.allSatisfy(\.isNumber) {
+ let prev = parts[parts.count - 2]
+ let tldStopwords: Set = ["com", "org", "net", "io", "app", "dev", "co", "uk", "de", "ru"]
+ if !tldStopwords.contains(prev.lowercased()) {
+ if prev.last?.isNumber == true {
+ return "\(prev).\(last)"
+ }
+ return "\(formatSegment(prev)) \(last)"
+ }
+ return base
+ }
+
+ return formatSegment(last)
+ }
+
+ private static func formatSegment(_ segment: String) -> String {
+ guard !segment.isEmpty else { return segment }
+ if segment.contains(where: \.isUppercase) {
+ return segment
+ }
+ return segment.prefix(1).uppercased() + segment.dropFirst()
+ }
+
+ private static let residualFileExtensions: Set = [
+ "plist", "savedstate", "sfl", "sfl2", "sfl3", "sfl4",
+ "binarycookies", "log", "json", "yaml", "yml", "xml", "conf"
+ ]
+
+ private static func strippingResidualExtension(from filename: String) -> String {
+ let ext = (filename as NSString).pathExtension.lowercased()
+ guard !ext.isEmpty, residualFileExtensions.contains(ext) else {
+ return filename
+ }
+ return (filename as NSString).deletingPathExtension
+ }
+
+ public static func extractBundleIDAndName(from file: URL) -> (bundleID: String?, name: String) {
var filename = file.lastPathComponent
let path = file.path
@@ -339,32 +545,26 @@ public actor OrphanScanner {
.replacingOccurrences(of: "groups.", with: "")
// Check if plist has embedded bundle identifier
- if filename.hasSuffix(".plist") {
+ if filename.lowercased().hasSuffix(".plist") {
let base = (filename as NSString).deletingPathExtension
if base.contains(".") && !base.hasPrefix(".") {
- let parts = base.components(separatedBy: ".")
- let lastPart = parts.last?.capitalized ?? base
- return (base, lastPart)
+ return (base, displayName(fromDotSeparated: base))
}
}
// Check Containers & Group Containers
if path.contains("/Containers/") || path.contains("/Group Containers/") {
- let clean = (filename as NSString).deletingPathExtension
+ let clean = strippingResidualExtension(from: filename)
if clean.contains(".") {
- let parts = clean.components(separatedBy: ".")
- let lastPart = parts.last?.capitalized ?? clean
- return (clean, lastPart)
+ return (clean, displayName(fromDotSeparated: clean))
}
}
// Check Saved Application State
- if filename.hasSuffix(".savedState") {
+ if filename.lowercased().hasSuffix(".savedstate") {
let base = (filename as NSString).deletingPathExtension
if base.contains(".") {
- let parts = base.components(separatedBy: ".")
- let lastPart = parts.last?.capitalized ?? base
- return (base, lastPart)
+ return (base, displayName(fromDotSeparated: base))
}
}
@@ -372,10 +572,8 @@ public actor OrphanScanner {
if filename.contains(".") && !filename.hasPrefix(".") {
let prefixes = ["com.", "org.", "net.", "io.", "app.", "dev.", "co.", "uk.", "de.", "ru."]
if prefixes.contains(where: { filename.lowercased().hasPrefix($0) }) {
- let clean = (filename as NSString).deletingPathExtension
- let parts = clean.components(separatedBy: ".")
- let lastPart = parts.last?.capitalized ?? clean
- return (clean, lastPart)
+ let clean = strippingResidualExtension(from: filename)
+ return (clean, displayName(fromDotSeparated: clean))
}
}
@@ -449,7 +647,17 @@ public actor OrphanScanner {
let ruleScore = rule.evidence(for: file, identity: syntheticIdentity).reduce(0) { $0 + $1.weight }
let assessment = ConfidenceEngine.assess(evidence, ruleScore: ruleScore, identity: syntheticIdentity)
- return (evidence, assessment.score, assessment.tier)
+ var tier = assessment.tier
+ let lowerFilename = file.lastPathComponent.lowercased()
+ if lowerFilename.hasPrefix("homebrew.mxcl.") || lowerFilename.hasPrefix("homebrew.cask.") {
+ // Homebrew formula services must never be marked Guaranteed (they may belong to CLI formulae).
+ if Self.extractLaunchdExecutablePaths(from: file).isEmpty {
+ tier = min(tier, .possible)
+ } else {
+ tier = min(tier, .veryLikely)
+ }
+ }
+ return (evidence, assessment.score, tier)
}
private func collectAllScanTargets() async -> Set {
@@ -487,28 +695,33 @@ public actor OrphanScanner {
]
var targets = Set()
- for base in basePaths {
- let url = NormalizedPath.url(base, isDirectory: true)
- guard let contents = try? fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) else { continue }
- for content in contents {
- targets.insert(content.resolvingSymlinksInPath())
+ autoreleasepool {
+ for base in basePaths {
+ let url = NormalizedPath.url(base, isDirectory: true)
+ guard let contents = try? fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: [.isSymbolicLinkKey], options: .skipsHiddenFiles) else { continue }
+ for content in contents {
+ let isSymlink = (try? content.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true
+ targets.insert(NormalizedPath.canonicalize(isSymlink ? content.resolvingSymlinksInPath() : content))
+ }
}
- }
-
- for relative in [".config", ".cache", ".local/share"] {
- let xdgPath = NormalizedPath.joinHome(home, relative)
- let url = NormalizedPath.url(xdgPath, isDirectory: true)
- guard let contents = try? fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) else { continue }
- for content in contents {
- targets.insert(content.resolvingSymlinksInPath())
+
+ for relative in [".config", ".cache", ".local/share"] {
+ let xdgPath = NormalizedPath.joinHome(home, relative)
+ let url = NormalizedPath.url(xdgPath, isDirectory: true)
+ guard let contents = try? fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: [.isSymbolicLinkKey], options: .skipsHiddenFiles) else { continue }
+ for content in contents {
+ let isSymlink = (try? content.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true
+ targets.insert(NormalizedPath.canonicalize(isSymlink ? content.resolvingSymlinksInPath() : content))
+ }
}
- }
- // Home dot-folders (~/.cursor, ~/.anydesk, ~/.antigravity)
- let homeURL = NormalizedPath.url(home, isDirectory: true)
- if let homeContents = try? fileManager.contentsOfDirectory(at: homeURL, includingPropertiesForKeys: nil, options: []) {
- for item in homeContents where item.lastPathComponent.hasPrefix(".") {
- targets.insert(item.resolvingSymlinksInPath())
+ // Home dot-folders (~/.cursor, ~/.anydesk, ~/.antigravity)
+ let homeURL = NormalizedPath.url(home, isDirectory: true)
+ if let homeContents = try? fileManager.contentsOfDirectory(at: homeURL, includingPropertiesForKeys: [.isSymbolicLinkKey], options: []) {
+ for item in homeContents where item.lastPathComponent.hasPrefix(".") {
+ let isSymlink = (try? item.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true
+ targets.insert(NormalizedPath.canonicalize(isSymlink ? item.resolvingSymlinksInPath() : item))
+ }
}
}
diff --git a/MacOSCleaner/Features/Uninstaller/OrphanedResidualsView.swift b/MacOSCleaner/Features/Uninstaller/OrphanedResidualsView.swift
index 87cbf2c..dd9c9a0 100644
--- a/MacOSCleaner/Features/Uninstaller/OrphanedResidualsView.swift
+++ b/MacOSCleaner/Features/Uninstaller/OrphanedResidualsView.swift
@@ -7,36 +7,25 @@ private extension Logger {
}
public struct OrphanedResidualsView: View {
- let service: UninstallerService
+ @Bindable var viewModel: UninstallerViewModel
let settings: AppSettings
- @State private var items: [OrphanItem] = []
- @State private var isLoading = false
- @State private var hasScanned = false
- @State private var scanProgressMessage = ""
- @State private var searchText = ""
- @State private var selectedFilterTier: ConfidenceTier? = nil
- @State private var expandedItemIDs: Set = []
@State private var showingConfirmation = false
- @State private var isCleaning = false
- @State private var scanTask: Task? = nil
- @State private var errorMessage: String? = nil
- @State private var showingErrorAlert = false
- public init(service: UninstallerService, settings: AppSettings) {
- self.service = service
+ public init(viewModel: UninstallerViewModel, settings: AppSettings) {
+ self.viewModel = viewModel
self.settings = settings
}
private var filteredItems: [OrphanItem] {
- items.filter { item in
- let matchesSearch = searchText.isEmpty
- || item.name.localizedCaseInsensitiveContains(searchText)
- || (item.bundleID?.localizedCaseInsensitiveContains(searchText) ?? false)
- || item.url.path.localizedCaseInsensitiveContains(searchText)
+ viewModel.orphanItems.filter { item in
+ let matchesSearch = viewModel.orphanSearchText.isEmpty
+ || item.name.localizedCaseInsensitiveContains(viewModel.orphanSearchText)
+ || (item.bundleID?.localizedCaseInsensitiveContains(viewModel.orphanSearchText) ?? false)
+ || item.url.path.localizedCaseInsensitiveContains(viewModel.orphanSearchText)
let matchesTier: Bool
- if let filterTier = selectedFilterTier {
+ if let filterTier = viewModel.orphanFilterTier {
matchesTier = item.confidence == filterTier
} else {
matchesTier = true
@@ -47,7 +36,7 @@ public struct OrphanedResidualsView: View {
}
private var selectedItems: [OrphanItem] {
- items.filter(\.isSelected)
+ viewModel.orphanItems.filter(\.isSelected)
}
private var selectedSizeBytes: Int64 {
@@ -56,18 +45,17 @@ public struct OrphanedResidualsView: View {
public var body: some View {
VStack(spacing: 0) {
- // Content
- if isLoading {
+ if viewModel.isLoadingOrphans {
AnimatedScanView(
title: "uninstaller_scanning_leftovers".localized,
- subtitle: scanProgressMessage,
+ subtitle: viewModel.orphanScanProgressMessage,
currentStep: 1,
totalSteps: 1
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
- } else if !hasScanned {
+ } else if !viewModel.hasScannedOrphans {
heroStateView
- } else if items.isEmpty {
+ } else if viewModel.orphanItems.isEmpty {
emptyStateView
} else {
resultsView
@@ -87,7 +75,7 @@ public struct OrphanedResidualsView: View {
: "uninstaller_move_trash".localized,
role: .destructive
) {
- performCleaning()
+ viewModel.cleanSelectedOrphans(selectedItems, settings: settings)
}
Button("cancel".localized, role: .cancel) { }
} message: {
@@ -97,10 +85,10 @@ public struct OrphanedResidualsView: View {
ByteCountFormatter.localizedString(fromByteCount: selectedSizeBytes, countStyle: .file)
))
}
- .alert("error".localized, isPresented: $showingErrorAlert) {
+ .alert("error".localized, isPresented: $viewModel.showingOrphanErrorAlert) {
Button("ok".localized, role: .cancel) { }
} message: {
- if let errorMessage {
+ if let errorMessage = viewModel.orphanErrorMessage {
Text(errorMessage)
}
}
@@ -127,7 +115,7 @@ public struct OrphanedResidualsView: View {
.frame(maxWidth: 480)
}
- Button(action: startScan) {
+ Button(action: { viewModel.startOrphanScan() }) {
HStack(spacing: 8) {
Image(systemName: "magnifyingglass")
Text("uninstaller_start_leftover_scan".localized)
@@ -161,7 +149,7 @@ public struct OrphanedResidualsView: View {
.foregroundColor(.secondary)
}
- Button(action: startScan) {
+ Button(action: { viewModel.startOrphanScan() }) {
HStack(spacing: 6) {
Image(systemName: "arrow.clockwise")
Text("uninstaller_reload".localized)
@@ -180,16 +168,15 @@ public struct OrphanedResidualsView: View {
VStack(spacing: 0) {
// Filter Bar
HStack(spacing: 10) {
- // Search box
HStack(spacing: 6) {
Image(systemName: "magnifyingglass")
.foregroundColor(.secondary)
.font(.caption)
- TextField("uninstaller_search".localized, text: $searchText)
+ TextField("uninstaller_search".localized, text: $viewModel.orphanSearchText)
.textFieldStyle(.plain)
.font(.caption)
- if !searchText.isEmpty {
- Button(action: { searchText = "" }) {
+ if !viewModel.orphanSearchText.isEmpty {
+ Button(action: { viewModel.orphanSearchText = "" }) {
Image(systemName: "xmark.circle.fill")
.foregroundColor(.secondary)
.font(.caption2)
@@ -203,7 +190,6 @@ public struct OrphanedResidualsView: View {
.cornerRadius(8)
.frame(maxWidth: 240)
- // Filter chips
HStack(spacing: 4) {
filterChip(title: "uninstaller_filter_all".localized, tier: nil)
filterChip(title: ConfidenceTier.guaranteed.displayKey.localized, tier: .guaranteed)
@@ -213,7 +199,7 @@ public struct OrphanedResidualsView: View {
Spacer()
- Button(action: startScan) {
+ Button(action: { viewModel.startOrphanScan() }) {
Image(systemName: "arrow.clockwise")
}
.glassButtonStyle()
@@ -225,7 +211,6 @@ public struct OrphanedResidualsView: View {
Divider()
- // List of items
List {
ForEach(filteredItems) { item in
orphanRow(for: item)
@@ -241,7 +226,7 @@ public struct OrphanedResidualsView: View {
// Bottom Action Bar
HStack(spacing: 12) {
Button(action: toggleSelectAll) {
- Text(items.allSatisfy(\.isSelected) ? "deselect_all".localized : "select_all".localized)
+ Text(viewModel.orphanItems.allSatisfy(\.isSelected) ? "deselect_all".localized : "select_all".localized)
.font(.caption)
}
.buttonStyle(.plain)
@@ -251,7 +236,7 @@ public struct OrphanedResidualsView: View {
.foregroundColor(.secondary)
.font(.caption2)
- Text(String(format: "uninstaller_leftovers_found_count".localized, Int64(items.count)))
+ Text(String(format: "uninstaller_leftovers_found_count".localized, Int64(viewModel.orphanItems.count)))
.font(.caption)
.foregroundColor(.secondary)
@@ -262,7 +247,7 @@ public struct OrphanedResidualsView: View {
Button(action: { showingConfirmation = true }) {
HStack(spacing: 6) {
- if isCleaning {
+ if viewModel.isCleaningOrphans {
ProgressView().controlSize(.small)
} else {
Image(systemName: "trash")
@@ -274,7 +259,7 @@ public struct OrphanedResidualsView: View {
}
.destructiveGlassButtonStyle()
.controlSize(.large)
- .disabled(selectedItems.isEmpty || isCleaning)
+ .disabled(selectedItems.isEmpty || viewModel.isCleaningOrphans)
}
.padding(.horizontal, 16)
.padding(.vertical, 12)
@@ -284,10 +269,10 @@ public struct OrphanedResidualsView: View {
@ViewBuilder
private func filterChip(title: String, tier: ConfidenceTier?) -> some View {
- let isSelected = selectedFilterTier == tier
+ let isSelected = viewModel.orphanFilterTier == tier
Button(action: {
withAnimation(.spring(response: 0.2, dampingFraction: 0.8)) {
- selectedFilterTier = tier
+ viewModel.orphanFilterTier = tier
}
}) {
Text(title)
@@ -307,16 +292,16 @@ public struct OrphanedResidualsView: View {
}
private func toggleSelectAll() {
- let allSelected = items.allSatisfy(\.isSelected)
- for i in items.indices {
- items[i].isSelected = !allSelected
+ let allSelected = viewModel.orphanItems.allSatisfy(\.isSelected)
+ for i in viewModel.orphanItems.indices {
+ viewModel.orphanItems[i].isSelected = !allSelected
}
}
@ViewBuilder
private func orphanRow(for item: OrphanItem) -> some View {
- let isExpanded = expandedItemIDs.contains(item.id)
- let index = items.firstIndex(where: { $0.id == item.id })
+ let isExpanded = viewModel.expandedOrphanIDs.contains(item.id)
+ let index = viewModel.orphanItems.firstIndex(where: { $0.id == item.id })
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 10) {
@@ -324,7 +309,7 @@ public struct OrphanedResidualsView: View {
get: { item.isSelected },
set: { val in
if let idx = index {
- items[idx].isSelected = val
+ viewModel.orphanItems[idx].isSelected = val
}
}
))
@@ -341,7 +326,7 @@ public struct OrphanedResidualsView: View {
.fontWeight(.medium)
.lineLimit(1)
- if let bid = item.bundleID {
+ if let bid = item.bundleID, bid.lowercased() != item.name.lowercased() {
Text(bid)
.font(.system(size: 9, design: .monospaced))
.foregroundColor(.secondary)
@@ -351,7 +336,7 @@ public struct OrphanedResidualsView: View {
.cornerRadius(4)
}
- Text(item.category)
+ Text(item.localizedCategory)
.font(.caption2)
.foregroundColor(.secondary)
.padding(.horizontal, 4)
@@ -394,9 +379,9 @@ public struct OrphanedResidualsView: View {
Button {
withAnimation(.spring(response: 0.25, dampingFraction: 0.8)) {
if isExpanded {
- expandedItemIDs.remove(item.id)
+ viewModel.expandedOrphanIDs.remove(item.id)
} else {
- expandedItemIDs.insert(item.id)
+ viewModel.expandedOrphanIDs.insert(item.id)
}
}
} label: {
@@ -432,79 +417,9 @@ public struct OrphanedResidualsView: View {
case "Caches": return "archivebox.fill"
case "Containers": return "shippingbox.fill"
case "Logs": return "doc.text.fill"
+ case "Launch Agents", "LaunchAgents": return "bolt.horizontal.fill"
case "Developer": return "wrench.and.screwdriver.fill"
default: return "doc.fill"
}
}
-
- // MARK: - Actions
-
- private func startScan() {
- scanTask?.cancel()
- isLoading = true
- scanProgressMessage = "uninstaller.progress.discovering".localized
-
- scanTask = Task {
- do {
- let found = try await service.scanOrphanedResiduals { message in
- Task { @MainActor in
- self.scanProgressMessage = message
- }
- }
- await MainActor.run {
- self.items = found
- self.isLoading = false
- self.hasScanned = true
- }
- } catch {
- Logger.orphanView.error("Orphan scan failed: \(error.localizedDescription, privacy: .public)")
- await MainActor.run {
- self.isLoading = false
- self.hasScanned = true
- }
- }
- }
- }
-
- private func performCleaning() {
- let targets = selectedItems
- guard !targets.isEmpty else { return }
-
- isCleaning = true
- Task {
- defer { isCleaning = false }
- do {
- let result = try await service.removeOrphanedResiduals(
- targets,
- bypassTrash: settings.bypassTrashOnUninstall
- )
-
- await MainActor.run {
- let removedIDs = Set(result.succeededItems.map(\.id))
- self.items.removeAll { removedIDs.contains($0.id) }
-
- if !result.failedItems.isEmpty {
- self.errorMessage = String(format: "orphaned_cleanup_failed_count".localized, Int64(result.failedItems.count))
- self.showingErrorAlert = true
- }
-
- if settings.showNotifications, !result.succeededItems.isEmpty {
- let title = "uninstaller_complete_title".localized
- let body = String(
- format: "uninstaller_leftovers_cleaned_notification".localized,
- Int64(result.succeededItems.count),
- ByteCountFormatter.localizedString(fromByteCount: result.freed, countStyle: .file)
- )
- NotificationManager.shared.sendNotification(title: title, body: body)
- }
- }
- } catch {
- Logger.orphanView.error("Cleaning failed: \(error.localizedDescription, privacy: .public)")
- await MainActor.run {
- self.errorMessage = error.localizedDescription
- self.showingErrorAlert = true
- }
- }
- }
- }
}
diff --git a/MacOSCleaner/Features/Uninstaller/PostUninstallLeftoversSheet.swift b/MacOSCleaner/Features/Uninstaller/PostUninstallLeftoversSheet.swift
index f9cd29a..3e58f42 100644
--- a/MacOSCleaner/Features/Uninstaller/PostUninstallLeftoversSheet.swift
+++ b/MacOSCleaner/Features/Uninstaller/PostUninstallLeftoversSheet.swift
@@ -324,7 +324,7 @@ public struct EvidenceCardView: View {
.font(.caption)
.fontWeight(.bold)
Spacer()
- Text("Score: \(score)")
+ Text(String(format: "uninstaller_evidence_score".localized, Int64(score)))
.font(.system(size: 9, design: .monospaced))
.foregroundColor(.secondary)
}
diff --git a/MacOSCleaner/Features/Uninstaller/ResidualScanIndex.swift b/MacOSCleaner/Features/Uninstaller/ResidualScanIndex.swift
new file mode 100644
index 0000000..189b02f
--- /dev/null
+++ b/MacOSCleaner/Features/Uninstaller/ResidualScanIndex.swift
@@ -0,0 +1,441 @@
+import Foundation
+import os
+
+/// One-pass snapshot of standard ~/Library, /Library, Darwin, receipt, Homebrew, and /tmp roots
+/// shared across all apps in a batch deep-scan to avoid O(apps × entries) filesystem re-enumeration.
+public final class ResidualScanIndex: Sendable {
+ public struct IndexedEntry: Sendable, Hashable {
+ public let url: URL
+ public let name: String
+ public let lowerName: String
+ public let parentName: String
+ public let lowerParentName: String
+ public let isDirectory: Bool
+ public let isSymlink: Bool
+
+ public init(
+ url: URL,
+ name: String,
+ lowerName: String,
+ parentName: String,
+ lowerParentName: String,
+ isDirectory: Bool,
+ isSymlink: Bool
+ ) {
+ self.url = url
+ self.name = name
+ self.lowerName = lowerName
+ self.parentName = parentName
+ self.lowerParentName = lowerParentName
+ self.isDirectory = isDirectory
+ self.isSymlink = isSymlink
+ }
+ }
+
+ public struct HomebrewAppEntry: Sendable {
+ public let url: URL
+ public let bundleIDLower: String?
+ }
+
+ public let baseDirectoryEntries: [String: [IndexedEntry]]
+ public let allBaseEntries: [IndexedEntry]
+ public let darwinEntries: [IndexedEntry]
+ public let receiptEntries: [IndexedEntry]
+ public let homeEntries: [IndexedEntry]
+ public let homebrewAppsByLowerName: [String: [HomebrewAppEntry]]
+ public let tmpTopLevelEntries: [IndexedEntry]
+ /// `nil` when `pkgutil --pkgs` produced no packages or failed (e.g. mock test runners).
+ public let pkgutilPackages: [String]?
+
+ private let byExactLowerName: [String: [Int]]
+ private let byTokenPrefix2: [String: [Int]]
+ private let byTokenPrefix3: [String: [Int]]
+ private let subdirectoryCache = OSAllocatedUnfairLock<[String: [IndexedEntry]]>(initialState: [:])
+ private let pkgutilFilesCache = OSAllocatedUnfairLock<[String: [String]]>(initialState: [:])
+
+ private static let tokenStopwords: Set = [
+ "com", "org", "net", "io", "app", "co", "dev", "ai",
+ "uk", "de", "ru", "fr", "jp", "cn", "me", "tv", "gg", "sh",
+ "us", "eu", "inc", "ltd", "llc", "apple"
+ ]
+
+ private init(
+ baseDirectoryEntries: [String: [IndexedEntry]],
+ allBaseEntries: [IndexedEntry],
+ byExactLowerName: [String: [Int]],
+ byTokenPrefix2: [String: [Int]],
+ byTokenPrefix3: [String: [Int]],
+ darwinEntries: [IndexedEntry],
+ receiptEntries: [IndexedEntry],
+ homeEntries: [IndexedEntry],
+ homebrewAppsByLowerName: [String: [HomebrewAppEntry]],
+ tmpTopLevelEntries: [IndexedEntry],
+ pkgutilPackages: [String]?
+ ) {
+ self.baseDirectoryEntries = baseDirectoryEntries
+ self.allBaseEntries = allBaseEntries
+ self.byExactLowerName = byExactLowerName
+ self.byTokenPrefix2 = byTokenPrefix2
+ self.byTokenPrefix3 = byTokenPrefix3
+ self.darwinEntries = darwinEntries
+ self.receiptEntries = receiptEntries
+ self.homeEntries = homeEntries
+ self.homebrewAppsByLowerName = homebrewAppsByLowerName
+ self.tmpTopLevelEntries = tmpTopLevelEntries
+ self.pkgutilPackages = pkgutilPackages
+ }
+
+ /// Reads one directory in a single kernel pass (`getattrlistbulk` via `URLResourceValues`).
+ public static func readDirectory(
+ at dirURL: URL,
+ options: FileManager.DirectoryEnumerationOptions = [],
+ fileManager: FileManager = .default
+ ) -> [IndexedEntry] {
+ autoreleasepool {
+ guard let contents = try? fileManager.contentsOfDirectory(
+ at: dirURL,
+ includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
+ options: options
+ ) else {
+ return []
+ }
+ let parentName = dirURL.lastPathComponent
+ let lowerParentName = parentName.lowercased()
+ var entries: [IndexedEntry] = []
+ entries.reserveCapacity(contents.count)
+ for item in contents {
+ let rv = try? item.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
+ let isSymlink = rv?.isSymbolicLink == true
+ let isDirectory = !isSymlink && (rv?.isDirectory == true)
+ let name = item.lastPathComponent
+ entries.append(IndexedEntry(
+ url: NormalizedPath.canonicalize(item),
+ name: name,
+ lowerName: name.lowercased(),
+ parentName: parentName,
+ lowerParentName: lowerParentName,
+ isDirectory: isDirectory,
+ isSymlink: isSymlink
+ ))
+ }
+ return entries
+ }
+ }
+
+ public static func build(
+ fileSystemContext: FileSystemContext = .production,
+ homebrewCellarDirectories: [URL] = AppDiscovery.defaultHomebrewCellarDirectories,
+ darwinUserDirectories: [URL]? = nil,
+ receiptsDirectory: URL? = nil,
+ tmpScanDirectory: URL? = nil,
+ commandRunner: any CommandRunning = CommandRunner(),
+ fileManager: FileManager = .default
+ ) async -> ResidualScanIndex {
+ let home = fileSystemContext.homePath
+
+ var baseDirs: [String] = CandidateCollector.basePaths(home: home)
+ for relative in [".config", ".cache", ".local/share"] {
+ baseDirs.append(NormalizedPath.joinHome(home, relative))
+ }
+ var seenBaseKeys = Set()
+ var uniqueBaseDirs: [URL] = []
+ for path in baseDirs {
+ let url = NormalizedPath.url(path, isDirectory: true)
+ let key = NormalizedPath.key(url)
+ if seenBaseKeys.insert(key).inserted {
+ uniqueBaseDirs.append(url)
+ }
+ }
+
+ let resolvedDarwinDirs: [URL]
+ if let darwinUserDirectories {
+ resolvedDarwinDirs = darwinUserDirectories
+ } else {
+ let parent = fileManager.temporaryDirectory
+ .deletingLastPathComponent()
+ .resolvingSymlinksInPath()
+ resolvedDarwinDirs = ["C", "T", "X"].map {
+ parent.appendingPathComponent($0, isDirectory: true)
+ }
+ }
+
+ let resolvedReceiptsDir = (receiptsDirectory
+ ?? URL(fileURLWithPath: "/private/var/db/receipts", isDirectory: true))
+ .resolvingSymlinksInPath()
+ let resolvedTmpDir = (tmpScanDirectory
+ ?? URL(fileURLWithPath: "/private/tmp", isDirectory: true))
+ .resolvingSymlinksInPath()
+
+ async let pkgutilTask: [String]? = fetchPkgutilPackages(commandRunner: commandRunner)
+
+ var baseDirectoryEntries: [String: [IndexedEntry]] = [:]
+ baseDirectoryEntries.reserveCapacity(uniqueBaseDirs.count)
+ var allBaseEntries: [IndexedEntry] = []
+
+ for dirURL in uniqueBaseDirs {
+ let key = NormalizedPath.key(dirURL)
+ let entries = readDirectory(at: dirURL, options: [], fileManager: fileManager)
+ baseDirectoryEntries[key] = entries
+ if !entries.isEmpty {
+ allBaseEntries.append(contentsOf: entries)
+ }
+ }
+
+ var byExactLowerName: [String: [Int]] = [:]
+ var byTokenPrefix2: [String: [Int]] = [:]
+ var byTokenPrefix3: [String: [Int]] = [:]
+ byExactLowerName.reserveCapacity(allBaseEntries.count)
+
+ for idx in allBaseEntries.indices {
+ let lowerName = allBaseEntries[idx].lowerName
+ byExactLowerName[lowerName, default: []].append(idx)
+
+ let bare = lowerName.hasPrefix(".") ? String(lowerName.dropFirst()) : lowerName
+ let compactBare = EvidenceProbe.compactIdentityToken(bare)
+ if compactBare.count >= 2 {
+ byTokenPrefix2[String(compactBare.prefix(2)), default: []].append(idx)
+ }
+ if compactBare.count >= 3 {
+ byTokenPrefix3[String(compactBare.prefix(3)), default: []].append(idx)
+ }
+
+ for token in alnumTokens(in: lowerName) {
+ if token.count >= 2 {
+ byTokenPrefix2[String(token.prefix(2)), default: []].append(idx)
+ }
+ if token.count >= 3 {
+ byTokenPrefix3[String(token.prefix(3)), default: []].append(idx)
+ }
+ }
+ }
+
+ var darwinEntries: [IndexedEntry] = []
+ for dir in resolvedDarwinDirs {
+ darwinEntries.append(contentsOf: readDirectory(at: dir, options: [.skipsHiddenFiles], fileManager: fileManager))
+ }
+
+ let receiptEntries = readDirectory(at: resolvedReceiptsDir, options: [.skipsHiddenFiles], fileManager: fileManager)
+ let homeURL = NormalizedPath.url(home, isDirectory: true)
+ let homeEntries = readDirectory(at: homeURL, options: [], fileManager: fileManager)
+ let homebrewApps = indexHomebrewApps(in: homebrewCellarDirectories, fileManager: fileManager)
+ let tmpTopLevel = readDirectory(at: resolvedTmpDir, options: [.skipsHiddenFiles], fileManager: fileManager)
+ let pkgutilPackages = await pkgutilTask
+
+ return ResidualScanIndex(
+ baseDirectoryEntries: baseDirectoryEntries,
+ allBaseEntries: allBaseEntries,
+ byExactLowerName: byExactLowerName,
+ byTokenPrefix2: byTokenPrefix2,
+ byTokenPrefix3: byTokenPrefix3,
+ darwinEntries: darwinEntries,
+ receiptEntries: receiptEntries,
+ homeEntries: homeEntries,
+ homebrewAppsByLowerName: homebrewApps,
+ tmpTopLevelEntries: tmpTopLevel,
+ pkgutilPackages: pkgutilPackages
+ )
+ }
+
+ public func candidateBaseEntries(for identity: AppIdentity) -> [IndexedEntry] {
+ var matchedIndices = Set()
+ var needsFullFallback = false
+
+ func addIndices(_ indices: [Int]?) {
+ guard let indices else { return }
+ matchedIndices.formUnion(indices)
+ }
+
+ func addPrefixLookup(forToken token: String) {
+ if token.count >= 3 {
+ addIndices(byTokenPrefix3[String(token.prefix(3))])
+ } else if token.count == 2 {
+ addIndices(byTokenPrefix2[token])
+ } else if token.count == 1 {
+ needsFullFallback = true
+ }
+ }
+
+ func addTermLookup(_ rawTerm: String) {
+ let lower = rawTerm.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !lower.isEmpty else { return }
+ addIndices(byExactLowerName[lower])
+ addIndices(byExactLowerName["." + lower])
+
+ let compact = EvidenceProbe.compactIdentityToken(lower)
+ if !compact.isEmpty {
+ addPrefixLookup(forToken: compact)
+ }
+
+ let tokens = Self.alnumTokens(in: lower)
+ if let first = tokens.first {
+ addPrefixLookup(forToken: first)
+ }
+ for token in tokens where token.count >= 2 && !Self.tokenStopwords.contains(token) {
+ addPrefixLookup(forToken: token)
+ }
+ }
+
+ let lowerBundleID = identity.bundleID.lowercased()
+ if !lowerBundleID.isEmpty, !lowerBundleID.hasPrefix("unknown.") {
+ addIndices(byExactLowerName[lowerBundleID])
+ let bidTokens = Self.alnumTokens(in: lowerBundleID)
+ let significant = bidTokens.filter { !Self.tokenStopwords.contains($0) }
+ let queryTokens = significant.isEmpty ? bidTokens : significant
+ if queryTokens.contains(where: { $0.count < 2 }) || queryTokens.isEmpty {
+ needsFullFallback = true
+ } else {
+ for token in queryTokens {
+ addPrefixLookup(forToken: token)
+ }
+ }
+ }
+
+ addTermLookup(identity.appName)
+ if let bundleName = identity.bundleName, !bundleName.isEmpty {
+ addTermLookup(bundleName)
+ }
+ if !identity.executableName.isEmpty {
+ addTermLookup(identity.executableName)
+ }
+
+ if let teamID = identity.teamID, !teamID.isEmpty {
+ addPrefixLookup(forToken: teamID.lowercased())
+ }
+
+ for group in identity.appGroups where !group.isEmpty {
+ addIndices(byExactLowerName[group.lowercased()])
+ }
+
+ for helper in identity.helperNames {
+ let helperLower = helper.lowercased()
+ guard helperLower.count >= 3 else { continue }
+ addIndices(byExactLowerName[helperLower])
+ let compactHelper = EvidenceProbe.compactIdentityToken(helperLower)
+ if compactHelper.count >= 2 {
+ addPrefixLookup(forToken: compactHelper)
+ }
+ if let first = Self.alnumTokens(in: helperLower).first {
+ addPrefixLookup(forToken: first)
+ }
+ }
+
+ for vendor in identity.vendorNames where !vendor.isEmpty {
+ addIndices(byExactLowerName[vendor.lowercased()])
+ }
+
+ if needsFullFallback {
+ return allBaseEntries
+ }
+ return matchedIndices.map { allBaseEntries[$0] }
+ }
+
+ public func entries(
+ inDirectory dirURL: URL,
+ options: FileManager.DirectoryEnumerationOptions = [],
+ fileManager: FileManager = .default
+ ) -> [IndexedEntry] {
+ let key = NormalizedPath.key(dirURL)
+ if let base = baseDirectoryEntries[key] {
+ if options.contains(.skipsHiddenFiles) {
+ return base.filter { !$0.name.hasPrefix(".") }
+ }
+ return base
+ }
+
+ let cacheKey = options.contains(.skipsHiddenFiles) ? "\(key)|nh" : key
+ if let cached = subdirectoryCache.withLock({ $0[cacheKey] }) {
+ return cached
+ }
+
+ let loaded = Self.readDirectory(at: dirURL, options: options, fileManager: fileManager)
+ subdirectoryCache.withLock { cache in
+ if cache.count < 4096 {
+ cache[cacheKey] = loaded
+ }
+ }
+ return loaded
+ }
+
+ public func pkgutilFiles(for packageID: String, commandRunner: any CommandRunning) async -> [String] {
+ if let cached = pkgutilFilesCache.withLock({ $0[packageID] }) {
+ return cached
+ }
+ guard let result = try? await commandRunner.run(command: "/usr/sbin/pkgutil", arguments: ["--files", packageID]),
+ result.exitCode == 0 else {
+ pkgutilFilesCache.withLock { $0[packageID] = [] }
+ return []
+ }
+ let files = result.stdout.split(whereSeparator: \.isNewline).map(String.init)
+ pkgutilFilesCache.withLock { cache in
+ if cache.count < 1024 {
+ cache[packageID] = files
+ }
+ }
+ return files
+ }
+
+ private static func alnumTokens(in string: String) -> [String] {
+ var tokens: [String] = []
+ var current = ""
+ for ch in string {
+ if ch.isLetter || ch.isNumber {
+ current.append(ch)
+ } else if !current.isEmpty {
+ tokens.append(current)
+ current.removeAll(keepingCapacity: true)
+ }
+ }
+ if !current.isEmpty {
+ tokens.append(current)
+ }
+ return tokens
+ }
+
+ private static func fetchPkgutilPackages(commandRunner: any CommandRunning) async -> [String]? {
+ guard let result = try? await commandRunner.run(command: "/usr/sbin/pkgutil", arguments: ["--pkgs"]),
+ result.exitCode == 0 else {
+ return nil
+ }
+ let packages = result.stdout.split(whereSeparator: \.isNewline).map(String.init)
+ return packages.isEmpty ? nil : packages
+ }
+
+ private static func indexHomebrewApps(
+ in cellarDirectories: [URL],
+ fileManager: FileManager
+ ) -> [String: [HomebrewAppEntry]] {
+ guard !cellarDirectories.isEmpty else { return [:] }
+ var map: [String: [HomebrewAppEntry]] = [:]
+ autoreleasepool {
+ for cellar in cellarDirectories {
+ guard let formulae = try? fileManager.contentsOfDirectory(
+ at: cellar,
+ includingPropertiesForKeys: [.isDirectoryKey],
+ options: [.skipsHiddenFiles]
+ ) else { continue }
+ for formula in formulae {
+ guard let versions = try? fileManager.contentsOfDirectory(
+ at: formula,
+ includingPropertiesForKeys: [.isDirectoryKey],
+ options: [.skipsHiddenFiles]
+ ) else { continue }
+ for version in versions {
+ guard let apps = try? fileManager.contentsOfDirectory(
+ at: version,
+ includingPropertiesForKeys: [.isDirectoryKey],
+ options: [.skipsHiddenFiles]
+ ) else { continue }
+ for app in apps {
+ let lowerName = app.lastPathComponent.lowercased()
+ guard lowerName.hasSuffix(".app") else { continue }
+ let resolved = app.resolvingSymlinksInPath()
+ let bid = Bundle(url: resolved)?.bundleIdentifier?.lowercased()
+ map[lowerName, default: []].append(HomebrewAppEntry(url: resolved, bundleIDLower: bid))
+ }
+ }
+ }
+ }
+ }
+ return map
+ }
+}
diff --git a/MacOSCleaner/Features/Uninstaller/Rules/BrowserRule.swift b/MacOSCleaner/Features/Uninstaller/Rules/BrowserRule.swift
index 5923e4f..29829c9 100644
--- a/MacOSCleaner/Features/Uninstaller/Rules/BrowserRule.swift
+++ b/MacOSCleaner/Features/Uninstaller/Rules/BrowserRule.swift
@@ -4,7 +4,9 @@ public struct BrowserRule: ApplicationRule {
public let displayName = "Browser"
public let supportedBundleIDs: Set = [
"com.google.Chrome",
+ "com.google.Chrome.beta",
"com.google.Chrome.canary",
+ "com.google.Chrome.dev",
"org.chromium.Chromium",
"com.brave.Browser",
"com.brave.Browser.beta",
@@ -29,11 +31,8 @@ public struct BrowserRule: ApplicationRule {
"net.mullvad.MullvadBrowser",
"ru.yandex.desktop.yandex-browser",
]
- public let supportedTeamIDs: Set = [
- "EQHXZ8M8AV", // Google
- "BFYZ25A2P4", // Brave
- "G7HH3F8CAK", // Opera?
- ]
+ // Never match by Team ID: EQHXZ8M8AV is shared across all Google apps (Drive, Earth, Updater, ...).
+ public let supportedTeamIDs: Set = []
public let supportedAppNames: Set = [
"Google Chrome", "Chrome", "Chromium", "Brave Browser", "Brave",
"Microsoft Edge", "Edge", "Firefox", "Firefox Developer Edition", "Firefox Nightly",
@@ -42,6 +41,86 @@ public struct BrowserRule: ApplicationRule {
"Mullvad Browser", "Yandex",
]
+ public static let knownLowercasedBundleIDs: Set = Set(
+ BrowserRule().supportedBundleIDs.map { $0.lowercased() }
+ )
+
+ /// True for Chromium/browser web-app shortcuts (`com.google.Chrome.app.`, etc.).
+ public static func isBrowserPWAShimBundleID(_ bundleID: String) -> Bool {
+ let lower = bundleID.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ guard let range = lower.range(of: ".app.") else { return false }
+ let hostPrefix = String(lower[.. Bool {
+ let lower = bundleID.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ guard !lower.isEmpty, !lower.hasPrefix("unknown."), !isBrowserPWAShimBundleID(lower) else {
+ return false
+ }
+ return knownLowercasedBundleIDs.contains(lower)
+ }
+
+ /// Product-relative vendor roots (`Library/Application Support/...`, `Library/Caches/...`) owned by each browser channel.
+ public static func vendorRoots(forBundleID bundleID: String) -> [(vendor: String, product: String?)] {
+ let bid = bundleID.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ guard isKnownBrowserBundleID(bid) else { return [] }
+ switch bid {
+ case "com.google.chrome":
+ return [("Google", "Chrome")]
+ case "com.google.chrome.beta":
+ return [("Google", "Chrome Beta")]
+ case "com.google.chrome.canary":
+ return [("Google", "Chrome Canary")]
+ case "com.google.chrome.dev":
+ return [("Google", "Chrome Dev")]
+ case "org.chromium.chromium":
+ return [("Chromium", nil)]
+ case "com.brave.browser":
+ return [("BraveSoftware", "Brave-Browser")]
+ case "com.brave.browser.beta":
+ return [("BraveSoftware", "Brave-Browser-Beta")]
+ case "com.brave.browser.nightly":
+ return [("BraveSoftware", "Brave-Browser-Nightly")]
+ case "com.microsoft.edgemac":
+ return [("Microsoft Edge", nil)]
+ case "com.microsoft.edgemac.beta":
+ return [("Microsoft Edge Beta", nil)]
+ case "com.microsoft.edgemac.canary":
+ return [("Microsoft Edge Canary", nil)]
+ case "com.microsoft.edgemac.dev":
+ return [("Microsoft Edge Dev", nil)]
+ case "org.mozilla.firefox", "org.mozilla.firefoxdeveloperedition", "org.mozilla.nightly":
+ return [("Mozilla", nil), ("Firefox", nil)]
+ case "com.operasoftware.opera":
+ return [("com.operasoftware.Opera", nil), ("Opera Software", "Opera Stable"), ("Opera", nil)]
+ case "com.operasoftware.operagx":
+ return [("com.operasoftware.OperaGX", nil), ("Opera Software", "Opera GX Stable")]
+ case "com.operasoftware.operadeveloperedition":
+ return [("com.operasoftware.OperaDeveloperEdition", nil), ("Opera Software", "Opera Developer")]
+ case "com.vivaldi.vivaldi":
+ return [("Vivaldi", nil)]
+ case "company.thebrowser.browser":
+ return [("Arc", nil)]
+ case "com.kagi.kagimacos":
+ return [("Orion", nil)]
+ case "org.torproject.torbrowser":
+ return [("TorBrowser-Data", nil)]
+ case "com.duckduckgo.macos.browser":
+ return [("DuckDuckGo", nil)]
+ case "net.waterfox.waterfox":
+ return [("Waterfox", nil)]
+ case "io.gitlab.librewolf-community":
+ return [("LibreWolf", nil)]
+ case "net.mullvad.mullvadbrowser":
+ return [("MullvadBrowser", nil)]
+ case "ru.yandex.desktop.yandex-browser":
+ return [("Yandex", "YandexBrowser")]
+ default:
+ return []
+ }
+ }
+
private let browserArtifactDirs: Set = [
"Default", "Profile", "Profiles",
"IndexedDB", "GPUCache", "Code Cache",
@@ -52,12 +131,24 @@ public struct BrowserRule: ApplicationRule {
public init() {}
+ public func matches(identity: AppIdentity) -> Bool {
+ Self.isKnownBrowserBundleID(identity.bundleID)
+ }
+
public func evidence(for candidate: URL, identity: AppIdentity) -> [ArtifactEvidence] {
+ guard matches(identity: identity) else { return [] }
+
let path = candidate.path.lowercased()
let name = candidate.lastPathComponent
+ let bid = identity.bundleID.lowercased()
var evidence: [ArtifactEvidence] = []
- if browserArtifactDirs.contains(name) {
+ let ownedMarkers = Self.ownedPathMarkers(forBundleID: bid, appName: identity.appName)
+ let belongsToThisBrowser = ownedMarkers.contains { marker in
+ path.contains("/\(marker)/") || path.hasSuffix("/\(marker)")
+ }
+
+ if browserArtifactDirs.contains(name), belongsToThisBrowser {
evidence.append(ArtifactEvidence(source: .rule, weight: 40))
}
@@ -69,30 +160,35 @@ public struct BrowserRule: ApplicationRule {
evidence.append(ArtifactEvidence(source: .appName, weight: 50))
}
- let bid = identity.bundleID.lowercased()
- if bid.contains("google") && bid.contains("chrome") {
- if path.contains("/application support/google/") || path.contains("/caches/google/") || path.contains("/logs/google/") {
- if path.contains("/chrome") || name == "Google" {
- evidence.append(ArtifactEvidence(source: .rule, weight: 70))
- }
- }
- if path.contains("/caches/com.google.chrome") {
- evidence.append(ArtifactEvidence(source: .bundleID, weight: 80))
- }
- }
-
- if bid.contains("brave") {
- if path.contains("/bravesoftware/") || path.contains("/caches/com.brave.") {
+ for (vendor, product) in Self.vendorRoots(forBundleID: bid) {
+ let marker = product.map { "\(vendor)/\($0)".lowercased() } ?? vendor.lowercased()
+ let appSupportMarker = "/application support/\(marker)"
+ let cachesMarker = "/caches/\(marker)"
+ let logsMarker = "/logs/\(marker)"
+ if path.contains(appSupportMarker + "/") || path.hasSuffix(appSupportMarker)
+ || path.contains(cachesMarker + "/") || path.hasSuffix(cachesMarker)
+ || path.contains(logsMarker + "/") || path.hasSuffix(logsMarker) {
evidence.append(ArtifactEvidence(source: .rule, weight: 70))
+ break
}
}
- if bid.contains("operasoftware") || bid.contains("vivaldi") || bid.contains("edgemac") {
- if path.contains(bid) || path.contains("/\(identity.appName.lowercased())") {
- evidence.append(ArtifactEvidence(source: .bundleID, weight: 70))
- }
+ if path.contains("/caches/\(bid)/") || path.hasSuffix("/caches/\(bid)") {
+ evidence.append(ArtifactEvidence(source: .bundleID, weight: 80))
}
return evidence
}
+
+ private static func ownedPathMarkers(forBundleID bid: String, appName: String) -> [String] {
+ var markers: [String] = [bid, appName.lowercased()].filter { !$0.isEmpty }
+ for (vendor, product) in vendorRoots(forBundleID: bid) {
+ if let product {
+ markers.append("\(vendor)/\(product)".lowercased())
+ } else {
+ markers.append(vendor.lowercased())
+ }
+ }
+ return markers
+ }
}
diff --git a/MacOSCleaner/Features/Uninstaller/UninstallerService.swift b/MacOSCleaner/Features/Uninstaller/UninstallerService.swift
index 4b72e79..65766d3 100644
--- a/MacOSCleaner/Features/Uninstaller/UninstallerService.swift
+++ b/MacOSCleaner/Features/Uninstaller/UninstallerService.swift
@@ -23,20 +23,32 @@ public actor UninstallerService {
private let safetyManager: SafetyManager
private let trashManager: TrashManager
private let commandRunner: CommandRunner
+ private let fileSystemContext: FileSystemContext
+ private let appDiscovery: AppDiscovery
private let codesignCache = CodesignCache()
private let plistCache = PlistContentCache()
private let ruleRegistry: ApplicationRuleRegistry
public init(
fileManager: FileManager = .default,
- safetyManager: SafetyManager = SafetyManager(),
- trashManager: TrashManager = TrashManager(),
- commandRunner: CommandRunner = CommandRunner()
+ safetyManager: SafetyManager? = nil,
+ trashManager: TrashManager? = nil,
+ commandRunner: CommandRunner = CommandRunner(),
+ fileSystemContext: FileSystemContext = .production,
+ appDiscovery: AppDiscovery? = nil
) {
self.fileManager = fileManager
- self.safetyManager = safetyManager
- self.trashManager = trashManager
+ self.fileSystemContext = fileSystemContext
+ let resolvedSafety = safetyManager ?? SafetyManager(
+ homeDirectory: fileSystemContext.homePath,
+ fileSystemContext: fileSystemContext
+ )
+ self.safetyManager = resolvedSafety
+ self.trashManager = trashManager ?? TrashManager(
+ safetyManager: resolvedSafety
+ )
self.commandRunner = commandRunner
+ self.appDiscovery = appDiscovery ?? AppDiscovery(commandRunner: commandRunner)
self.ruleRegistry = ApplicationRuleRegistry.createDefault()
}
@@ -86,14 +98,24 @@ public actor UninstallerService {
public let deletionRisk: DeletionRisk
public let evidence: Set
public let confidence: ConfidenceTier
+ public let isBrowserData: Bool
- public init(url: URL, isSelected: Bool = true, size: Int64 = 0, deletionRisk: DeletionRisk = .normal, evidence: Set = [], confidence: ConfidenceTier = .possible) {
+ public init(
+ url: URL,
+ isSelected: Bool = true,
+ size: Int64 = 0,
+ deletionRisk: DeletionRisk = .normal,
+ evidence: Set = [],
+ confidence: ConfidenceTier = .possible,
+ isBrowserData: Bool = false
+ ) {
self.url = NormalizedPath.url(url)
self.isSelected = isSelected
self.size = size
self.deletionRisk = deletionRisk
self.evidence = evidence
self.confidence = confidence
+ self.isBrowserData = isBrowserData
}
public func hash(into hasher: inout Hasher) { hasher.combine(id) }
@@ -129,7 +151,6 @@ public actor UninstallerService {
public var size: Int64 = 0
public var version: String = ""
public var lastUsed: Date? = nil
- public var iconData: Data? = nil
public var isIntelOnly: Bool = false
/// Multiple versions of the same app grouped together.
public var versions: [AppInfo] = []
@@ -147,7 +168,6 @@ public actor UninstallerService {
size: Int64 = 0,
version: String = "",
lastUsed: Date? = nil,
- iconData: Data? = nil,
isIntelOnly: Bool = false,
versions: [AppInfo] = []
) {
@@ -163,7 +183,6 @@ public actor UninstallerService {
self.size = size
self.version = version
self.lastUsed = lastUsed
- self.iconData = iconData
self.isIntelOnly = isIntelOnly
self.versions = versions
}
@@ -197,10 +216,11 @@ public actor UninstallerService {
// MARK: - Scan All Applications (Discovery only)
+ public static let maxConcurrentDiscoveryTasks = 6
+
public func scanAllApplications() async throws -> [AppInfo] {
- let discovery = AppDiscovery(commandRunner: commandRunner)
// Keep distinct bundle URLs separate even when bundle IDs collide.
- let listable = uniqueApplicationURLs(await discovery.findAll())
+ let listable = uniqueApplicationURLs(await appDiscovery.findAll())
.filter { AppDiscovery.isListableApplication($0) }
// Progress denominator ≈ final sidebar (helpers indexed but not counted).
let primaryCount = listable.filter { !HelperAppCollapser.isLikelyHelperURL($0) }.count
@@ -212,54 +232,76 @@ public actor UninstallerService {
progress.percentage = 0.0
}
- return try await withThrowingTaskGroup(of: AppInfo?.self) { group in
- for url in listable {
- group.addTask {
- do {
- let app = try await self.discoverAndIndex(url)
- let countsTowardProgress = !HelperAppCollapser.isLikelyHelperURL(url)
- await MainActor.run {
- if countsTowardProgress {
- self.progress.currentStep += 1
- self.progress.percentage = Double(self.progress.currentStep)
- / Double(self.progress.totalSteps)
- }
- }
- return app
- } catch {
- Logger.uninstaller.warning(
- "Skip '\(url.lastPathComponent, privacy: .public)': \(error.localizedDescription, privacy: .public)"
- )
- let countsTowardProgress = !HelperAppCollapser.isLikelyHelperURL(url)
- await MainActor.run {
- if countsTowardProgress {
- self.progress.currentStep += 1
- self.progress.percentage = Double(self.progress.currentStep)
- / Double(self.progress.totalSteps)
- }
- }
- return nil
+ let results: [AppInfo?] = try await Self.mapWithBoundedConcurrency(
+ items: listable,
+ maxConcurrent: Self.maxConcurrentDiscoveryTasks
+ ) { url -> AppInfo? in
+ do {
+ let app = try await self.discoverAndIndex(url)
+ let countsTowardProgress = !HelperAppCollapser.isLikelyHelperURL(url)
+ await MainActor.run {
+ if countsTowardProgress {
+ self.progress.currentStep += 1
+ self.progress.percentage = Double(self.progress.currentStep)
+ / Double(self.progress.totalSteps)
+ }
+ }
+ return app
+ } catch {
+ Logger.uninstaller.warning(
+ "Skip '\(url.lastPathComponent, privacy: .public)': \(error.localizedDescription, privacy: .public)"
+ )
+ let countsTowardProgress = !HelperAppCollapser.isLikelyHelperURL(url)
+ await MainActor.run {
+ if countsTowardProgress {
+ self.progress.currentStep += 1
+ self.progress.percentage = Double(self.progress.currentStep)
+ / Double(self.progress.totalSteps)
}
}
+ return nil
}
+ }
- var apps: [AppInfo] = []
- for try await app in group {
- if let app = app { apps.append(app) }
- }
+ let apps = results.compactMap { $0 }
+ let merged = mergeApps(apps)
+ let collapsed = HelperAppCollapser.collapse(merged).apps
- let merged = mergeApps(apps)
- let collapsed = HelperAppCollapser.collapse(merged).apps
+ await MainActor.run {
+ // Align counter with what the UI actually lists.
+ progress.totalSteps = max(collapsed.count, 1)
+ progress.currentStep = collapsed.count
+ progress.message = "uninstaller.progress.complete".localized
+ progress.percentage = 1.0
+ }
- await MainActor.run {
- // Align counter with what the UI actually lists.
- progress.totalSteps = max(collapsed.count, 1)
- progress.currentStep = collapsed.count
- progress.message = "uninstaller.progress.complete".localized
- progress.percentage = 1.0
+ return collapsed.sorted { $0.name.localizedCompare($1.name) == .orderedAscending }
+ }
+
+ static func mapWithBoundedConcurrency(
+ items: [Item],
+ maxConcurrent: Int = maxConcurrentDiscoveryTasks,
+ operation: @Sendable @escaping (Item) async throws -> Output
+ ) async throws -> [Output] {
+ guard !items.isEmpty else { return [] }
+ let limit = max(1, maxConcurrent)
+ return try await withThrowingTaskGroup(of: Output.self) { group in
+ var iterator = items.makeIterator()
+ for _ in 0.. AppInfo {
+ nonisolated private func discoverAndIndex(_ url: URL) async throws -> AppInfo {
try safetyManager.validate(url: url, policy: .uninstall)
let identity = await AppIdentity.resolve(from: url, commandRunner: commandRunner)
let size = await getDirectorySize(url: url)
- let iconData = await MainActor.run {
- NSWorkspace.shared.icon(forFile: url.path).tiffRepresentation
- }
- let mdItem = MDItemCreate(nil, url.path as CFString)
- let lastUsed = MDItemCopyAttribute(mdItem, kMDItemLastUsedDate) as? Date
+ let lastUsed = SpotlightMetadata.lastUsedDate(for: url)
let isIntelOnly = Self.isIntelOnlyApp(at: url)
@@ -293,18 +331,28 @@ public actor UninstallerService {
size: size,
version: version(from: url),
lastUsed: lastUsed,
- iconData: iconData,
isIntelOnly: isIntelOnly
)
}
// MARK: - Deep Forensics
- public func deepScan(_ app: AppInfo, mode: ScanMode = .balanced) async throws -> AppInfo {
+ public nonisolated func buildResidualScanIndex() async -> ResidualScanIndex {
+ await ResidualScanIndex.build(
+ fileSystemContext: fileSystemContext,
+ commandRunner: commandRunner
+ )
+ }
+
+ public nonisolated func deepScan(
+ _ app: AppInfo,
+ mode: ScanMode = .balanced,
+ scanIndex: ResidualScanIndex? = nil
+ ) async throws -> AppInfo {
if !app.versions.isEmpty {
var scannedVersions: [AppInfo] = []
for versionApp in app.versions {
- let scanned = try await deepScanSingle(versionApp, mode: mode)
+ let scanned = try await deepScanSingle(versionApp, mode: mode, scanIndex: scanIndex)
scannedVersions.append(scanned)
}
scannedVersions.sort { preferredApp($0, $1) == $0 }
@@ -318,7 +366,6 @@ public actor UninstallerService {
updated.url = primary.url
updated.version = versionSummary
updated.lastUsed = scannedVersions.compactMap(\.lastUsed).max()
- updated.iconData = primary.iconData ?? app.iconData
updated.relatedFiles = aggregateRelatedFiles(from: scannedVersions)
updated.developerComponents = aggregateDeveloperComponents(from: scannedVersions)
updated.absorbedHelperURLs = NormalizedPath.unique(scannedVersions.flatMap(\.absorbedHelperURLs))
@@ -326,11 +373,15 @@ public actor UninstallerService {
updated.scanState = .deepScanned
return updated
} else {
- return try await deepScanSingle(app, mode: mode)
+ return try await deepScanSingle(app, mode: mode, scanIndex: scanIndex)
}
}
- private func deepScanSingle(_ app: AppInfo, mode: ScanMode = .balanced) async throws -> AppInfo {
+ nonisolated private func deepScanSingle(
+ _ app: AppInfo,
+ mode: ScanMode = .balanced,
+ scanIndex: ResidualScanIndex? = nil
+ ) async throws -> AppInfo {
let identity: AppIdentity
if let existing = app.identity {
identity = existing
@@ -344,7 +395,12 @@ public actor UninstallerService {
let graph = EvidenceGraph(identity: identity)
- async let relatedTask: [RelatedFile] = runDeepRelatedFiles(identity: identity, graph: graph, mode: mode)
+ async let relatedTask: [RelatedFile] = runDeepRelatedFiles(
+ identity: identity,
+ graph: graph,
+ mode: mode,
+ scanIndex: scanIndex
+ )
async let developerTask: [RelatedCleanupComponent] = DeveloperComponentsDetector.detect(
appName: identity.appName,
bundleID: identity.bundleID
@@ -378,21 +434,23 @@ public actor UninstallerService {
}
}
- private func attachAbsorbedHelpers(
+ nonisolated private func attachAbsorbedHelpers(
_ related: [RelatedFile],
helperURLs: [URL],
parentBundlePath: String
) async -> [RelatedFile] {
guard !helperURLs.isEmpty else { return related }
+ let fm = FileManager.default
var existing = Set(related.map { NormalizedPath.key($0.url) })
var result = related
for url in helperURLs {
let standardized = NormalizedPath.canonicalize(url)
let path = NormalizedPath.key(standardized)
if path.hasPrefix(parentBundlePath + "/") { continue }
+ if safetyManager.isBrowserUserDataPath(path) { continue }
guard existing.insert(path).inserted else { continue }
var isDir: ObjCBool = false
- guard fileManager.fileExists(atPath: path, isDirectory: &isDir) else { continue }
+ guard fm.fileExists(atPath: path, isDirectory: &isDir) else { continue }
let fileSize = await getDirectorySize(url: standardized)
result.append(RelatedFile(
url: standardized,
@@ -406,8 +464,19 @@ public actor UninstallerService {
return dedupAndSort(result.map { ($0, $0.confidence) })
}
- private func runDeepRelatedFiles(identity: AppIdentity, graph: EvidenceGraph, mode: ScanMode = .balanced) async -> [RelatedFile] {
- let collector = CandidateCollector(commandRunner: commandRunner)
+ nonisolated private func runDeepRelatedFiles(
+ identity: AppIdentity,
+ graph: EvidenceGraph,
+ mode: ScanMode = .balanced,
+ scanIndex: ResidualScanIndex? = nil
+ ) async -> [RelatedFile] {
+ let fm = FileManager.default
+ let collector = CandidateCollector(
+ commandRunner: commandRunner,
+ fileSystemContext: fileSystemContext,
+ safetyManager: safetyManager,
+ scanIndex: scanIndex
+ )
let collection = await collector.collectDetailed(identity: identity, mode: mode)
let probe = EvidenceProbe(commandRunner: commandRunner, codesignCache: codesignCache, plistCache: plistCache)
@@ -447,37 +516,52 @@ public actor UninstallerService {
let ruleScore = rule.evidence(for: node.url, identity: identity).reduce(0) { $0 + $1.weight }
let assessment = ConfidenceEngine.assess(node.evidence, ruleScore: ruleScore, identity: identity)
guard assessment.tier >= minimumTier else { continue }
- guard (try? safetyManager.validate(url: node.url, policy: .uninstall)) != nil else { continue }
- guard !Self.isProtectedMailPath(node.url.path) else { continue }
+ guard (try? safetyManager.validate(url: node.url, policy: .uninstallApp(bundleID: identity.bundleID))) != nil else { continue }
+ guard !Self.isProtectedMailPath(node.url.path, homeDirectory: fileSystemContext.homePath) else { continue }
guard node.url.path != identity.bundleURL.path else { continue }
guard !identity.bundleURL.path.hasPrefix(node.url.path + "/") else { continue }
guard !node.url.path.hasPrefix(identity.bundleURL.path + "/") else { continue }
var isDir: ObjCBool = false
- guard fileManager.fileExists(atPath: node.url.path, isDirectory: &isDir) else { continue }
+ guard fm.fileExists(atPath: node.url.path, isDirectory: &isDir) else { continue }
- let fileSize = await getDirectorySize(url: node.url)
- // Browser user data carries logins/sessions — never label it "safe".
- let risk: DeletionRisk = (node.url.path.contains("Preferences") || safetyManager.isBrowserUserDataPath(node.url.path))
+ // Browser user data carries logins/sessions/extensions — never preselect or label "safe".
+ let isBrowserData = safetyManager.isBrowserUserDataPath(node.url.path)
+ let risk: DeletionRisk = (node.url.path.contains("Preferences") || isBrowserData)
? .normal : .safe
let isConfig = Self.isApplicationConfigurationPath(node.url.path)
- let isSelectedByDefault = isConfig ? false : (assessment.tier >= .veryLikely)
+ let isSelectedByDefault = (isConfig || isBrowserData) ? false : (assessment.tier >= .veryLikely)
let file = RelatedFile(
url: node.url,
- // App configuration/settings are optional (unselected by default); others preselected if veryLikely+
+ // App configuration/settings and browser user data are opt-in only.
isSelected: isSelectedByDefault,
- size: fileSize,
+ size: 0,
deletionRisk: isConfig ? .normal : risk,
evidence: assessment.evidence,
- confidence: assessment.tier
+ confidence: assessment.tier,
+ isBrowserData: isBrowserData
)
related.append((file, assessment.tier))
}
- // Dedup by prefix, sort by tier then path
- var result = dedupAndSort(related)
+ // Collapse covered descendants before paying directory-size I/O.
+ let collapsed = dedupAndSort(related)
+ var result: [RelatedFile] = []
+ result.reserveCapacity(collapsed.count)
+ for file in collapsed {
+ let fileSize = await getDirectorySize(url: file.url)
+ result.append(RelatedFile(
+ url: file.url,
+ isSelected: file.isSelected,
+ size: fileSize,
+ deletionRisk: file.deletionRisk,
+ evidence: file.evidence,
+ confidence: file.confidence,
+ isBrowserData: file.isBrowserData
+ ))
+ }
let sharedSet = Set(collection.sharedPaths.map(NormalizedPath.key))
let informationalSet = Set(collection.informationalPaths.map(NormalizedPath.key))
@@ -505,7 +589,8 @@ public actor UninstallerService {
size: file.size,
deletionRisk: .shared,
evidence: file.evidence,
- confidence: file.confidence
+ confidence: file.confidence,
+ isBrowserData: file.isBrowserData
)
}
if informationalSet.contains(path) {
@@ -515,7 +600,8 @@ public actor UninstallerService {
size: file.size,
deletionRisk: .normal,
evidence: file.evidence,
- confidence: file.confidence
+ confidence: file.confidence,
+ isBrowserData: file.isBrowserData
)
}
if Self.isCLIConfigPath(file.url) {
@@ -525,7 +611,8 @@ public actor UninstallerService {
size: file.size,
deletionRisk: .shared,
evidence: file.evidence,
- confidence: file.confidence
+ confidence: file.confidence,
+ isBrowserData: file.isBrowserData
)
}
return file
@@ -540,7 +627,7 @@ public actor UninstallerService {
continue // SSOT is developerComponents / unlocked related above
}
var isDir: ObjCBool = false
- guard fileManager.fileExists(atPath: standardized.path, isDirectory: &isDir) else { continue }
+ guard fm.fileExists(atPath: standardized.path, isDirectory: &isDir) else { continue }
let fileSize = await getDirectorySize(url: standardized)
result.append(RelatedFile(
url: standardized,
@@ -548,7 +635,8 @@ public actor UninstallerService {
size: fileSize,
deletionRisk: .shared,
evidence: [],
- confidence: .guaranteed
+ confidence: .guaranteed,
+ isBrowserData: safetyManager.isBrowserUserDataPath(standardized.path)
))
}
@@ -557,7 +645,7 @@ public actor UninstallerService {
let standardized = NormalizedPath.canonicalize(url)
guard existing.insert(NormalizedPath.key(standardized)).inserted else { continue }
var isDir: ObjCBool = false
- guard fileManager.fileExists(atPath: standardized.path, isDirectory: &isDir) else { continue }
+ guard fm.fileExists(atPath: standardized.path, isDirectory: &isDir) else { continue }
let fileSize = await getDirectorySize(url: standardized)
result.append(RelatedFile(
url: standardized,
@@ -565,7 +653,8 @@ public actor UninstallerService {
size: fileSize,
deletionRisk: .normal,
evidence: [],
- confidence: .guaranteed
+ confidence: .guaranteed,
+ isBrowserData: safetyManager.isBrowserUserDataPath(standardized.path)
))
}
@@ -590,9 +679,11 @@ public actor UninstallerService {
let scanner = OrphanScanner(
safetyManager: safetyManager,
commandRunner: commandRunner,
+ fileSystemContext: fileSystemContext,
codesignCache: codesignCache,
plistCache: plistCache,
- ruleRegistry: ruleRegistry
+ ruleRegistry: ruleRegistry,
+ appDiscovery: appDiscovery
)
return try await scanner.scanOrphans(progress: progress)
}
@@ -622,12 +713,19 @@ public actor UninstallerService {
}
private func terminateRunningApp(_ app: AppInfo) async {
+ guard !AppQuitter.isRunningUnderTests else { return }
let appBundleURL = app.url.standardizedFileURL
let bundleID = app.bundleID?.trimmingCharacters(in: .whitespacesAndNewlines)
+ let context = fileSystemContext
let runningApps = await MainActor.run {
NSWorkspace.shared.runningApplications.filter { running in
if running.processIdentifier == ProcessInfo.processInfo.processIdentifier { return false }
+ if context.enforceAllowedRoots,
+ let runningURL = running.bundleURL,
+ !context.isInsideAllowedRoots(runningURL) {
+ return false
+ }
if let bundleID, !bundleID.isEmpty, running.bundleIdentifier == bundleID {
return true
}
@@ -801,10 +899,11 @@ public actor UninstallerService {
var failedDeletions: [FailedDeletion] = []
let allTargets = [app.url] + deletionTargets
+ let uninstallPolicy = DeletionPolicy.uninstallApp(bundleID: app.bundleID)
if bypassTrash {
for target in allTargets {
do {
- try safetyManager.validate(url: target, policy: .uninstall)
+ try safetyManager.validate(url: target, policy: uninstallPolicy)
try fileManager.removeItem(at: target)
Logger.uninstaller.debug("Removed: \(target.path, privacy: .public)")
} catch {
@@ -818,8 +917,8 @@ public actor UninstallerService {
}
}
} else {
- trashedURLs = try await trashManager.trashItems(urls: allTargets, policy: .uninstall)
- for target in deletionTargets where fileManager.fileExists(atPath: target.path) {
+ trashedURLs = try await trashManager.trashItems(urls: allTargets, policy: uninstallPolicy)
+ for target in allTargets where fileManager.fileExists(atPath: target.path) {
failedDeletions.append(FailedDeletion(url: target, reason: "cleanup_skip_reason_permission".localized))
}
Logger.uninstaller.info("Trashed \(trashedURLs.count) item(s) for '\(app.name, privacy: .public)'")
@@ -829,7 +928,7 @@ public actor UninstallerService {
await DockTileManager.removeFromDock(appURL: app.url, bundleID: app.bundleID, commandRunner: commandRunner)
}
- if let bundleID = app.bundleID {
+ if !AppQuitter.isRunningUnderTests, let bundleID = app.bundleID {
do {
_ = try await commandRunner.run(command: "/usr/sbin/pkgutil", arguments: ["--forget", bundleID])
Logger.uninstaller.debug("pkgutil --forget \(bundleID, privacy: .public)")
@@ -851,14 +950,23 @@ public actor UninstallerService {
Logger.uninstaller.info("Uninstall complete: '\(app.name, privacy: .public)'")
- // Verification
+ // Verification — exclude files the user explicitly left unchecked (e.g. browser profiles).
+ let intentionallyKeptPaths = Set(
+ app.relatedFiles
+ .filter { !$0.isSelected }
+ .map { NormalizedPath.lowercaseKey($0.url.path) }
+ )
if let identity = app.identity {
let engine = VerificationEngine(
commandRunner: commandRunner,
codesignCache: codesignCache,
- plistCache: plistCache
+ plistCache: plistCache,
+ fileSystemContext: fileSystemContext,
+ safetyManager: safetyManager
)
- let report = await engine.verify(identity: identity).withFailedDeletions(failedDeletions)
+ let report = await engine
+ .verify(identity: identity, excludedPaths: intentionallyKeptPaths)
+ .withFailedDeletions(failedDeletions)
if report.hasLeftovers {
Logger.uninstaller.warning("\(report.count, privacy: .public) leftover(s) after uninstall of '\(app.name, privacy: .public)'")
} else {
@@ -901,7 +1009,7 @@ public actor UninstallerService {
return false
}
- private func version(from url: URL) -> String {
+ nonisolated private func version(from url: URL) -> String {
Bundle(url: url)?.infoDictionary?["CFBundleShortVersionString"] as? String
?? Bundle(url: url)?.infoDictionary?["CFBundleVersion"] as? String
?? "version_unknown".localized
@@ -909,8 +1017,8 @@ public actor UninstallerService {
/// Physical size: what deleting the item actually frees. Sparse VM images
/// (OrbStack data.img.raw) report tens of GB here, not their logical 500 GB.
- private func getDirectorySize(url: URL) async -> Int64 {
- fileManager.getPhysicalDirectorySize(url: url, excludedPaths: [])
+ nonisolated private func getDirectorySize(url: URL) async -> Int64 {
+ FileManager.default.getPhysicalDirectorySize(url: url, excludedPaths: [])
}
public static func groupKey(for app: AppInfo) -> String {
@@ -922,12 +1030,12 @@ public actor UninstallerService {
return "name:" + app.name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
}
- private func aggregateRelatedFiles(from versions: [AppInfo]) -> [RelatedFile] {
+ nonisolated private func aggregateRelatedFiles(from versions: [AppInfo]) -> [RelatedFile] {
let allRelated = versions.flatMap(\.relatedFiles)
return dedupAndSort(allRelated.map { ($0, $0.confidence) })
}
- private func aggregateDeveloperComponents(from versions: [AppInfo]) -> [RelatedCleanupComponent] {
+ nonisolated private func aggregateDeveloperComponents(from versions: [AppInfo]) -> [RelatedCleanupComponent] {
var seen = Set()
var result: [RelatedCleanupComponent] = []
for v in versions {
@@ -983,7 +1091,6 @@ public actor UninstallerService {
size: sortedVersions.reduce(0) { $0 + $1.size },
version: versionSummary,
lastUsed: latestLastUsed,
- iconData: sortedVersions.compactMap(\.iconData).first,
isIntelOnly: primary.isIntelOnly,
versions: sortedVersions
)
@@ -993,7 +1100,7 @@ public actor UninstallerService {
return result
}
- private func preferredApp(_ lhs: AppInfo, _ rhs: AppInfo) -> AppInfo {
+ nonisolated private func preferredApp(_ lhs: AppInfo, _ rhs: AppInfo) -> AppInfo {
let lhsIsStandard = lhs.url.path.hasPrefix("/Applications/")
let rhsIsStandard = rhs.url.path.hasPrefix("/Applications/")
if lhsIsStandard != rhsIsStandard {
@@ -1007,7 +1114,7 @@ public actor UninstallerService {
return lhs.url.path <= rhs.url.path ? lhs : rhs
}
- private func dedupAndSort(_ items: [(file: RelatedFile, tier: ConfidenceTier)]) -> [RelatedFile] {
+ nonisolated private func dedupAndSort(_ items: [(file: RelatedFile, tier: ConfidenceTier)]) -> [RelatedFile] {
let sortedByPath = items.map(\.file).sorted { $0.url.path.count < $1.url.path.count }
var deduplicated: [String: RelatedFile] = [:]
for file in sortedByPath {
@@ -1022,22 +1129,24 @@ public actor UninstallerService {
if let existing = deduplicated[pathKey] {
deduplicated[pathKey] = RelatedFile(
url: NormalizedPath.canonicalize(file.url),
- isSelected: existing.isSelected || file.isSelected,
+ isSelected: (existing.isBrowserData || file.isBrowserData) ? false : (existing.isSelected || file.isSelected),
size: max(existing.size, file.size),
deletionRisk: existing.deletionRisk == .shared || file.deletionRisk == .shared
? .shared
: (existing.deletionRisk == .normal || file.deletionRisk == .normal ? .normal : existing.deletionRisk),
evidence: existing.evidence.union(file.evidence),
- confidence: max(existing.confidence, file.confidence)
+ confidence: max(existing.confidence, file.confidence),
+ isBrowserData: existing.isBrowserData || file.isBrowserData
)
} else {
deduplicated[pathKey] = RelatedFile(
url: NormalizedPath.canonicalize(file.url),
- isSelected: file.isSelected,
+ isSelected: file.isBrowserData ? false : file.isSelected,
size: file.size,
deletionRisk: file.deletionRisk,
evidence: file.evidence,
- confidence: file.confidence
+ confidence: file.confidence,
+ isBrowserData: file.isBrowserData
)
}
}
@@ -1072,4 +1181,27 @@ public actor UninstallerService {
let name = url.lastPathComponent.lowercased()
return sharedCLIConfigNames.contains(name)
}
+
+ /// True when any removed path belongs to system-wide daemons, kernel/system extensions,
+ /// privileged helpers, or hardware plug-ins that stay resident until reboot.
+ public static func requiresRestartForRemovedPaths(_ urls: [URL]) -> Bool {
+ let systemComponentPrefixes = [
+ "/library/launchdaemons/",
+ "/library/systemextensions/",
+ "/library/extensions/",
+ "/library/privilegedhelpertools/",
+ "/library/audio/plug-ins/",
+ "/library/coremediaio/plug-ins/",
+ "/library/filesystems/",
+ "/library/security/securityagentplugins/"
+ ]
+ return urls.contains { url in
+ let normalized = NormalizedPath.lowercaseKey(url.path)
+ if systemComponentPrefixes.contains(where: { normalized.hasPrefix($0) }) {
+ return true
+ }
+ let ext = url.pathExtension.lowercased()
+ return ext == "kext" || ext == "systemextension"
+ }
+ }
}
diff --git a/MacOSCleaner/Features/Uninstaller/UninstallerView.swift b/MacOSCleaner/Features/Uninstaller/UninstallerView.swift
index 057ee76..d96d6d5 100644
--- a/MacOSCleaner/Features/Uninstaller/UninstallerView.swift
+++ b/MacOSCleaner/Features/Uninstaller/UninstallerView.swift
@@ -30,50 +30,36 @@ enum UninstallerTab: String, CaseIterable, Identifiable {
struct UninstallerView: View {
let settings: AppSettings
+ @Bindable var viewModel: UninstallerViewModel
let navigateToCleanup: () -> Void
var navigateToPrivacy: ((String?) -> Void)? = nil
var scanLimited: Bool = false
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
- @State private var service = UninstallerService()
- @State private var selectedTab: UninstallerTab = .applications
- @State private var allApps: [UninstallerService.AppInfo] = []
- @State private var selectedApp: UninstallerService.AppInfo?
- @State private var searchText = ""
@State private var isTargeted = false
@State private var showingConfirmation = false
- @State private var isLoading = false
- @State private var isUninstalling = false
- @State private var uninstallingAppName = ""
- @State private var deepScanCache: [String: UninstallerService.AppInfo] = [:]
- @State private var isDeepScanning = false
- @State private var deepScanCompleted = 0
- @State private var deepScanTotal = 0
- @State private var scanTask: Task? = nil
- @State private var expandedConfidenceTiers: Set = [.guaranteed, .veryLikely, .possible]
@State private var versionToUninstall: UninstallerService.AppInfo?
@State private var showingVersionConfirmation = false
- @State private var selectedVersionID: UUID? = nil
- @State private var postUninstallReport: VerificationReport? = nil
- @State private var showingPostUninstallSheet = false
- private func sameAppURL(_ lhs: URL, _ rhs: URL) -> Bool {
- NormalizedPath.key(lhs) == NormalizedPath.key(rhs)
+ init(
+ settings: AppSettings,
+ viewModel: UninstallerViewModel = UninstallerViewModel(),
+ navigateToCleanup: @escaping () -> Void,
+ navigateToPrivacy: ((String?) -> Void)? = nil,
+ scanLimited: Bool = false
+ ) {
+ self.settings = settings
+ self.viewModel = viewModel
+ self.navigateToCleanup = navigateToCleanup
+ self.navigateToPrivacy = navigateToPrivacy
+ self.scanLimited = scanLimited
}
-
+
private var formatter: ByteCountFormatter {
let f = ByteCountFormatter.makeLocalized(countStyle: .file)
f.allowedUnits = [.useAll]
return f
}
- var filteredApps: [UninstallerService.AppInfo] {
- if searchText.isEmpty {
- return allApps
- } else {
- return allApps.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
- }
- }
-
var body: some View {
GlassEffectContainer {
VStack(spacing: 0) {
@@ -89,22 +75,33 @@ struct UninstallerView: View {
.padding(.horizontal, 16)
.padding(.vertical, 8)
}
- if selectedTab == .applications {
+ if !viewModel.isSpotlightAvailable {
+ Label("uninstaller_spotlight_disabled".localized, systemImage: "magnifyingglass.circle")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 16)
+ .padding(.vertical, 6)
+ }
+ if viewModel.showingRestartBanner {
+ uninstallerRestartBanner
+ }
+ if viewModel.selectedTab == .applications {
applicationsContentView
} else {
- OrphanedResidualsView(service: service, settings: settings)
+ OrphanedResidualsView(viewModel: viewModel, settings: settings)
}
}
}
- .sheet(isPresented: $showingPostUninstallSheet) {
+ .sheet(isPresented: $viewModel.showingPostUninstallSheet) {
PostUninstallLeftoversSheet(
- report: $postUninstallReport,
+ report: $viewModel.postUninstallReport,
onClean: { selectedItems in
- cleanPostUninstallLeftovers(selectedItems)
+ viewModel.cleanPostUninstallLeftovers(selectedItems, settings: settings)
},
onDismiss: {
- showingPostUninstallSheet = false
- postUninstallReport = nil
+ viewModel.showingPostUninstallSheet = false
+ viewModel.postUninstallReport = nil
}
)
}
@@ -112,19 +109,7 @@ struct UninstallerView: View {
if settings.enableAI {
AIExplanationService.shared.prewarm()
}
- if allApps.isEmpty {
- loadApps()
- }
- }
- .onDisappear {
- scanTask?.cancel()
- }
- .onChange(of: selectedApp?.id) { _, newID in
- guard let id = newID else { return }
- guard let app = allApps.first(where: { $0.id == id }) else { return }
- if app.scanState != .deepScanned {
- selectedApp = nil
- }
+ viewModel.loadAppsIfNeeded(mode: settings.uninstallerScanMode)
}
.confirmationDialog(
settings.bypassTrashOnUninstall
@@ -139,20 +124,24 @@ struct UninstallerView: View {
: "uninstaller_move_trash".localized,
role: .destructive
) {
- if let app = selectedApp {
- uninstall(app)
+ if let app = viewModel.selectedApp {
+ viewModel.uninstall(app, settings: settings)
}
}
Button("cancel".localized, role: .cancel) { }
} message: {
- if let app = selectedApp {
+ if let app = viewModel.selectedApp {
let count = app.relatedFiles.filter(\.isSelected).count + app.developerComponents.filter(\.isSelected).count
let sizeToReclaim = settings.showRelatedFiles ? app.totalSize : app.size
let formattedSize = ByteCountFormatter.localizedString(fromByteCount: sizeToReclaim, countStyle: .file)
- if settings.bypassTrashOnUninstall {
- Text(String(format: "uninstaller_uninstall_app_warning_perm".localized, app.name, Int64(count)) + " (\(formattedSize))")
+ let baseWarning = settings.bypassTrashOnUninstall
+ ? String(format: "uninstaller_uninstall_app_warning_perm".localized, app.name, Int64(count)) + " (\(formattedSize))"
+ : String(format: "uninstaller_uninstall_app_warning_trash".localized, app.name, Int64(count))
+ let hasSelectedBrowserData = app.relatedFiles.contains { $0.isSelected && $0.isBrowserData }
+ if hasSelectedBrowserData {
+ Text(baseWarning + "\n\n" + "uninstaller_browser_data_confirm_warning".localized)
} else {
- Text(String(format: "uninstaller_uninstall_app_warning_trash".localized, app.name, Int64(count)))
+ Text(baseWarning)
}
}
}
@@ -169,30 +158,84 @@ struct UninstallerView: View {
: "uninstaller_move_trash".localized,
role: .destructive
) {
- if let versionApp = versionToUninstall, let parentApp = selectedApp {
- uninstallVersion(versionApp, from: parentApp)
+ if let versionApp = versionToUninstall, let parentApp = viewModel.selectedApp {
+ viewModel.uninstallVersion(versionApp, from: parentApp, settings: settings)
}
}
Button("cancel".localized, role: .cancel) { }
} message: {
- if let versionApp = versionToUninstall, let parentApp = selectedApp {
+ if let versionApp = versionToUninstall, let parentApp = viewModel.selectedApp {
let count = versionApp.relatedFiles.filter(\.isSelected).count + versionApp.developerComponents.filter(\.isSelected).count
let sizeToReclaim = settings.showRelatedFiles ? versionApp.totalSize : versionApp.size
let formattedSize = ByteCountFormatter.localizedString(fromByteCount: sizeToReclaim, countStyle: .file)
- if settings.bypassTrashOnUninstall {
- Text(String(format: "uninstaller_uninstall_version_warning_perm".localized, versionApp.version, parentApp.name, Int64(count)) + " (\(formattedSize))")
+ let baseWarning = settings.bypassTrashOnUninstall
+ ? String(format: "uninstaller_uninstall_version_warning_perm".localized, versionApp.version, parentApp.name, Int64(count)) + " (\(formattedSize))"
+ : String(format: "uninstaller_uninstall_version_warning_trash".localized, versionApp.version, parentApp.name, Int64(count))
+ let hasSelectedBrowserData = versionApp.relatedFiles.contains { $0.isSelected && $0.isBrowserData }
+ if hasSelectedBrowserData {
+ Text(baseWarning + "\n\n" + "uninstaller_browser_data_confirm_warning".localized)
} else {
- Text(String(format: "uninstaller_uninstall_version_warning_trash".localized, versionApp.version, parentApp.name, Int64(count)))
+ Text(baseWarning)
}
}
}
+ .alert("error".localized, isPresented: $viewModel.showingUninstallErrorAlert) {
+ Button("close".localized, role: .cancel) {
+ viewModel.uninstallErrorMessage = nil
+ }
+ } message: {
+ if let message = viewModel.uninstallErrorMessage {
+ Text(message)
+ }
+ }
+ }
+
+ private var uninstallerRestartBanner: some View {
+ HStack(spacing: 12) {
+ Image(systemName: "arrow.trianglehead.2.clockwise.rotate.90")
+ .font(.system(size: 16, weight: .semibold))
+ .foregroundStyle(.orange)
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text("uninstaller_restart_recommended_title".localized)
+ .font(.callout.weight(.semibold))
+ Text("uninstaller_restart_recommended_body".localized)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ Spacer(minLength: 8)
+
+ Button {
+ SystemMaintenanceService.requestSystemRestart()
+ } label: {
+ Label("restart_mac_button".localized, systemImage: "power")
+ .font(.callout.weight(.medium))
+ }
+ .buttonStyle(.glass)
+ .tint(.orange)
+
+ Button {
+ viewModel.showingRestartBanner = false
+ } label: {
+ Image(systemName: "xmark")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ .buttonStyle(.plain)
+ .help("close".localized)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 10)
+ .background(Color.orange.opacity(0.08))
}
private var uninstallerHeaderBar: some View {
WorkspaceHeaderBar {
GlassPillPicker(
items: UninstallerTab.allCases,
- selection: $selectedTab,
+ selection: $viewModel.selectedTab,
icon: { $0.iconName },
label: { $0.localizedTitle }
)
@@ -217,14 +260,16 @@ struct UninstallerView: View {
Capsule().strokeBorder(settings.uninstallerScanMode == .safe ? Color.blue.opacity(0.3) : Color.green.opacity(0.3), lineWidth: 1)
)
- if selectedTab == .applications {
+ if viewModel.selectedTab == .applications {
CompactSearchField(
placeholder: "uninstaller_search".localized,
- text: $searchText,
+ text: $viewModel.searchText,
width: 200
)
- Button(action: loadApps) {
+ ScanStatusPill(lastUpdatedAt: viewModel.lastUpdatedAt)
+
+ Button(action: { viewModel.loadApps(mode: settings.uninstallerScanMode) }) {
Image(systemName: "arrow.clockwise")
}
.glassButtonStyle()
@@ -238,31 +283,34 @@ struct UninstallerView: View {
HStack(spacing: 0) {
// Apps List
VStack(spacing: 0) {
- if isLoading {
+ if viewModel.isLoading {
AnimatedScanView(
title: "uninstaller_scanning_apps".localized,
- subtitle: service.progress.message,
- currentStep: service.progress.currentStep,
- totalSteps: service.progress.totalSteps
+ subtitle: viewModel.service.progress.message,
+ currentStep: viewModel.service.progress.currentStep,
+ totalSteps: viewModel.service.progress.totalSteps
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
VStack(spacing: 0) {
- if isDeepScanning {
+ if viewModel.isDeepScanning {
VStack(spacing: 4) {
- ProgressView(value: Double(min(deepScanCompleted, deepScanTotal)), total: Double(max(1, deepScanTotal)))
- .progressViewStyle(.linear)
- .padding(.horizontal, 8)
- Text(String(format: "uninstaller.deep_scanning_progress".localized, min(deepScanCompleted, deepScanTotal), deepScanTotal))
+ ProgressView(
+ value: Double(min(viewModel.deepScanCompleted, viewModel.deepScanTotal)),
+ total: Double(max(1, viewModel.deepScanTotal))
+ )
+ .progressViewStyle(.linear)
+ .padding(.horizontal, 8)
+ Text(String(format: "uninstaller.deep_scanning_progress".localized, min(viewModel.deepScanCompleted, viewModel.deepScanTotal), viewModel.deepScanTotal))
.font(.caption2)
.foregroundColor(.secondary)
}
.padding(.vertical, 6)
.background(Color(NSColor.controlBackgroundColor).opacity(reduceTransparency ? 1.0 : 0.15))
}
- List(filteredApps) { app in
+ List(viewModel.filteredApps) { app in
let unscan = app.scanState != .deepScanned
- let isThisAppUninstalling = isUninstalling && (selectedApp?.id == app.id)
+ let isThisAppUninstalling = viewModel.isUninstalling && (viewModel.selectedApp?.id == app.id)
AppRowView(
app: app,
formatter: formatter,
@@ -272,13 +320,11 @@ struct UninstallerView: View {
)
.contentShape(Rectangle())
.onTapGesture {
- guard !isUninstalling else { return }
- guard app.scanState == .deepScanned else { return }
- selectedVersionID = nil
- selectedApp = app
+ guard !viewModel.isUninstalling else { return }
+ viewModel.selectApp(app, mode: settings.uninstallerScanMode)
}
.listRowBackground(
- (selectedApp?.id == app.id)
+ (viewModel.selectedApp?.id == app.id)
? Color.accentColor.opacity(0.1)
: Color.clear
)
@@ -291,12 +337,12 @@ struct UninstallerView: View {
.frame(width: max(250, geometry.size.width * 0.3)) // 30% width but min 250
.background(reduceTransparency ? Color(NSColor.controlBackgroundColor) : Color.clear)
.background(.ultraThinMaterial)
-
+
Divider()
-
+
// Detail Area
ZStack {
- if isUninstalling {
+ if viewModel.isUninstalling {
VStack(spacing: 20) {
ProgressView()
.scaleEffect(1.4)
@@ -304,7 +350,7 @@ struct UninstallerView: View {
.padding(.bottom, 4)
VStack(spacing: 6) {
- Text(String(format: "uninstaller_uninstalling_app".localized, uninstallingAppName))
+ Text(String(format: "uninstaller_uninstalling_app".localized, viewModel.uninstallingAppName))
.font(.title3)
.fontWeight(.bold)
.multilineTextAlignment(.center)
@@ -319,7 +365,7 @@ struct UninstallerView: View {
.glassCard(cornerRadius: 16)
.padding(24)
.transition(.opacity.combined(with: .scale(scale: 0.96)))
- } else if let app = selectedApp {
+ } else if let app = viewModel.selectedApp {
appDetailView(app)
.frame(maxWidth: .infinity)
} else {
@@ -327,174 +373,13 @@ struct UninstallerView: View {
.frame(maxWidth: .infinity)
}
}
- .animation(.spring(response: 0.35, dampingFraction: 0.8), value: isUninstalling)
+ .animation(.spring(response: 0.35, dampingFraction: 0.8), value: viewModel.isUninstalling)
.layoutPriority(1) // Occupy remaining space
}
.padding(.top, 4)
}
}
- private func loadApps() {
- scanTask?.cancel()
- isLoading = true
- isDeepScanning = false
- deepScanCompleted = 0
- deepScanTotal = 0
-
- scanTask = Task {
- let fresh = (try? await service.scanAllApplications()) ?? []
- guard !Task.isCancelled else { return }
-
- allApps = fresh
- isLoading = false
-
- let total = fresh.count
- guard total > 0 else { return }
-
- isDeepScanning = true
- deepScanCompleted = 0
- deepScanTotal = total
-
- for app in fresh {
- guard !Task.isCancelled else { break }
- if let result = try? await service.deepScan(app, mode: settings.uninstallerScanMode) {
- guard !Task.isCancelled else { break }
- deepScanCompleted = min(deepScanTotal, deepScanCompleted + 1)
- if let idx = allApps.firstIndex(where: { $0.id == result.id || sameAppURL($0.url, result.url) }) {
- allApps[idx] = result
- }
- if let selected = selectedApp, selected.id == result.id || sameAppURL(selected.url, result.url) {
- selectedApp = result
- }
- deepScanCache[NormalizedPath.key(result.url)] = result
- } else {
- guard !Task.isCancelled else { break }
- deepScanCompleted = min(deepScanTotal, deepScanCompleted + 1)
- }
- }
-
- if !Task.isCancelled {
- isDeepScanning = false
- }
- }
- }
-
- private func uninstall(_ app: UninstallerService.AppInfo) {
- uninstallingAppName = app.name
- isUninstalling = true
- Task {
- defer {
- isUninstalling = false
- }
- do {
- let report = try await service.uninstall(
- app: app,
- bypassTrash: settings.bypassTrashOnUninstall,
- emptyTrashImmediately: settings.emptyTrashDuringCleanup,
- removeFromDock: settings.removeFromDockOnUninstall
- )
-
- await MainActor.run {
- loadApps()
- selectedApp = nil
- if let report = report, report.hasLeftovers || !report.failedDeletions.isEmpty {
- postUninstallReport = report
- showingPostUninstallSheet = true
- } else if settings.showNotifications {
- let title = "uninstaller_complete_title".localized
- let body = String(format: "uninstaller_complete_body".localized, app.name)
- NotificationManager.shared.sendNotification(title: title, body: body)
- }
- }
- } catch {
- Logger.uninstallerView.error("Uninstall failed: \(error.localizedDescription, privacy: .public)")
- }
- }
- }
-
- private func uninstallVersion(_ versionApp: UninstallerService.AppInfo, from parentApp: UninstallerService.AppInfo) {
- uninstallingAppName = "\(parentApp.name) v\(versionApp.version)"
- isUninstalling = true
- Task {
- defer {
- isUninstalling = false
- }
- do {
- let report = try await service.uninstall(
- app: versionApp,
- bypassTrash: settings.bypassTrashOnUninstall,
- emptyTrashImmediately: settings.emptyTrashDuringCleanup,
- removeFromDock: settings.removeFromDockOnUninstall
- )
-
- await MainActor.run {
- if let report = report, report.hasLeftovers || !report.failedDeletions.isEmpty {
- postUninstallReport = report
- showingPostUninstallSheet = true
- } else if settings.showNotifications {
- let title = "uninstaller_complete_title".localized
- let body = String(format: "uninstaller_version_deleted_body".localized, versionApp.version, parentApp.name)
- NotificationManager.shared.sendNotification(title: title, body: body)
- }
-
- let remaining = parentApp.versions.filter { NormalizedPath.key($0.url) != NormalizedPath.key(versionApp.url) }
-
- if remaining.isEmpty {
- allApps.removeAll { $0.id == parentApp.id }
- selectedApp = nil
- } else if remaining.count == 1 {
- var updatedParent = remaining[0]
- updatedParent.versions = []
- if let idx = allApps.firstIndex(where: { $0.id == parentApp.id }) {
- allApps[idx] = updatedParent
- }
- selectedApp = updatedParent
- } else {
- var updatedParent = parentApp
- updatedParent.versions = remaining
- updatedParent.size = remaining.reduce(0) { $0 + $1.size }
- if let idx = allApps.firstIndex(where: { $0.id == parentApp.id }) {
- allApps[idx] = updatedParent
- }
- selectedApp = updatedParent
- }
- }
- } catch {
- Logger.uninstallerView.error("Uninstall version failed: \(error.localizedDescription, privacy: .public)")
- }
- }
- }
-
- private func cleanPostUninstallLeftovers(_ items: [LeftoverItem]) {
- guard !items.isEmpty else {
- showingPostUninstallSheet = false
- postUninstallReport = nil
- return
- }
-
- Task {
- do {
- let freed = try await service.removeLeftovers(items, bypassTrash: settings.bypassTrashOnUninstall)
- await MainActor.run {
- self.showingPostUninstallSheet = false
- self.postUninstallReport = nil
-
- if settings.showNotifications {
- let title = "uninstaller_complete_title".localized
- let body = String(
- format: "uninstaller_leftovers_cleaned_notification".localized,
- Int64(items.count),
- ByteCountFormatter.localizedString(fromByteCount: freed, countStyle: .file)
- )
- NotificationManager.shared.sendNotification(title: title, body: body)
- }
- }
- } catch {
- Logger.uninstallerView.error("Failed to clean leftovers: \(error.localizedDescription, privacy: .public)")
- }
- }
- }
-
private var dropZoneView: some View {
VStack(spacing: 20) {
ZStack {
@@ -535,10 +420,7 @@ struct UninstallerView: View {
_ = provider.loadObject(ofClass: URL.self) { url, _ in
guard let url = url, url.pathExtension == "app" else { return }
Task { @MainActor in
- if let scanned = try? await service.scan(appURL: url) {
- let deep = (try? await service.deepScan(scanned)) ?? scanned
- self.selectedApp = deep
- }
+ viewModel.dropApp(at: url, mode: settings.uninstallerScanMode)
}
}
return true
@@ -572,10 +454,20 @@ struct UninstallerView: View {
}
if settings.showRelatedFiles {
- relatedFilesSection(app)
+ if app.scanState != .deepScanned {
+ HStack(spacing: 8) {
+ ProgressView().controlSize(.small)
+ Text("uninstaller.progress.discovering".localized)
+ .font(.caption)
+ .foregroundColor(.secondary)
+ }
+ .padding(.vertical, 4)
+ } else {
+ relatedFilesSection(app)
- if !app.developerComponents.isEmpty {
- developerComponentsSection(app)
+ if !app.developerComponents.isEmpty {
+ developerComponentsSection(app)
+ }
}
}
@@ -613,10 +505,10 @@ struct UninstallerView: View {
.font(.headline)
}
Spacer()
- if selectedVersionID != nil {
+ if viewModel.selectedVersionID != nil {
Button(action: {
withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
- selectedVersionID = nil
+ viewModel.selectedVersionID = nil
}
}) {
HStack(spacing: 4) {
@@ -633,20 +525,13 @@ struct UninstallerView: View {
VStack(spacing: 8) {
ForEach(app.versions) { versionApp in
- let isSelectedVersion = selectedVersionID == versionApp.id
+ let isSelectedVersion = viewModel.selectedVersionID == versionApp.id
HStack(alignment: .center, spacing: 12) {
- if let iconData = versionApp.iconData ?? app.iconData, let nsImage = NSImage(data: iconData) {
- Image(nsImage: nsImage)
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 28, height: 28)
- .cornerRadius(6)
- } else {
+ CachedFileIconView(path: versionApp.url.path, size: 28, cornerRadius: 6) {
Image(systemName: "square.stack.3d.up")
.font(.system(size: 18))
.foregroundColor(.secondary)
- .frame(width: 28, height: 28)
}
VStack(alignment: .leading, spacing: 2) {
@@ -702,10 +587,10 @@ struct UninstallerView: View {
.contentShape(Rectangle())
.onTapGesture {
withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
- if selectedVersionID == versionApp.id {
- selectedVersionID = nil
+ if viewModel.selectedVersionID == versionApp.id {
+ viewModel.selectedVersionID = nil
} else {
- selectedVersionID = versionApp.id
+ viewModel.selectedVersionID = versionApp.id
}
}
}
@@ -724,6 +609,8 @@ struct UninstallerView: View {
DetailBadge(title: "size".localized, value: ByteCountFormatter.localizedString(fromByteCount: settings.showRelatedFiles ? app.totalSize : app.size, countStyle: .file))
if let lastUsed = app.lastUsed {
DetailBadge(title: "last_used".localized, value: lastUsed.formatted(.dateTime.year().month().day().locale(LanguageManager.shared.currentLocale)))
+ } else {
+ DetailBadge(title: "last_used".localized, value: "process.unknown".localized)
}
}
@@ -755,11 +642,11 @@ struct UninstallerView: View {
Button(action: { showingConfirmation = true }) {
HStack(spacing: 8) {
- if isUninstalling {
+ if viewModel.isUninstalling {
ProgressView()
.controlSize(.small)
}
- Text(isUninstalling ? "uninstaller_uninstalling".localized : "uninstaller_button_uninstall".localized)
+ Text(viewModel.isUninstalling ? "uninstaller_uninstalling".localized : "uninstaller_button_uninstall".localized)
.font(.headline)
}
.frame(maxWidth: 300)
@@ -767,12 +654,12 @@ struct UninstallerView: View {
}
.destructiveGlassButtonStyle()
.controlSize(.large)
- .disabled(isUninstalling)
+ .disabled(viewModel.isUninstalling)
}
}
private func displayedRelatedFiles(for app: UninstallerService.AppInfo) -> [UninstallerService.RelatedFile] {
- guard app.isGrouped, let selectedID = selectedVersionID,
+ guard app.isGrouped, let selectedID = viewModel.selectedVersionID,
let selectedVersion = app.versions.first(where: { $0.id == selectedID }) else {
return app.relatedFiles
}
@@ -802,7 +689,7 @@ struct UninstallerView: View {
}
private func displayedDeveloperComponents(for app: UninstallerService.AppInfo) -> [UninstallerService.RelatedCleanupComponent] {
- guard app.isGrouped, let selectedID = selectedVersionID,
+ guard app.isGrouped, let selectedID = viewModel.selectedVersionID,
let selectedVersion = app.versions.first(where: { $0.id == selectedID }) else {
return app.developerComponents
}
@@ -865,17 +752,25 @@ struct UninstallerView: View {
let visibleTiers = allTiers
let selectedCount = displayFiles.filter(\.isSelected).count
return VStack(alignment: .leading, spacing: 8) {
+ if displayFiles.contains(where: \.isBrowserData) {
+ Label("uninstaller_browser_data_warning".localized, systemImage: "exclamationmark.shield.fill")
+ .font(.caption)
+ .foregroundStyle(.orange)
+ .padding(10)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: 10).fill(Color.orange.opacity(0.1)))
+ }
ForEach(visibleTiers, id: \.self) { tier in
let files = grouped[tier] ?? []
if !files.isEmpty {
DisclosureGroup(
isExpanded: Binding(
- get: { expandedConfidenceTiers.contains(tier) },
+ get: { viewModel.expandedConfidenceTiers.contains(tier) },
set: { expanded in
if expanded {
- expandedConfidenceTiers.insert(tier)
+ viewModel.expandedConfidenceTiers.insert(tier)
} else {
- expandedConfidenceTiers.remove(tier)
+ viewModel.expandedConfidenceTiers.remove(tier)
}
}
)
@@ -888,7 +783,7 @@ struct UninstallerView: View {
settings: settings,
formatter: formatter,
versionBadge: versionBadgeText(for: file.url, in: app),
- onToggle: { toggleSelection(file, in: app) }
+ onToggle: { viewModel.toggleSelection(file, in: app) }
)
if index < files.count - 1 {
Divider()
@@ -959,7 +854,7 @@ struct UninstallerView: View {
Toggle("", isOn: Binding(
get: { component.isSelected },
set: { newValue in
- toggleDeveloperComponent(in: app, at: index, value: newValue)
+ viewModel.toggleDeveloperComponent(in: app, at: index, value: newValue)
}
))
.toggleStyle(.checkbox)
@@ -1021,38 +916,6 @@ struct UninstallerView: View {
}
.padding(.top, app.relatedFiles.isEmpty ? 0 : 4)
}
-
- private func toggleSelection(_ file: UninstallerService.RelatedFile, in app: UninstallerService.AppInfo) {
- if let appIndex = allApps.firstIndex(where: { $0.id == app.id }),
- let fileIndex = allApps[appIndex].relatedFiles.firstIndex(where: { $0.id == file.id }) {
- allApps[appIndex].relatedFiles[fileIndex].isSelected.toggle()
- if selectedApp?.id == app.id {
- selectedApp = allApps[appIndex]
- }
- return
- }
- if var current = selectedApp, current.id == app.id,
- let fileIndex = current.relatedFiles.firstIndex(where: { $0.id == file.id }) {
- current.relatedFiles[fileIndex].isSelected.toggle()
- selectedApp = current
- }
- }
-
- private func toggleDeveloperComponent(in app: UninstallerService.AppInfo, at index: Int, value: Bool) {
- if let appIndex = allApps.firstIndex(where: { $0.id == app.id }),
- allApps[appIndex].developerComponents.indices.contains(index) {
- allApps[appIndex].developerComponents[index].isSelected = value
- if selectedApp?.id == app.id {
- selectedApp = allApps[appIndex]
- }
- return
- }
- if var current = selectedApp, current.id == app.id,
- current.developerComponents.indices.contains(index) {
- current.developerComponents[index].isSelected = value
- selectedApp = current
- }
- }
}
struct AppRowView: View {
@@ -1068,14 +931,11 @@ struct AppRowView: View {
ProgressView()
.controlSize(.small)
.frame(width: 32, height: 32)
- } else if let iconData = app.iconData, let nsImage = NSImage(data: iconData) {
- Image(nsImage: nsImage)
- .resizable()
- .frame(width: 32, height: 32)
} else {
- RoundedRectangle(cornerRadius: 8)
- .fill(Color.secondary.opacity(0.2))
- .frame(width: 32, height: 32)
+ CachedFileIconView(path: app.url.path, size: 32, cornerRadius: 8) {
+ RoundedRectangle(cornerRadius: 8)
+ .fill(Color.secondary.opacity(0.2))
+ }
}
VStack(alignment: .leading, spacing: 2) {
@@ -1198,6 +1058,15 @@ struct RelatedFileRow: View {
.foregroundStyle(Color.purple)
.background(Capsule().fill(Color.purple.opacity(0.12)))
}
+ if file.isBrowserData {
+ Text("uninstaller_browser_data_badge".localized)
+ .font(.caption2)
+ .fontWeight(.semibold)
+ .padding(.horizontal, 5)
+ .padding(.vertical, 1)
+ .foregroundStyle(Color.orange)
+ .background(Capsule().fill(Color.orange.opacity(0.14)))
+ }
if file.deletionRisk == .shared {
SharedBadgeView(url: file.url, riskColor: riskColor)
}
@@ -1402,15 +1271,9 @@ struct AppDetailHeaderView: View {
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .center, spacing: 14) {
- if let iconData = app.iconData, let nsImage = NSImage(data: iconData) {
- Image(nsImage: nsImage)
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 56, height: 56)
- } else {
+ CachedFileIconView(path: app.url.path, size: 56, cornerRadius: 12) {
RoundedRectangle(cornerRadius: 12)
.fill(Color.secondary.opacity(0.2))
- .frame(width: 56, height: 56)
.overlay(Image(systemName: "app").foregroundColor(.secondary))
}
diff --git a/MacOSCleaner/Features/Uninstaller/UninstallerViewModel.swift b/MacOSCleaner/Features/Uninstaller/UninstallerViewModel.swift
new file mode 100644
index 0000000..33b2f9e
--- /dev/null
+++ b/MacOSCleaner/Features/Uninstaller/UninstallerViewModel.swift
@@ -0,0 +1,506 @@
+import Foundation
+import Observation
+import OSLog
+
+private extension Logger {
+ static let uninstallerVM = Logger(subsystem: Bundle.main.bundleIdentifier ?? "com.macos-cleaner", category: "UninstallerViewModel")
+}
+
+@MainActor
+@Observable
+public final class UninstallerViewModel {
+ public let service: UninstallerService
+
+ // Applications tab state
+ var selectedTab: UninstallerTab = .applications
+ public var allApps: [UninstallerService.AppInfo] = []
+ public var selectedApp: UninstallerService.AppInfo?
+ public var searchText = ""
+ public var isLoading = false
+ public var isUninstalling = false
+ public var uninstallingAppName = ""
+ public var isDeepScanning = false
+ public var deepScanCompleted = 0
+ public var deepScanTotal = 0
+ public var expandedConfidenceTiers: Set = [.guaranteed, .veryLikely, .possible]
+ public var selectedVersionID: UUID? = nil
+ public var postUninstallReport: VerificationReport? = nil
+ public var showingPostUninstallSheet = false
+ public var uninstallErrorMessage: String? = nil
+ public var showingUninstallErrorAlert = false
+ public var showingRestartBanner = false
+ public var isSpotlightAvailable: Bool = true
+ public var lastUpdatedAt: Date? = nil
+
+ // Leftovers tab state
+ public var orphanItems: [OrphanItem] = []
+ public var isLoadingOrphans = false
+ public var hasScannedOrphans = false
+ public var orphanScanProgressMessage = ""
+ public var orphanSearchText = ""
+ public var orphanFilterTier: ConfidenceTier? = nil
+ public var expandedOrphanIDs: Set = []
+ public var isCleaningOrphans = false
+ public var orphanErrorMessage: String? = nil
+ public var showingOrphanErrorAlert = false
+
+ private var deepScanCache: [String: UninstallerService.AppInfo] = [:]
+ private var activeScanIndex: ResidualScanIndex?
+ private var scanTask: Task?
+ private var priorityDeepScanTask: Task?
+ private var orphanScanTask: Task?
+ private let discoverAppsHandler: (@Sendable () async throws -> [UninstallerService.AppInfo])?
+ private let deepScanHandler: (@Sendable (UninstallerService.AppInfo, ScanMode) async throws -> UninstallerService.AppInfo)?
+
+ public init(
+ service: UninstallerService = UninstallerService(),
+ discoverAppsHandler: (@Sendable () async throws -> [UninstallerService.AppInfo])? = nil,
+ deepScanHandler: (@Sendable (UninstallerService.AppInfo, ScanMode) async throws -> UninstallerService.AppInfo)? = nil
+ ) {
+ self.service = service
+ self.discoverAppsHandler = discoverAppsHandler
+ self.deepScanHandler = deepScanHandler
+ }
+
+ public var filteredApps: [UninstallerService.AppInfo] {
+ if searchText.isEmpty {
+ return allApps
+ }
+ return allApps.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
+ }
+
+ public func sameAppURL(_ lhs: URL, _ rhs: URL) -> Bool {
+ NormalizedPath.key(lhs) == NormalizedPath.key(rhs)
+ }
+
+ public func refreshSpotlightAvailability() {
+ Task { [weak self] in
+ let available = await Task.detached(priority: .utility) {
+ SpotlightMetadata.isIndexingAvailable()
+ }.value
+ self?.isSpotlightAvailable = available
+ }
+ }
+
+ public func loadAppsIfNeeded(mode: ScanMode) {
+ refreshSpotlightAvailability()
+ guard lastUpdatedAt == nil, allApps.isEmpty, !isLoading else { return }
+ loadApps(mode: mode)
+ }
+
+ public func loadApps(mode: ScanMode) {
+ scanTask?.cancel()
+ priorityDeepScanTask?.cancel()
+ refreshSpotlightAvailability()
+ isLoading = true
+ isDeepScanning = false
+ deepScanCompleted = 0
+ deepScanTotal = 0
+ deepScanCache.removeAll()
+ activeScanIndex = nil
+
+ let discover = discoverAppsHandler
+ let deepScanRunner = deepScanHandler
+ let service = self.service
+
+ scanTask = Task {
+ let fresh: [UninstallerService.AppInfo]
+ if let discover {
+ fresh = (try? await discover()) ?? []
+ } else {
+ fresh = (try? await service.scanAllApplications()) ?? []
+ }
+ guard !Task.isCancelled else { return }
+
+ allApps = fresh
+ lastUpdatedAt = Date()
+ isLoading = false
+
+ let total = fresh.count
+ guard total > 0 else { return }
+
+ isDeepScanning = true
+ deepScanCompleted = 0
+ deepScanTotal = total
+
+ let scanIndex: ResidualScanIndex?
+ if deepScanRunner == nil {
+ let built = await Task.detached(priority: .utility) {
+ await service.buildResidualScanIndex()
+ }.value
+ guard !Task.isCancelled else { return }
+ activeScanIndex = built
+ scanIndex = built
+ } else {
+ scanIndex = nil
+ }
+
+ let maxConcurrent = 4
+ var iterator = fresh.makeIterator()
+
+ await withTaskGroup(of: (UninstallerService.AppInfo, UninstallerService.AppInfo?).self) { group in
+ for _ in 0.. [URL] {
+ if !app.versions.isEmpty {
+ return app.versions.flatMap { selectedRemovalURLs(for: $0) }
+ }
+ return [app.url]
+ + app.relatedFiles.filter(\.isSelected).map(\.url)
+ + app.developerComponents.filter(\.isSelected).map(\.url)
+ }
+
+ public func toggleSelection(_ file: UninstallerService.RelatedFile, in app: UninstallerService.AppInfo) {
+ if let appIndex = allApps.firstIndex(where: { $0.id == app.id }),
+ let fileIndex = allApps[appIndex].relatedFiles.firstIndex(where: { $0.id == file.id }) {
+ allApps[appIndex].relatedFiles[fileIndex].isSelected.toggle()
+ let updated = allApps[appIndex]
+ deepScanCache[NormalizedPath.key(updated.url)] = updated
+ if selectedApp?.id == app.id {
+ selectedApp = updated
+ }
+ return
+ }
+ if var current = selectedApp, current.id == app.id,
+ let fileIndex = current.relatedFiles.firstIndex(where: { $0.id == file.id }) {
+ current.relatedFiles[fileIndex].isSelected.toggle()
+ deepScanCache[NormalizedPath.key(current.url)] = current
+ selectedApp = current
+ }
+ }
+
+ public func toggleDeveloperComponent(in app: UninstallerService.AppInfo, at index: Int, value: Bool) {
+ if let appIndex = allApps.firstIndex(where: { $0.id == app.id }),
+ allApps[appIndex].developerComponents.indices.contains(index) {
+ allApps[appIndex].developerComponents[index].isSelected = value
+ let updated = allApps[appIndex]
+ deepScanCache[NormalizedPath.key(updated.url)] = updated
+ if selectedApp?.id == app.id {
+ selectedApp = updated
+ }
+ return
+ }
+ if var current = selectedApp, current.id == app.id,
+ current.developerComponents.indices.contains(index) {
+ current.developerComponents[index].isSelected = value
+ deepScanCache[NormalizedPath.key(current.url)] = current
+ selectedApp = current
+ }
+ }
+
+ // MARK: - Orphans
+
+ public func startOrphanScan() {
+ orphanScanTask?.cancel()
+ isLoadingOrphans = true
+ orphanScanProgressMessage = "uninstaller.progress.discovering".localized
+
+ let service = self.service
+ orphanScanTask = Task {
+ do {
+ let found = try await service.scanOrphanedResiduals { message in
+ Task { @MainActor in
+ self.orphanScanProgressMessage = message
+ }
+ }
+ guard !Task.isCancelled else { return }
+ self.orphanItems = found
+ self.isLoadingOrphans = false
+ self.hasScannedOrphans = true
+ } catch {
+ Logger.uninstallerVM.error("Orphan scan failed: \(error.localizedDescription, privacy: .public)")
+ self.isLoadingOrphans = false
+ self.hasScannedOrphans = true
+ }
+ }
+ }
+
+ public func cleanSelectedOrphans(_ targets: [OrphanItem], settings: AppSettings) {
+ guard !targets.isEmpty else { return }
+ isCleaningOrphans = true
+ let bypassTrash = settings.bypassTrashOnUninstall
+ let showNotifications = settings.showNotifications
+
+ Task {
+ defer { isCleaningOrphans = false }
+ do {
+ let result = try await service.removeOrphanedResiduals(targets, bypassTrash: bypassTrash)
+ let removedIDs = Set(result.succeededItems.map(\.id))
+ self.orphanItems.removeAll { removedIDs.contains($0.id) }
+ if UninstallerService.requiresRestartForRemovedPaths(result.succeededItems.map(\.url)) {
+ self.showingRestartBanner = true
+ }
+
+ if !result.failedItems.isEmpty {
+ self.orphanErrorMessage = String(format: "orphaned_cleanup_failed_count".localized, Int64(result.failedItems.count))
+ self.showingOrphanErrorAlert = true
+ }
+
+ if showNotifications, !result.succeededItems.isEmpty {
+ let title = "uninstaller_complete_title".localized
+ let body = String(
+ format: "uninstaller_leftovers_cleaned_notification".localized,
+ Int64(result.succeededItems.count),
+ ByteCountFormatter.localizedString(fromByteCount: result.freed, countStyle: .file)
+ )
+ NotificationManager.shared.sendNotification(title: title, body: body)
+ }
+ } catch {
+ Logger.uninstallerVM.error("Cleaning orphans failed: \(error.localizedDescription, privacy: .public)")
+ self.orphanErrorMessage = error.localizedDescription
+ self.showingOrphanErrorAlert = true
+ }
+ }
+ }
+
+ private func nextPendingDeepScanApp(
+ from iterator: inout IndexingIterator<[UninstallerService.AppInfo]>
+ ) -> UninstallerService.AppInfo? {
+ while !Task.isCancelled {
+ guard let next = iterator.next() else { return nil }
+ let key = NormalizedPath.key(next.url)
+ if let existingIdx = allApps.firstIndex(where: { $0.id == next.id || sameAppURL($0.url, next.url) }),
+ allApps[existingIdx].scanState == .deepScanned {
+ deepScanCompleted = min(deepScanTotal, deepScanCompleted + 1)
+ continue
+ }
+ if let alreadyScanned = deepScanCache[key] {
+ applyDeepScanResult(alreadyScanned)
+ deepScanCompleted = min(deepScanTotal, deepScanCompleted + 1)
+ continue
+ }
+ return next
+ }
+ return nil
+ }
+
+ private func applyDeepScanResult(_ result: UninstallerService.AppInfo) {
+ deepScanCache[NormalizedPath.key(result.url)] = result
+ if let idx = allApps.firstIndex(where: { $0.id == result.id || sameAppURL($0.url, result.url) }) {
+ allApps[idx] = result
+ }
+ if let selected = selectedApp, selected.id == result.id || sameAppURL(selected.url, result.url) {
+ selectedApp = result
+ }
+ }
+}
diff --git a/MacOSCleaner/Features/Uninstaller/VerificationEngine.swift b/MacOSCleaner/Features/Uninstaller/VerificationEngine.swift
index 9fadb35..d933375 100644
--- a/MacOSCleaner/Features/Uninstaller/VerificationEngine.swift
+++ b/MacOSCleaner/Features/Uninstaller/VerificationEngine.swift
@@ -13,6 +13,7 @@ public actor VerificationEngine {
private let weights: ScoringWeights
private let ruleRegistry: ApplicationRuleRegistry
private let fileSystemContext: FileSystemContext
+ private let safetyManager: SafetyManager
public init(
commandRunner: any CommandRunning = CommandRunner(),
@@ -21,7 +22,8 @@ public actor VerificationEngine {
thresholds: ScoreThresholds = .default,
weights: ScoringWeights = .default,
ruleRegistry: ApplicationRuleRegistry = ApplicationRuleRegistry.createDefault(),
- fileSystemContext: FileSystemContext = .production
+ fileSystemContext: FileSystemContext = .production,
+ safetyManager: SafetyManager? = nil
) {
self.commandRunner = commandRunner
self.codesignCache = codesignCache
@@ -30,17 +32,28 @@ public actor VerificationEngine {
self.weights = weights
self.ruleRegistry = ruleRegistry
self.fileSystemContext = fileSystemContext
+ self.safetyManager = safetyManager ?? SafetyManager(
+ homeDirectory: fileSystemContext.homePath,
+ fileSystemContext: fileSystemContext
+ )
}
- public func verify(identity: AppIdentity) async -> VerificationReport {
+ public func verify(identity: AppIdentity, excludedPaths: Set = []) async -> VerificationReport {
Logger.verification.info("Verifying '\(identity.appName, privacy: .public)' after uninstall")
let collector = CandidateCollector(
fileManager: .default,
commandRunner: commandRunner,
- fileSystemContext: fileSystemContext
+ fileSystemContext: fileSystemContext,
+ safetyManager: safetyManager
)
- let candidates = await collector.collect(identity: identity)
+ let rawCandidates = await collector.collect(identity: identity)
+ let candidates = rawCandidates.filter { candidate in
+ let lowerKey = NormalizedPath.lowercaseKey(candidate.path)
+ return !excludedPaths.contains { excluded in
+ NormalizedPath.isEqualOrDescendant(lowerKey, of: excluded)
+ }
+ }
guard !candidates.isEmpty else {
Logger.verification.info("0 leftovers found")
@@ -82,6 +95,7 @@ public actor VerificationEngine {
var leftoverItems: [LeftoverItem] = []
for artifact in leftovers {
let details = artifactMap[artifact.url]
+ let isBrowserData = safetyManager.isBrowserUserDataPath(artifact.url.path)
leftoverItems.append(
LeftoverItem(
url: artifact.url,
@@ -92,7 +106,7 @@ public actor VerificationEngine {
evidence: details?.evidence ?? artifact.evidence,
rawEvidence: details?.rawEvidence ?? [],
confidence: details?.tier ?? .possible,
- isSelected: true
+ isSelected: !isBrowserData
)
)
}
diff --git a/MacOSCleaner/Features/Updates/UpdateAvailableView.swift b/MacOSCleaner/Features/Updates/UpdateAvailableView.swift
index f10c84a..37202ba 100644
--- a/MacOSCleaner/Features/Updates/UpdateAvailableView.swift
+++ b/MacOSCleaner/Features/Updates/UpdateAvailableView.swift
@@ -176,7 +176,7 @@ struct UpdateAvailableView: View {
version: "3.0.1",
dmgURL: URL(string: "https://github.com/AlexTkDev/MacOSCleaner/releases/download/3.0.1/MacOSCleaner.dmg")
),
- currentVersion: "3.0.0",
+ currentVersion: "3.0.1",
onDismissLater: {},
onDismissForVersion: {}
)
diff --git a/MacOSCleaner/Infrastructure/AppIconCache.swift b/MacOSCleaner/Infrastructure/AppIconCache.swift
new file mode 100644
index 0000000..a8b7260
--- /dev/null
+++ b/MacOSCleaner/Infrastructure/AppIconCache.swift
@@ -0,0 +1,158 @@
+import AppKit
+import CoreGraphics
+import Foundation
+
+/// Bounded, memory-capped cache of downsampled app/file icons.
+/// Rasterizes icons off the main actor at target pixel dimensions (64px or 128px)
+/// into concrete CGImage-backed NSImages so SwiftUI never triggers synchronous
+/// IconServices XPC / 1024px TIFF expansion on the main thread.
+public final class AppIconCache: @unchecked Sendable {
+ public static let shared = AppIconCache()
+
+ private actor RenderGate {
+ private var available: Int
+ private var waiters: [CheckedContinuation] = []
+
+ init(limit: Int) {
+ self.available = max(1, limit)
+ }
+
+ func acquire() async {
+ if available > 0 {
+ available -= 1
+ return
+ }
+ await withCheckedContinuation { continuation in
+ waiters.append(continuation)
+ }
+ }
+
+ func release() {
+ if !waiters.isEmpty {
+ let next = waiters.removeFirst()
+ next.resume()
+ } else {
+ available += 1
+ }
+ }
+ }
+
+ private let cache: NSCache
+ private let renderGate: RenderGate
+ private let customRenderer: (@Sendable (String, Int) -> NSImage?)?
+
+ public init(
+ countLimit: Int = 512,
+ totalCostLimit: Int = 32 * 1024 * 1024,
+ maxConcurrentRenders: Int = 4,
+ iconRenderer: (@Sendable (String, Int) -> NSImage?)? = nil
+ ) {
+ let cache = NSCache()
+ cache.countLimit = countLimit
+ cache.totalCostLimit = totalCostLimit
+ self.cache = cache
+ self.renderGate = RenderGate(limit: maxConcurrentRenders)
+ self.customRenderer = iconRenderer
+ }
+
+ public func cachedIcon(forPath path: String, pixelSize: Int = 64) -> NSImage? {
+ let key = Self.cacheKey(path: path, pixelSize: pixelSize) as NSString
+ return cache.object(forKey: key)
+ }
+
+ public func clear() {
+ cache.removeAllObjects()
+ }
+
+ public func icon(forPath path: String, pixelSize: Int = 64) async -> NSImage? {
+ let normalizedPath = NormalizedPath.string(URL(fileURLWithPath: path).standardizedFileURL.path)
+ let targetPixels = max(16, min(pixelSize, 256))
+ let key = Self.cacheKey(path: normalizedPath, pixelSize: targetPixels) as NSString
+
+ if let hit = cache.object(forKey: key) {
+ return hit
+ }
+
+ guard FileManager.default.fileExists(atPath: normalizedPath) else {
+ return nil
+ }
+
+ await renderGate.acquire()
+ if let hit = cache.object(forKey: key) {
+ await renderGate.release()
+ return hit
+ }
+ if Task.isCancelled {
+ await renderGate.release()
+ return nil
+ }
+
+ let customRenderer = self.customRenderer
+ let rendered: NSImage? = await Task.detached(priority: .utility) {
+ guard !Task.isCancelled else { return nil }
+ return autoreleasepool {
+ let raw: NSImage? = if let customRenderer {
+ customRenderer(normalizedPath, targetPixels)
+ } else {
+ NSWorkspace.shared.icon(forFile: normalizedPath)
+ }
+ guard let raw else { return nil }
+ return Self.downsample(raw, targetPixelSize: targetPixels)
+ }
+ }.value
+
+ await renderGate.release()
+
+ guard let rendered else { return nil }
+ let cost = Self.estimatedByteCost(of: rendered, fallbackPixelSize: targetPixels)
+ cache.setObject(rendered, forKey: key, cost: cost)
+ return rendered
+ }
+
+ static func cacheKey(path: String, pixelSize: Int) -> String {
+ let std = NormalizedPath.lowercaseKey(path)
+ return "\(std)#\(pixelSize)"
+ }
+
+ static func downsample(_ image: NSImage, targetPixelSize: Int) -> NSImage? {
+ var proposedRect = CGRect(x: 0, y: 0, width: targetPixelSize, height: targetPixelSize)
+ guard let cg = image.cgImage(forProposedRect: &proposedRect, context: nil, hints: nil) else {
+ return nil
+ }
+
+ let finalCG: CGImage
+ if cg.width <= targetPixelSize && cg.height <= targetPixelSize {
+ finalCG = cg
+ } else {
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
+ let bitmapInfo = CGImageAlphaInfo.premultipliedFirst.rawValue | CGImageByteOrderInfo.order32Host.rawValue
+ guard let ctx = CGContext(
+ data: nil,
+ width: targetPixelSize,
+ height: targetPixelSize,
+ bitsPerComponent: 8,
+ bytesPerRow: targetPixelSize * 4,
+ space: colorSpace,
+ bitmapInfo: bitmapInfo
+ ) else {
+ return nil
+ }
+ ctx.interpolationQuality = CGInterpolationQuality.high
+ ctx.draw(cg, in: CGRect(x: 0, y: 0, width: targetPixelSize, height: targetPixelSize))
+ guard let scaled = ctx.makeImage() else {
+ return nil
+ }
+ finalCG = scaled
+ }
+
+ let points = CGFloat(targetPixelSize) / 2.0
+ return NSImage(cgImage: finalCG, size: NSSize(width: points, height: points))
+ }
+
+ private static func estimatedByteCost(of image: NSImage, fallbackPixelSize: Int) -> Int {
+ if let rep = image.representations.first, rep.pixelsWide > 0, rep.pixelsHigh > 0 {
+ return rep.pixelsWide * rep.pixelsHigh * 4
+ }
+ return fallbackPixelSize * fallbackPixelSize * 4
+ }
+}
diff --git a/MacOSCleaner/Infrastructure/CrashSignalHandler.swift b/MacOSCleaner/Infrastructure/CrashSignalHandler.swift
new file mode 100644
index 0000000..1281d05
--- /dev/null
+++ b/MacOSCleaner/Infrastructure/CrashSignalHandler.swift
@@ -0,0 +1,50 @@
+import Darwin
+import Foundation
+
+enum CrashSignalHandler {
+ static let defaultSignals: [Int32] = [SIGABRT, SIGSEGV, SIGBUS]
+
+ static func install(signals: [Int32] = defaultSignals, installExceptionHandler: Bool = true) {
+ if installExceptionHandler {
+ NSSetUncaughtExceptionHandler { exception in
+ let message = "Uncaught NSException: \(exception.name.rawValue): \(exception.reason ?? "")\n"
+ message.withCString { ptr in
+ _ = Darwin.write(STDERR_FILENO, ptr, Darwin.strlen(ptr))
+ }
+ Darwin.abort()
+ }
+ }
+
+ for sig in signals {
+ var action = sigaction()
+ sigemptyset(&action.sa_mask)
+ action.sa_flags = SA_RESETHAND | SA_NODEFER
+ action.__sigaction_u.__sa_handler = { receivedSignal in
+ CrashSignalHandler.writeSignalBanner(for: receivedSignal)
+ Darwin.signal(receivedSignal, SIG_DFL)
+ Darwin.raise(receivedSignal)
+ }
+ sigaction(sig, &action, nil)
+ }
+ }
+
+ private static func writeSignalBanner(for sig: Int32) {
+ switch sig {
+ case SIGABRT:
+ writeStatic("MacOSCleaner fatal signal: SIGABRT\n")
+ case SIGSEGV:
+ writeStatic("MacOSCleaner fatal signal: SIGSEGV\n")
+ case SIGBUS:
+ writeStatic("MacOSCleaner fatal signal: SIGBUS\n")
+ default:
+ writeStatic("MacOSCleaner fatal signal\n")
+ }
+ }
+
+ private static func writeStatic(_ message: StaticString) {
+ message.withUTF8Buffer { buffer in
+ guard let base = buffer.baseAddress else { return }
+ _ = Darwin.write(STDERR_FILENO, base, buffer.count)
+ }
+ }
+}
diff --git a/MacOSCleaner/Infrastructure/DirectorySizeCache.swift b/MacOSCleaner/Infrastructure/DirectorySizeCache.swift
index d312435..cddbaeb 100644
--- a/MacOSCleaner/Infrastructure/DirectorySizeCache.swift
+++ b/MacOSCleaner/Infrastructure/DirectorySizeCache.swift
@@ -69,31 +69,43 @@ public actor DirectorySizeCache {
options: []
) else { return CachedDirectoryInfo(size: 0, fileCount: 0, timestamp: Date()) }
- while let fileURL = enumerator.nextObject() as? URL {
- if Task.isCancelled {
- break
- }
- let shouldExclude = FileManager.shouldExclude(url: fileURL)
- if shouldExclude {
- if (try? fileURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true {
- enumerator.skipDescendants()
+ var stopEnumerating = false
+ while !stopEnumerating {
+ autoreleasepool {
+ var batchCount = 0
+ while batchCount < 256 {
+ guard let fileURL = enumerator.nextObject() as? URL else {
+ stopEnumerating = true
+ break
+ }
+ batchCount += 1
+ if Task.isCancelled {
+ stopEnumerating = true
+ break
+ }
+ let shouldExclude = FileManager.shouldExclude(url: fileURL)
+ if shouldExclude {
+ if (try? fileURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true {
+ enumerator.skipDescendants()
+ }
+ continue
+ }
+ guard let values = try? fileURL.resourceValues(forKeys: Set(keys)) else {
+ continue
+ }
+ if FileManager.isNotDownloadedUbiquitous(values) {
+ if values.isDirectory == true { enumerator.skipDescendants() }
+ continue
+ }
+ fileCount += 1
+ // Prefer allocated (physical) size — what deleting actually reclaims.
+ // Use allocated even when 0 (true sparse files); only fall back if key is missing.
+ if let allocated = values.totalFileAllocatedSize {
+ size += Int64(allocated)
+ } else if let fileSize = values.fileSize {
+ size += Int64(fileSize)
+ }
}
- continue
- }
- guard let values = try? fileURL.resourceValues(forKeys: Set(keys)) else {
- continue
- }
- if FileManager.isNotDownloadedUbiquitous(values) {
- if values.isDirectory == true { enumerator.skipDescendants() }
- continue
- }
- fileCount += 1
- // Prefer allocated (physical) size — what deleting actually reclaims.
- // Use allocated even when 0 (true sparse files); only fall back if key missing.
- if let allocated = values.totalFileAllocatedSize {
- size += Int64(allocated)
- } else if let fileSize = values.fileSize {
- size += Int64(fileSize)
}
}
return CachedDirectoryInfo(size: size, fileCount: fileCount, timestamp: Date())
diff --git a/MacOSCleaner/Infrastructure/FileManager+Size.swift b/MacOSCleaner/Infrastructure/FileManager+Size.swift
index 4517489..5168b91 100644
--- a/MacOSCleaner/Infrastructure/FileManager+Size.swift
+++ b/MacOSCleaner/Infrastructure/FileManager+Size.swift
@@ -53,7 +53,11 @@ extension FileManager {
return result
}()
- nonisolated(unsafe) private static let _sizeCache = NSCache()
+ nonisolated(unsafe) private static let _sizeCache: NSCache = {
+ let cache = NSCache()
+ cache.countLimit = 4096
+ return cache
+ }()
private static let _sizeCacheLock = NSLock()
public nonisolated static func clearSizeCache() {
@@ -122,47 +126,60 @@ extension FileManager {
includingPropertiesForKeys: keys,
options: []
)
- while let fileURL = enumerator?.nextObject() as? URL {
- if Task.isCancelled {
- cancelled = true
- break
- }
- let shouldExclude: Bool
- if excludedPaths.isEmpty {
- shouldExclude = false
- } else if excludedPaths == FileManager.defaultExcludedPaths {
- shouldExclude = FileManager.shouldExclude(url: fileURL)
- } else {
- let filePath = fileURL.path
- shouldExclude = excludedPaths.contains { filePath.contains($0) }
- }
- if shouldExclude {
- if (try? fileURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true {
- enumerator?.skipDescendants()
- }
- continue
- }
+ var batchCount = 0
+ var stopEnumerating = false
+ while !stopEnumerating {
+ autoreleasepool {
+ batchCount = 0
+ while batchCount < 256 {
+ guard let fileURL = enumerator?.nextObject() as? URL else {
+ stopEnumerating = true
+ break
+ }
+ batchCount += 1
+ if Task.isCancelled {
+ cancelled = true
+ stopEnumerating = true
+ break
+ }
+ let shouldExclude: Bool
+ if excludedPaths.isEmpty {
+ shouldExclude = false
+ } else if excludedPaths == FileManager.defaultExcludedPaths {
+ shouldExclude = FileManager.shouldExclude(url: fileURL)
+ } else {
+ let filePath = fileURL.path
+ shouldExclude = excludedPaths.contains { filePath.contains($0) }
+ }
+ if shouldExclude {
+ if (try? fileURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true {
+ enumerator?.skipDescendants()
+ }
+ continue
+ }
- guard let values = try? fileURL.resourceValues(forKeys: Set(keys)) else {
- continue
- }
- if FileManager.isNotDownloadedUbiquitous(values) {
- if values.isDirectory == true { enumerator?.skipDescendants() }
- continue
- }
+ guard let values = try? fileURL.resourceValues(forKeys: Set(keys)) else {
+ continue
+ }
+ if FileManager.isNotDownloadedUbiquitous(values) {
+ if values.isDirectory == true { enumerator?.skipDescendants() }
+ continue
+ }
- if let fileSize = values.fileSize,
- let allocated = values.totalFileAllocatedSize, allocated > 0,
- fileSize / allocated >= FileManager.sparseFileRatioThreshold {
- continue
- }
+ if let fileSize = values.fileSize,
+ let allocated = values.totalFileAllocatedSize, allocated > 0,
+ fileSize / allocated >= FileManager.sparseFileRatioThreshold {
+ continue
+ }
- // Prefer allocated (physical) size — APFS clones inflate logical fileSize.
- // allocated == 0 is valid for sparse files; only fall back if key is missing.
- if let allocated = values.totalFileAllocatedSize {
- size += Int64(allocated)
- } else if let fileSize = values.fileSize {
- size += Int64(fileSize)
+ // Prefer allocated (physical) size — APFS clones inflate logical fileSize.
+ // allocated == 0 is valid for sparse files; only fall back if key is missing.
+ if let allocated = values.totalFileAllocatedSize {
+ size += Int64(allocated)
+ } else if let fileSize = values.fileSize {
+ size += Int64(fileSize)
+ }
+ }
}
}
@@ -183,7 +200,8 @@ extension FileManager {
url: URL,
excludedPaths: [String] = FileManager.defaultExcludedPaths
) -> Int64 {
- let cacheKey = "physical:\(url.path)" as NSString
+ let rootPath = url.path
+ let cacheKey = "physical:\(rootPath)" as NSString
FileManager._sizeCacheLock.lock()
if let cached = FileManager._sizeCache.object(forKey: cacheKey) {
FileManager._sizeCacheLock.unlock()
@@ -191,63 +209,119 @@ extension FileManager {
}
FileManager._sizeCacheLock.unlock()
+ var rootStat = Darwin.stat()
+ if stat(rootPath, &rootStat) != 0 {
+ if lstat(rootPath, &rootStat) != 0 {
+ return 0
+ }
+ }
+
+ if (rootStat.st_flags & UInt32(SF_DATALESS)) != 0 {
+ return 0
+ }
+
+ if (rootStat.st_mode & S_IFMT) != S_IFDIR {
+ let size = Int64(rootStat.st_blocks) * 512
+ if !Task.isCancelled {
+ FileManager._sizeCacheLock.lock()
+ FileManager._sizeCache.setObject(NSNumber(value: size), forKey: cacheKey)
+ FileManager._sizeCacheLock.unlock()
+ }
+ return size
+ }
+
+ let useDefaultExclusions = excludedPaths == FileManager.defaultExcludedPaths
+ let customExcluded = useDefaultExclusions ? [] : excludedPaths
+ let isSystemRoot = useDefaultExclusions && rootPath.hasPrefix("/System")
+ if isSystemRoot {
+ return 0
+ }
+
var size: Int64 = 0
var cancelled = false
- if let values = try? url.resourceValues(forKeys: [
- .isRegularFileKey,
- .fileSizeKey,
- .totalFileAllocatedSizeKey,
- .isUbiquitousItemKey,
- .ubiquitousItemDownloadingStatusKey
- ]),
- values.isRegularFile == true {
- if FileManager.isNotDownloadedUbiquitous(values) {
- return 0
+ var visitedDirInodes = Set()
+ var stack: [String] = [rootPath]
+ var checkCounter = 0
+
+ while let currentDir = stack.popLast() {
+ if Task.isCancelled {
+ cancelled = true
+ break
}
- size = Int64(values.totalFileAllocatedSize ?? values.fileSize ?? 0)
- } else {
- let keys: [URLResourceKey] = [
- .fileSizeKey,
- .totalFileAllocatedSizeKey,
- .isDirectoryKey,
- .isUbiquitousItemKey,
- .ubiquitousItemDownloadingStatusKey
- ]
- let enumerator = self.enumerator(
- at: url,
- includingPropertiesForKeys: keys,
- options: []
- )
- while let fileURL = enumerator?.nextObject() as? URL {
- if Task.isCancelled {
+ guard let dir = opendir(currentDir) else { continue }
+ let fd = dirfd(dir)
+
+ var dirStat = Darwin.stat()
+ if fstat(fd, &dirStat) == 0 {
+ if (dirStat.st_flags & UInt32(SF_DATALESS)) != 0 {
+ closedir(dir)
+ continue
+ }
+ if !visitedDirInodes.insert(dirStat.st_ino).inserted {
+ closedir(dir)
+ continue
+ }
+ }
+
+ while let entry = readdir(dir) {
+ checkCounter &+= 1
+ if (checkCounter & 63) == 0, Task.isCancelled {
cancelled = true
break
}
- let shouldExclude: Bool
- if excludedPaths.isEmpty {
- shouldExclude = false
- } else if excludedPaths == FileManager.defaultExcludedPaths {
- shouldExclude = FileManager.shouldExclude(url: fileURL)
- } else {
- let filePath = fileURL.path
- shouldExclude = excludedPaths.contains { filePath.contains($0) }
- }
- if shouldExclude {
- if (try? fileURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true {
- enumerator?.skipDescendants()
+
+ let isDot = withUnsafePointer(to: &entry.pointee.d_name) { ptr -> Bool in
+ let cPtr = UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self)
+ if cPtr[0] == 46 { // '.'
+ if cPtr[1] == 0 { return true }
+ if cPtr[1] == 46 && cPtr[2] == 0 { return true }
}
- continue
+ return false
+ }
+ if isDot { continue }
+
+ let name = withUnsafePointer(to: &entry.pointee.d_name) { ptr in
+ String(cString: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self))
+ }
+ let childPath = currentDir == "/" ? "/\(name)" : "\(currentDir)/\(name)"
+
+ var childStat = Darwin.stat()
+ let statOK = withUnsafePointer(to: &entry.pointee.d_name) { ptr in
+ let cPtr = UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self)
+ return fstatat(fd, cPtr, &childStat, AT_SYMLINK_NOFOLLOW) == 0
}
+ guard statOK else { continue }
- guard let values = try? fileURL.resourceValues(forKeys: Set(keys)) else { continue }
- if FileManager.isNotDownloadedUbiquitous(values) {
- if values.isDirectory == true { enumerator?.skipDescendants() }
+ if (childStat.st_flags & UInt32(SF_DATALESS)) != 0 {
continue
}
- guard let fileSize = values.fileSize else { continue }
- size += Int64(values.totalFileAllocatedSize ?? fileSize)
+ let fileType = childStat.st_mode & S_IFMT
+ let isDir = fileType == S_IFDIR
+
+ if !excludedPaths.isEmpty {
+ if useDefaultExclusions {
+ if Self.shouldExcludePOSIXEntry(
+ name: name,
+ fullPath: childPath,
+ isDirectory: isDir
+ ) {
+ continue
+ }
+ } else if customExcluded.contains(where: { childPath.contains($0) }) {
+ continue
+ }
+ }
+
+ if isDir {
+ stack.append(childPath)
+ } else if fileType == S_IFREG || fileType == S_IFLNK {
+ size += Int64(childStat.st_blocks) * 512
+ }
}
+
+ closedir(dir)
+ if cancelled { break }
}
guard !cancelled else { return size }
@@ -257,4 +331,17 @@ extension FileManager {
FileManager._sizeCacheLock.unlock()
return size
}
+
+ private static func shouldExcludePOSIXEntry(name: String, fullPath: String, isDirectory: Bool) -> Bool {
+ if fullPath.hasPrefix("/System") { return true }
+ if let dotIndex = name.lastIndex(of: "."), dotIndex < name.index(before: name.endIndex) {
+ let ext = name[name.index(after: dotIndex)...].lowercased()
+ if excludedExtensions.contains(ext) { return true }
+ }
+ if excludedFileNames.contains(name) { return true }
+ if isDirectory, excludedDirectoryNames.contains(where: { name.hasSuffix($0) }) {
+ return true
+ }
+ return false
+ }
}
diff --git a/MacOSCleaner/Infrastructure/FileSystemContext.swift b/MacOSCleaner/Infrastructure/FileSystemContext.swift
index f306c6f..f9d0242 100644
--- a/MacOSCleaner/Infrastructure/FileSystemContext.swift
+++ b/MacOSCleaner/Infrastructure/FileSystemContext.swift
@@ -22,7 +22,9 @@ public struct FileSystemContext: Sendable {
let temp = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().standardizedFileURL
self.allowedRoots = [
home,
+ URL(fileURLWithPath: "/Applications", isDirectory: true).resolvingSymlinksInPath().standardizedFileURL,
URL(fileURLWithPath: "/Library", isDirectory: true).resolvingSymlinksInPath().standardizedFileURL,
+ URL(fileURLWithPath: "/Volumes", isDirectory: true).resolvingSymlinksInPath().standardizedFileURL,
URL(fileURLWithPath: "/private/tmp", isDirectory: true).resolvingSymlinksInPath().standardizedFileURL,
URL(fileURLWithPath: "/tmp", isDirectory: true).resolvingSymlinksInPath().standardizedFileURL,
URL(fileURLWithPath: "/usr/local", isDirectory: true).resolvingSymlinksInPath().standardizedFileURL,
@@ -68,11 +70,11 @@ public struct FileSystemContext: Sendable {
}
}
- /// Fail-closed guard for destructive test operations.
+ /// Fail-closed guard for destructive operations outside allowed roots.
public func assertAllowedForMutation(_ url: URL) throws {
guard enforceAllowedRoots else { return }
guard isInsideAllowedRoots(url) else {
- throw SafetyError.protectedPath("outside test root: \(url.path)")
+ throw SafetyError.protectedPath("outside allowed root: \(url.path)")
}
}
}
diff --git a/MacOSCleaner/Infrastructure/NormalizedPath.swift b/MacOSCleaner/Infrastructure/NormalizedPath.swift
index fe686a0..e5d835f 100644
--- a/MacOSCleaner/Infrastructure/NormalizedPath.swift
+++ b/MacOSCleaner/Infrastructure/NormalizedPath.swift
@@ -79,4 +79,38 @@ public enum NormalizedPath {
public static func displayString(_ url: URL) -> String {
key(url)
}
+
+ /// Canonical path string with symlinks resolved and redundant slashes collapsed.
+ public static func resolvedString(_ path: String) -> String {
+ string(URL(fileURLWithPath: string(path)).standardizedFileURL.resolvingSymlinksInPath().standardizedFileURL.path)
+ }
+
+ /// Lowercased standardized key for APFS case-insensitive path matching.
+ public static func lowercaseKey(_ path: String) -> String {
+ string(URL(fileURLWithPath: string(path)).standardizedFileURL.path).lowercased()
+ }
+
+ /// Lowercased symlink-resolved key for APFS case-insensitive security checks.
+ public static func resolvedLowercaseKey(_ path: String) -> String {
+ resolvedString(path).lowercased()
+ }
+
+ /// True if `candidate` equals `root` or is a strict descendant of `root`.
+ public static func isEqualOrDescendant(_ candidate: String, of root: String, caseInsensitive: Bool = false) -> Bool {
+ let lhs = caseInsensitive ? candidate.lowercased() : candidate
+ let rhs = caseInsensitive ? root.lowercased() : root
+ if rhs == "/" {
+ return lhs == "/" || lhs.hasPrefix("/")
+ }
+ return lhs == rhs || lhs.hasPrefix(rhs + "/")
+ }
+
+ /// True if `candidate` is a strict ancestor of `root` (never equal).
+ public static func isStrictAncestor(_ candidate: String, of root: String, caseInsensitive: Bool = false) -> Bool {
+ let lhs = caseInsensitive ? candidate.lowercased() : candidate
+ let rhs = caseInsensitive ? root.lowercased() : root
+ guard lhs != rhs else { return false }
+ if lhs == "/" { return rhs.hasPrefix("/") && rhs != "/" }
+ return rhs.hasPrefix(lhs + "/")
+ }
}
diff --git a/MacOSCleaner/Infrastructure/PermissionsManager.swift b/MacOSCleaner/Infrastructure/PermissionsManager.swift
index fac1f4c..905ffec 100644
--- a/MacOSCleaner/Infrastructure/PermissionsManager.swift
+++ b/MacOSCleaner/Infrastructure/PermissionsManager.swift
@@ -40,69 +40,63 @@ public final class PermissionsManager {
}
}
- /// Checks if the application has Full Disk Access by attempting to read protected paths.
- public static func checkFullDiskAccess() -> Bool {
- let fm = FileManager.default
+ /// Target paths guarded by macOS TCC that only succeed when Full Disk Access is granted.
+ static func fdaProbeTargets(homeDirectory: String) -> (files: [String], directories: [String]) {
+ let files = [
+ "/Library/Application Support/com.apple.TCC/TCC.db",
+ homeDirectory + "/Library/Safari/CloudTabs.db",
+ homeDirectory + "/Library/Safari/Bookmarks.plist",
+ ]
+ let directories = [
+ homeDirectory + "/Library/Suggestions",
+ homeDirectory + "/Library/Mail",
+ homeDirectory + "/Library/Safari",
+ ]
+ return (files, directories)
+ }
- let timeMachine = "/Library/Preferences/com.apple.TimeMachine.plist"
- if fm.fileExists(atPath: timeMachine), let handle = FileHandle(forReadingAtPath: timeMachine) {
- try? handle.close()
- Logger.permissions.info("Full Disk Access check passed via Time Machine preferences")
- return true
- }
+ /// Checks if the application has Full Disk Access by attempting to read TCC-protected paths.
+ public static func checkFullDiskAccess(
+ homeDirectory: String = FileManager.default.homeDirectoryForCurrentUser.path
+ ) -> Bool {
+ let fm = FileManager.default
+ let targets = fdaProbeTargets(homeDirectory: homeDirectory)
- // 1. Check system TCC.db (POSIX 644 world-readable, guarded by macOS TCC)
- let systemTCC = "/Library/Application Support/com.apple.TCC/TCC.db"
- if fm.fileExists(atPath: systemTCC) {
- if let handle = FileHandle(forReadingAtPath: systemTCC) {
+ for file in targets.files {
+ guard fm.fileExists(atPath: file) else { continue }
+ if let handle = FileHandle(forReadingAtPath: file) {
try? handle.close()
- Logger.permissions.info("Full Disk Access check passed via system TCC.db")
+ Logger.permissions.debug("Full Disk Access check passed via file: \(file, privacy: .public)")
return true
}
}
- // 2. Check user-level TCC protected directories (listing requires FDA)
- let homeDir = fm.homeDirectoryForCurrentUser.path
- let userTCCDirs = [
- homeDir + "/Library/Suggestions",
- homeDir + "/Library/Mail"
- ]
- for dir in userTCCDirs {
+ for dir in targets.directories {
guard fm.fileExists(atPath: dir) else { continue }
do {
_ = try fm.contentsOfDirectory(atPath: dir)
- Logger.permissions.info("Full Disk Access check passed via directory: \(dir)")
+ Logger.permissions.debug("Full Disk Access check passed via directory: \(dir, privacy: .public)")
return true
} catch {
// Throws EPERM if FDA is not granted
}
}
- // 3. Check Safari protected files
- let safariFiles = [
- homeDir + "/Library/Safari/CloudTabs.db",
- homeDir + "/Library/Safari/Bookmarks.plist"
- ]
- for file in safariFiles {
- guard fm.fileExists(atPath: file) else { continue }
- if let handle = FileHandle(forReadingAtPath: file) {
- try? handle.close()
- Logger.permissions.info("Full Disk Access check passed via Safari file: \(file)")
- return true
- }
- }
-
- Logger.permissions.warning("Full Disk Access check: not granted")
+ Logger.permissions.debug("Full Disk Access check: not granted")
return false
}
/// Refreshes Full Disk Access status.
public func refresh() {
+ let previous = hasFullDiskAccess
let liveFDA = fdaCheckClosure()
hasFullDiskAccess = liveFDA
if liveFDA {
persistFDAState()
}
+ if liveFDA != previous {
+ Logger.permissions.info("Full Disk Access status changed: granted=\(liveFDA, privacy: .public)")
+ }
if hasFullDiskAccess && showGuidance {
showGuidance = false
@@ -111,6 +105,7 @@ public final class PermissionsManager {
/// Persists the Full Disk Access grant so the app remembers it across launches.
private func persistFDAState() {
+ guard !fdaEverGranted else { return }
fdaEverGranted = true
userDefaults.set(true, forKey: fdaGrantedKey)
Logger.permissions.info("Full Disk Access persisted as granted")
diff --git a/MacOSCleaner/Infrastructure/ProcessInfoProvider.swift b/MacOSCleaner/Infrastructure/ProcessInfoProvider.swift
index c3b98bd..f94da03 100644
--- a/MacOSCleaner/Infrastructure/ProcessInfoProvider.swift
+++ b/MacOSCleaner/Infrastructure/ProcessInfoProvider.swift
@@ -59,9 +59,12 @@ public actor ProcessInfoProvider {
let currentPID = ProcessInfo.processInfo.processIdentifier
guard pid != currentPID else { return nil }
+ let bsdInfo = getBSDInfo(for: pid)
let path = getPath(for: pid)
+ if bsdInfo == nil && path == nil {
+ return nil
+ }
let taskInfo = getTaskInfo(for: pid)
- let bsdInfo = getBSDInfo(for: pid)
let name: String
if let bsdInfo {
@@ -142,8 +145,7 @@ public actor ProcessInfoProvider {
pid, PROC_PIDTASKINFO, 0,
&info, Int32(MemoryLayout.size)
)
- if size != Int32(MemoryLayout.size) {
- logger.debug("proc_pidinfo(PROC_PIDTASKINFO) failed for pid \(pid): size=\(size)")
+ guard size == Int32(MemoryLayout.size) else {
return nil
}
return info
@@ -155,8 +157,7 @@ public actor ProcessInfoProvider {
pid, PROC_PIDTBSDINFO, 0,
&info, Int32(MemoryLayout.size)
)
- if size != Int32(MemoryLayout.size) {
- logger.debug("proc_pidinfo(PROC_PIDTBSDINFO) failed for pid \(pid): size=\(size)")
+ guard size == Int32(MemoryLayout.size) else {
return nil
}
return info
diff --git a/MacOSCleaner/Infrastructure/SafetyManager.swift b/MacOSCleaner/Infrastructure/SafetyManager.swift
index 5f951d7..c5e7034 100644
--- a/MacOSCleaner/Infrastructure/SafetyManager.swift
+++ b/MacOSCleaner/Infrastructure/SafetyManager.swift
@@ -18,15 +18,57 @@ public enum SafetyError: Error, Equatable, LocalizedError {
}
/// Context of a deletion request. Regular cleanup must never touch login/session
-/// data; a full app uninstall is allowed to remove the app's user data.
-public enum DeletionPolicy: Sendable {
+/// data; a full app uninstall is allowed to remove the app's user data only when
+/// the target belongs to the app being uninstalled.
+public enum DeletionPolicy: Sendable, Equatable {
case cleanup
case uninstall
+ case uninstallApp(bundleID: String?)
case userSelected
+
+ public var isUninstall: Bool {
+ switch self {
+ case .uninstall, .uninstallApp:
+ return true
+ case .cleanup, .userSelected:
+ return false
+ }
+ }
}
public struct SafetyManager: Sendable {
+ private enum BrowserCacheLayout: Sendable {
+ case chromium(channelSubdirs: Set = [])
+ case firefox
+ case safariLibrary
+ case browserContainer
+ case opaqueUserData
+ }
+
+ private struct BrowserRootSpec: Sendable {
+ let canonicalRoot: String
+ let lowerRoot: String
+ let ownerBundleIDs: Set
+ let layout: BrowserCacheLayout
+ let isSystemProtected: Bool
+
+ init(
+ root: String,
+ ownerBundleIDs: Set,
+ layout: BrowserCacheLayout,
+ isSystemProtected: Bool = false
+ ) {
+ let normalized = NormalizedPath.string(URL(fileURLWithPath: root).standardizedFileURL.path)
+ self.canonicalRoot = normalized
+ self.lowerRoot = normalized.lowercased()
+ self.ownerBundleIDs = Set(ownerBundleIDs.map { $0.lowercased() })
+ self.layout = layout
+ self.isSystemProtected = isSystemProtected
+ }
+ }
+
private let home: String
+ private let homeVariants: [String]
private let refuseList: [String]
private let allowedExceptions: [String]
private let customAllowedExceptions: [String]
@@ -40,26 +82,66 @@ public struct SafetyManager: Sendable {
// Directories that must never be deleted wholesale, though their children may be
// (e.g. ~/Library/Preferences itself vs. an app's plist inside it). Exact match only.
- private let exactRefuseList: Set
+ private let exactRefuseLowerMap: [String: String]
- // Browser user-data roots holding logins, cookies and site sessions.
- // Under .cleanup only well-known cache subdirectories inside them may be deleted.
- private let browserUserDataRoots: [String]
-
- // Lowercased directory names inside browser user-data roots that are safe caches.
- private let browserCacheDirNames: Set
+ // Browser user-data roots holding logins, cookies, extensions, and site sessions.
+ private let browserSpecs: [BrowserRootSpec]
// Lowercased basenames of credential/session files (Chromium family) protected
// anywhere under Application Support during cleanup.
private let credentialFileNames: Set
+ private static let chromiumRootCacheDirs: Set = [
+ "grshadercache", "shadercache", "graphite_dawn_cache", "crashpad",
+ ]
+ private static let chromiumProfileCacheDirs: Set = [
+ "cache", "code cache", "gpucache",
+ ]
+ private static let firefoxProfileCacheDirs: Set = [
+ "cache2", "startupcache", "thumbnails",
+ ]
+ private static let safariLibraryCacheDirs: Set = [
+ "favicon cache", "touch icons cache", "template icons",
+ ]
+ private static let browserProtectedSegments: Set = [
+ "extensions",
+ "extension state",
+ "extension rules",
+ "extension scripts",
+ "local extension settings",
+ "sync extension settings",
+ "managed extension settings",
+ "local extension storage",
+ "local storage",
+ "session storage",
+ "indexeddb",
+ "sync data",
+ "sessions",
+ "nativemessaginghosts",
+ "external extensions",
+ "databases",
+ "file system",
+ "blob_storage",
+ "shared_proto_db",
+ "autofillstrikedatabase",
+ "network",
+ "cookies",
+ "login data",
+ "web data",
+ ]
+
private let fileSystemContext: FileSystemContext?
public init(allowedExceptions: [String] = [], homeDirectory: String? = nil, fileSystemContext: FileSystemContext? = nil) {
- let home = homeDirectory
+ let rawHome = homeDirectory
?? fileSystemContext?.homePath
?? NSHomeDirectory()
- self.home = home
+ let stdHome = NormalizedPath.string(URL(fileURLWithPath: rawHome).standardizedFileURL.path)
+ let resolvedHome = NormalizedPath.resolvedString(stdHome)
+ let homeVariants = resolvedHome == stdHome ? [stdHome] : [stdHome, resolvedHome]
+
+ self.home = stdHome
+ self.homeVariants = homeVariants
self.fileSystemContext = fileSystemContext
self.immutableRefuseRoots = [
@@ -77,7 +159,7 @@ public struct SafetyManager: Sendable {
"/nix",
]
- self.refuseList = [
+ var refuse: [String] = [
"/System",
"/Library",
"/usr",
@@ -91,20 +173,24 @@ public struct SafetyManager: Sendable {
"/nix",
"/Applications",
"/Users/Shared",
- "\(home)/.ssh",
- "\(home)/.gnupg",
- "\(home)/Documents",
- "\(home)/Desktop",
- "\(home)/Downloads",
- "\(home)/Movies",
- "\(home)/Music",
- "\(home)/Pictures",
- "\(home)/Backups",
- "/",
]
+ for h in homeVariants {
+ refuse.append(contentsOf: [
+ "\(h)/.ssh",
+ "\(h)/.gnupg",
+ "\(h)/Documents",
+ "\(h)/Desktop",
+ "\(h)/Downloads",
+ "\(h)/Movies",
+ "\(h)/Music",
+ "\(h)/Pictures",
+ "\(h)/Backups",
+ ])
+ }
+ refuse.append("/")
+ self.refuseList = Self.dedupePreservingOrder(refuse)
- let defaultExceptions = [
- "\(home)/Library",
+ var defaultExceptions: [String] = [
"/Library/Application Support",
"/Library/LaunchAgents",
"/Library/LaunchDaemons",
@@ -129,18 +215,6 @@ public struct SafetyManager: Sendable {
"/Library/SystemExtensions",
"/Library/StagedExtensions",
"/Library/Preferences",
- "\(home)/Library/Application Support/MacOSCleaner",
- "\(home)/Library/Application Scripts/input.MacOSCleaner",
- "\(home)/Library/Caches",
- "\(home)/Library/Developer",
- "\(home)/Library/Logs",
- "\(home)/Library/Application Support",
- "\(home)/Library/Containers",
- "\(home)/Library/Android",
- "\(home)/Library/Safari",
- "\(home)/Library/WebKit",
- "\(home)/Library/Application Support/Google/Chrome",
- "\(home)/Library/Application Support/Chrome",
"/opt/homebrew/Cellar",
"/opt/homebrew/Caskroom",
"/usr/local/Cellar",
@@ -148,71 +222,116 @@ public struct SafetyManager: Sendable {
URL(fileURLWithPath: NSTemporaryDirectory()).standardizedFileURL.path,
URL(fileURLWithPath: NSTemporaryDirectory()).resolvingSymlinksInPath().standardizedFileURL.path,
]
+ for h in homeVariants {
+ defaultExceptions.append(contentsOf: [
+ "\(h)/Library",
+ "\(h)/Library/Application Support/MacOSCleaner",
+ "\(h)/Library/Application Scripts/input.MacOSCleaner",
+ "\(h)/Library/Caches",
+ "\(h)/Library/Developer",
+ "\(h)/Library/Logs",
+ "\(h)/Library/Application Support",
+ "\(h)/Library/Containers",
+ "\(h)/Library/Android",
+ "\(h)/Library/Safari",
+ "\(h)/Library/WebKit",
+ ])
+ }
self.customAllowedExceptions = allowedExceptions
- self.allowedExceptions = defaultExceptions + allowedExceptions
+ self.allowedExceptions = Self.dedupePreservingOrder(defaultExceptions + allowedExceptions)
- self.hardRefuseList = [
+ var hardRefuse: [String] = [
"/Library/Application Support/Apple",
"/Library/Application Support/Script Editor",
- "\(home)/Library/Application Support/Apple",
- "\(home)/Library/Keychains",
- "\(home)/Library/Calendars",
- "\(home)/Library/Reminders",
- "\(home)/Library/Contacts",
- "\(home)/Library/Application Support/AddressBook",
- "\(home)/Library/Messages",
- "\(home)/Library/Mobile Documents",
- "\(home)/Library/Preferences/com.google.Keystone.Agent.plist",
- "\(home)/Library/Google/GoogleSoftwareUpdate",
- "\(home)/Library/Application Support/Google/GoogleUpdater",
- "\(home)/Library/Caches/com.google.SoftwareUpdate",
- "\(home)/Library/Caches/com.google.GoogleUpdater",
- "\(home)/Library/HTTPStorages/com.google.GoogleUpdater",
- "\(home)/Library/LaunchAgents/com.google.keystone.agent.plist",
- "\(home)/Library/LaunchAgents/com.google.keystone.xpcservice.plist",
- "\(home)/Library/LaunchAgents/com.google.GoogleUpdater.wake.plist",
- "\(home)/Library/Application Support/Chrome/Default/Login Data",
- "\(home)/Library/Application Support/Chrome/Default/Cookies",
- "\(home)/Library/Application Support/Google/Chrome/Default/Login Data",
- "\(home)/Library/Application Support/Google/Chrome/Default/Cookies",
- "\(home)/Library/Application Support/com.apple.TCC",
"/Library/Application Support/com.apple.TCC",
"/var/db/dslocal",
"/private/var/db/dslocal",
- // Sensitive user credentials roots
- "\(home)/.ssh",
- "\(home)/.gnupg",
- ]
-
- let appSupport = "\(home)/Library/Application Support"
- self.browserUserDataRoots = [
- "\(appSupport)/Google/Chrome",
- "\(appSupport)/Google/Chrome Beta",
- "\(appSupport)/Google/Chrome Canary",
- "\(appSupport)/Google/Chrome Dev",
- "\(appSupport)/Chrome",
- "\(appSupport)/Chromium",
- "\(appSupport)/BraveSoftware",
- "\(appSupport)/Microsoft Edge",
- "\(appSupport)/Microsoft Edge Beta",
- "\(appSupport)/Microsoft Edge Canary",
- "\(appSupport)/Microsoft Edge Dev",
- "\(appSupport)/Arc/User Data",
- "\(appSupport)/Firefox/Profiles",
- "\(appSupport)/Vivaldi",
- "\(appSupport)/Yandex/YandexBrowser",
- "\(appSupport)/com.operasoftware.Opera",
- "\(appSupport)/com.operasoftware.OperaGX",
- "\(appSupport)/com.operasoftware.OperaDeveloperEdition",
]
- self.browserCacheDirNames = [
- "cache", "code cache", "gpucache",
- "shadercache", "grshadercache", "crashpad",
- // Narrow Service Worker: only CacheStorage / ScriptCache are regenerable caches.
- "cachestorage", "scriptcache",
- "cache2", "startupcache", "thumbnails",
+ for h in homeVariants {
+ hardRefuse.append(contentsOf: [
+ "\(h)/Library/Application Support/Apple",
+ "\(h)/Library/Keychains",
+ "\(h)/Library/Calendars",
+ "\(h)/Library/Reminders",
+ "\(h)/Library/Contacts",
+ "\(h)/Library/Application Support/AddressBook",
+ "\(h)/Library/Messages",
+ "\(h)/Library/Mobile Documents",
+ "\(h)/Library/Preferences/com.google.Keystone.Agent.plist",
+ "\(h)/Library/Google/GoogleSoftwareUpdate",
+ "\(h)/Library/Application Support/Google/GoogleUpdater",
+ "\(h)/Library/Caches/com.google.SoftwareUpdate",
+ "\(h)/Library/Caches/com.google.GoogleUpdater",
+ "\(h)/Library/HTTPStorages/com.google.GoogleUpdater",
+ "\(h)/Library/LaunchAgents/com.google.keystone.agent.plist",
+ "\(h)/Library/LaunchAgents/com.google.keystone.xpcservice.plist",
+ "\(h)/Library/LaunchAgents/com.google.GoogleUpdater.wake.plist",
+ "\(h)/Library/Application Support/Chrome/Default/Login Data",
+ "\(h)/Library/Application Support/Chrome/Default/Cookies",
+ "\(h)/Library/Application Support/Google/Chrome/Default/Login Data",
+ "\(h)/Library/Application Support/Google/Chrome/Default/Cookies",
+ "\(h)/Library/Application Support/com.apple.TCC",
+ "\(h)/.ssh",
+ "\(h)/.gnupg",
+ ])
+ }
+ self.hardRefuseList = Self.dedupePreservingOrder(hardRefuse)
+
+ var specs: [BrowserRootSpec] = [
+ BrowserRootSpec(
+ root: "/Library/Application Support/Google/Chrome",
+ ownerBundleIDs: [],
+ layout: .opaqueUserData,
+ isSystemProtected: true
+ ),
+ BrowserRootSpec(
+ root: "/Library/Google/Chrome",
+ ownerBundleIDs: [],
+ layout: .opaqueUserData,
+ isSystemProtected: true
+ ),
]
+ for h in homeVariants {
+ let appSupport = "\(h)/Library/Application Support"
+ specs.append(contentsOf: [
+ BrowserRootSpec(root: "\(appSupport)/Google/Chrome", ownerBundleIDs: ["com.google.chrome"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Google/Chrome Beta", ownerBundleIDs: ["com.google.chrome.beta"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Google/Chrome Canary", ownerBundleIDs: ["com.google.chrome.canary"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Google/Chrome Dev", ownerBundleIDs: ["com.google.chrome.dev"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Chrome", ownerBundleIDs: ["com.google.chrome"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Chromium", ownerBundleIDs: ["org.chromium.chromium"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/BraveSoftware/Brave-Browser", ownerBundleIDs: ["com.brave.browser"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/BraveSoftware/Brave-Browser-Beta", ownerBundleIDs: ["com.brave.browser.beta"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/BraveSoftware/Brave-Browser-Nightly", ownerBundleIDs: ["com.brave.browser.nightly"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Microsoft Edge", ownerBundleIDs: ["com.microsoft.edgemac"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Microsoft Edge Beta", ownerBundleIDs: ["com.microsoft.edgemac.beta"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Microsoft Edge Canary", ownerBundleIDs: ["com.microsoft.edgemac.canary"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Microsoft Edge Dev", ownerBundleIDs: ["com.microsoft.edgemac.dev"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Arc", ownerBundleIDs: ["company.thebrowser.browser"], layout: .chromium(channelSubdirs: ["user data"])),
+ BrowserRootSpec(root: "\(appSupport)/Firefox", ownerBundleIDs: ["org.mozilla.firefox", "org.mozilla.firefoxdeveloperedition", "org.mozilla.nightly"], layout: .firefox),
+ BrowserRootSpec(root: "\(appSupport)/Mozilla", ownerBundleIDs: ["org.mozilla.firefox", "org.mozilla.firefoxdeveloperedition", "org.mozilla.nightly"], layout: .firefox),
+ BrowserRootSpec(root: "\(appSupport)/Vivaldi", ownerBundleIDs: ["com.vivaldi.vivaldi"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Yandex", ownerBundleIDs: ["ru.yandex.desktop.yandex-browser"], layout: .chromium(channelSubdirs: ["yandexbrowser"])),
+ BrowserRootSpec(root: "\(appSupport)/com.operasoftware.Opera", ownerBundleIDs: ["com.operasoftware.opera"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/com.operasoftware.OperaGX", ownerBundleIDs: ["com.operasoftware.operagx"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/com.operasoftware.OperaDeveloperEdition", ownerBundleIDs: ["com.operasoftware.operadeveloperedition"], layout: .chromium()),
+ BrowserRootSpec(root: "\(appSupport)/Opera Software", ownerBundleIDs: ["com.operasoftware.opera", "com.operasoftware.operagx", "com.operasoftware.operadeveloperedition"], layout: .chromium(channelSubdirs: ["opera stable", "opera gx stable", "opera developer"])),
+ BrowserRootSpec(root: "\(appSupport)/Orion", ownerBundleIDs: ["com.kagi.kagimacos"], layout: .opaqueUserData),
+ BrowserRootSpec(root: "\(appSupport)/DuckDuckGo", ownerBundleIDs: ["com.duckduckgo.macos.browser"], layout: .opaqueUserData),
+ BrowserRootSpec(root: "\(appSupport)/TorBrowser-Data", ownerBundleIDs: ["org.torproject.torbrowser"], layout: .opaqueUserData),
+ BrowserRootSpec(root: "\(appSupport)/Waterfox", ownerBundleIDs: ["net.waterfox.waterfox"], layout: .firefox),
+ BrowserRootSpec(root: "\(appSupport)/LibreWolf", ownerBundleIDs: ["io.gitlab.librewolf-community"], layout: .firefox),
+ BrowserRootSpec(root: "\(appSupport)/MullvadBrowser", ownerBundleIDs: ["net.mullvad.mullvadbrowser"], layout: .firefox),
+ BrowserRootSpec(root: "\(h)/Library/Safari", ownerBundleIDs: [], layout: .safariLibrary, isSystemProtected: true),
+ BrowserRootSpec(root: "\(h)/Library/Containers/com.apple.Safari", ownerBundleIDs: [], layout: .browserContainer, isSystemProtected: true),
+ BrowserRootSpec(root: "\(h)/Library/WebKit/com.apple.Safari", ownerBundleIDs: [], layout: .opaqueUserData, isSystemProtected: true),
+ BrowserRootSpec(root: "\(h)/Library/Containers/com.duckduckgo.macos.browser", ownerBundleIDs: ["com.duckduckgo.macos.browser"], layout: .browserContainer),
+ BrowserRootSpec(root: "\(h)/Library/Containers/com.kagi.kagimacOS", ownerBundleIDs: ["com.kagi.kagimacos"], layout: .browserContainer),
+ ])
+ }
+ self.browserSpecs = specs
+
self.credentialFileNames = [
"login data", "login data for account", "cookies",
"web data", "account web data", "local state", "secure preferences",
@@ -222,36 +341,49 @@ public struct SafetyManager: Sendable {
"sessionstore.jsonlz4", "logins-backup.json",
]
- self.exactRefuseList = [
+ var exactRefuse: [String] = [
"/Users",
- home,
- "\(home)/Library",
- "\(home)/Library/Preferences",
- "\(home)/Library/Preferences/ByHost",
- "\(home)/Library/Application Support",
- "\(home)/Library/Caches",
- "\(home)/Library/Containers",
- "\(home)/Library/Group Containers",
- "\(home)/Library/Logs",
- "\(home)/Library/WebKit",
- "\(home)/Library/HTTPStorages",
- "\(home)/Library/Application Scripts",
- "\(home)/Library/Developer",
- "\(home)/Library/Messages",
- "\(home)/Library/Mobile Documents",
- "\(home)/Library/Cookies",
- "\(home)/Backups",
"/Library/Application Support",
"/Library/Preferences",
"/Library/LaunchAgents",
"/Library/LaunchDaemons",
"/Library/PrivilegedHelperTools",
- "\(home)/Library/LaunchAgents",
"/tmp",
"/private/tmp",
URL(fileURLWithPath: NSTemporaryDirectory()).standardizedFileURL.path,
URL(fileURLWithPath: NSTemporaryDirectory()).resolvingSymlinksInPath().standardizedFileURL.path,
]
+ for h in homeVariants {
+ exactRefuse.append(contentsOf: [
+ h,
+ "\(h)/Library",
+ "\(h)/Library/Preferences",
+ "\(h)/Library/Preferences/ByHost",
+ "\(h)/Library/Application Support",
+ "\(h)/Library/Caches",
+ "\(h)/Library/Containers",
+ "\(h)/Library/Group Containers",
+ "\(h)/Library/Logs",
+ "\(h)/Library/WebKit",
+ "\(h)/Library/HTTPStorages",
+ "\(h)/Library/Application Scripts",
+ "\(h)/Library/Developer",
+ "\(h)/Library/Messages",
+ "\(h)/Library/Mobile Documents",
+ "\(h)/Library/Cookies",
+ "\(h)/Backups",
+ "\(h)/Library/LaunchAgents",
+ ])
+ }
+ var exactMap: [String: String] = [:]
+ for item in exactRefuse {
+ let normalized = NormalizedPath.string(item)
+ let key = normalized.lowercased()
+ if exactMap[key] == nil {
+ exactMap[key] = normalized
+ }
+ }
+ self.exactRefuseLowerMap = exactMap
}
public func validate(url: URL, policy: DeletionPolicy = .cleanup) throws {
@@ -260,7 +392,7 @@ public struct SafetyManager: Sendable {
}
let standardized = url.standardizedFileURL
- let path = standardized.path
+ let path = NormalizedPath.string(standardized.path)
guard !path.isEmpty else {
throw SafetyError.pathNormalizationFailed
@@ -272,108 +404,131 @@ public struct SafetyManager: Sendable {
try validateSymlinkComponents(of: standardized)
- let resolvedPath = standardized.resolvingSymlinksInPath().path
- let pathsToCheck = [path, resolvedPath]
+ let resolvedPath = NormalizedPath.string(standardized.resolvingSymlinksInPath().standardizedFileURL.path)
+ let pathsToCheck = resolvedPath == path ? [path] : [path, resolvedPath]
for p in pathsToCheck {
- for refused in hardRefuseList where p == refused || p.hasPrefix(refused + "/") {
- throw SafetyError.protectedPath(refused)
+ let lowerP = p.lowercased()
+
+ for refused in hardRefuseList {
+ if NormalizedPath.isEqualOrDescendant(lowerP, of: refused.lowercased()) {
+ throw SafetyError.protectedPath(refused)
+ }
}
// Apple system group containers must never be removed
- if p == "\(home)/Library/Group Containers" {
- throw SafetyError.protectedPath(p)
- }
- if p.hasPrefix("\(home)/Library/Group Containers/group.com.apple")
- || p.hasPrefix("\(home)/Library/Group Containers/com.apple") {
- throw SafetyError.protectedPath("\(home)/Library/Group Containers")
+ for h in homeVariants {
+ let lowerGC = "\(h.lowercased())/library/group containers"
+ if lowerP == lowerGC {
+ throw SafetyError.protectedPath("\(h)/Library/Group Containers")
+ }
+ if lowerP.hasPrefix("\(lowerGC)/group.com.apple")
+ || lowerP.hasPrefix("\(lowerGC)/com.apple") {
+ throw SafetyError.protectedPath("\(h)/Library/Group Containers")
+ }
}
- if exactRefuseList.contains(p) {
- throw SafetyError.protectedPath(p)
+ if let exactRefused = exactRefuseLowerMap[lowerP] {
+ throw SafetyError.protectedPath(exactRefused)
}
// Protect ~/Library/Mail under uninstall unless inside ~/Library/Mail/Bundles
- if policy == .uninstall && (p == "\(home)/Library/Mail" || p.hasPrefix("\(home)/Library/Mail/")) {
- let bundles = "\(home)/Library/Mail/Bundles"
- if !(p == bundles || p.hasPrefix(bundles + "/")) {
- throw SafetyError.protectedPath("\(home)/Library/Mail")
+ if policy.isUninstall {
+ for h in homeVariants {
+ let lowerMail = "\(h.lowercased())/library/mail"
+ let lowerBundles = "\(h.lowercased())/library/mail/bundles"
+ if NormalizedPath.isEqualOrDescendant(lowerP, of: lowerMail)
+ && !NormalizedPath.isEqualOrDescendant(lowerP, of: lowerBundles) {
+ throw SafetyError.protectedPath("\(h)/Library/Mail")
+ }
}
}
- if policy == .cleanup, let refused = cleanupProtectedPath(p) {
+ if let refused = browserProtectedPath(p, lowerP: lowerP, policy: policy) {
+ throw SafetyError.protectedPath(refused)
+ }
+
+ if policy == .cleanup, let refused = cleanupProtectedPath(p, lowerPath: lowerP) {
throw SafetyError.protectedPath(refused)
}
// Under cleanup, home dot-directories are blocked unless they match an explicit
// regenerable cache in EmbeddedCleanupPaths, an opt-in AI model root, or custom exception.
if policy == .cleanup {
- let normalizedHome = home.hasSuffix("/") ? String(home.dropLast()) : home
- if p == "\(normalizedHome)/go/pkg/mod" {
- throw SafetyError.protectedPath(p)
- }
- if p.hasPrefix("\(normalizedHome)/.") && p != "\(normalizedHome)/.DS_Store" {
- let hasCustomException = customAllowedExceptions.contains { exception in
- p == exception || p.hasPrefix(exception + "/")
+ for h in homeVariants {
+ let trimmedHome = h.hasSuffix("/") ? String(h.dropLast()) : h
+ let lowerHome = trimmedHome.lowercased()
+ if lowerP == "\(lowerHome)/go/pkg/mod" {
+ throw SafetyError.protectedPath("\(trimmedHome)/go/pkg/mod")
}
- if !hasCustomException
- && !Self.isRegenerableCachePath(p, home: normalizedHome)
- && !Self.isReviewableAIModelPath(p, home: normalizedHome) {
- throw SafetyError.protectedPath(p)
+ if lowerP.hasPrefix("\(lowerHome)/.") && lowerP != "\(lowerHome)/.ds_store" {
+ let hasCustomException = customAllowedExceptions.contains { exception in
+ NormalizedPath.isEqualOrDescendant(lowerP, of: exception.lowercased())
+ }
+ if !hasCustomException
+ && !Self.isRegenerableCachePath(p, homeVariants: homeVariants)
+ && !Self.isReviewableAIModelPath(p, homeVariants: homeVariants) {
+ throw SafetyError.protectedPath(p)
+ }
}
}
}
// Custom exceptions never override immutable system / shared roots themselves.
// Only pre-declared narrow subpaths (Homebrew Cellar, /Library/LaunchAgents, …) may pass.
- if isUnderImmutableRefuseRoot(p) {
- if p == "/Applications" || p.hasPrefix("/Applications/") {
- if policy == .uninstall, p != "/Applications" {
+ if isUnderImmutableRefuseRoot(lowerP) {
+ if lowerP == "/applications" || lowerP.hasPrefix("/applications/") {
+ if policy.isUninstall, lowerP != "/applications" {
continue
}
throw SafetyError.protectedPath("/Applications")
}
let hasNarrowException = allowedExceptions.contains { exception in
- guard p == exception || p.hasPrefix(exception + "/") else { return false }
+ let lowerException = exception.lowercased()
+ guard NormalizedPath.isEqualOrDescendant(lowerP, of: lowerException) else { return false }
// Exception must be deeper than the immutable root (never the root itself).
- guard let root = immutableRefuseRoot(matching: exception) else { return false }
- return exception != root && exception.hasPrefix(root + "/")
+ guard let root = immutableRefuseRoot(matchingLowerPath: lowerException) else { return false }
+ return lowerException != root.lowercased() && lowerException.hasPrefix(root.lowercased() + "/")
}
if hasNarrowException {
continue
}
- throw SafetyError.protectedPath(immutableRefuseRoot(matching: p) ?? p)
+ throw SafetyError.protectedPath(immutableRefuseRoot(matchingLowerPath: lowerP) ?? p)
}
// Custom exceptions must never override user personal content roots.
- let isUserContentRoot = [
- "\(home)/Documents",
- "\(home)/Desktop",
- "\(home)/Downloads",
- "\(home)/Movies",
- "\(home)/Music",
- "\(home)/Pictures",
- "\(home)/Backups",
- ].contains { p == $0 || p.hasPrefix($0 + "/") }
+ let isUserContentRoot = homeVariants.contains { h in
+ [
+ "\(h)/Documents",
+ "\(h)/Desktop",
+ "\(h)/Downloads",
+ "\(h)/Movies",
+ "\(h)/Music",
+ "\(h)/Pictures",
+ "\(h)/Backups",
+ ].contains { NormalizedPath.isEqualOrDescendant(lowerP, of: $0.lowercased()) }
+ }
if policy == .userSelected {
- let isStrictUserContentDescendant = [
- "\(home)/Documents",
- "\(home)/Desktop",
- "\(home)/Downloads",
- "\(home)/Movies",
- "\(home)/Music",
- "\(home)/Pictures",
- "\(home)/Backups",
- ].contains { p.hasPrefix($0 + "/") }
+ let isStrictUserContentDescendant = homeVariants.contains { h in
+ [
+ "\(h)/Documents",
+ "\(h)/Desktop",
+ "\(h)/Downloads",
+ "\(h)/Movies",
+ "\(h)/Music",
+ "\(h)/Pictures",
+ "\(h)/Backups",
+ ].contains { lowerP.hasPrefix($0.lowercased() + "/") }
+ }
if isStrictUserContentDescendant {
continue
}
}
let isException = !isUserContentRoot && allowedExceptions.contains { exception in
- p == exception || p.hasPrefix(exception + "/")
+ NormalizedPath.isEqualOrDescendant(lowerP, of: exception.lowercased())
}
if isException {
@@ -381,10 +536,12 @@ public struct SafetyManager: Sendable {
}
// Regenerable project build artifacts / aged backup leaves under user project roots
- if Self.isProjectLocalBuildArtifact(p, home: home)
- || Self.isReviewableBackupLeaf(p, home: home)
- || Self.isReviewableInstallerLeaf(p, home: home)
- || Self.isReviewableLargeArchiveLeaf(p, home: home) {
+ if homeVariants.contains(where: {
+ Self.isProjectLocalBuildArtifact(p, home: $0)
+ || Self.isReviewableBackupLeaf(p, home: $0)
+ || Self.isReviewableInstallerLeaf(p, home: $0)
+ || Self.isReviewableLargeArchiveLeaf(p, home: $0)
+ }) {
continue
}
@@ -392,11 +549,16 @@ public struct SafetyManager: Sendable {
throw SafetyError.protectedPath(p)
}
+ if Self.isAllowedExternalVolumePath(p, policy: policy) {
+ continue
+ }
+
for refused in refuseList {
- let isExactMatch = (p == refused)
- let isSubdirectory = (refused == "/")
- ? (!p.hasPrefix(home + "/") && p != "/" && p.hasPrefix("/"))
- : p.hasPrefix(refused + "/")
+ let lowerRefused = refused.lowercased()
+ let isExactMatch = (lowerP == lowerRefused)
+ let isSubdirectory = (lowerRefused == "/")
+ ? (!homeVariants.contains { lowerP.hasPrefix($0.lowercased() + "/") } && lowerP != "/" && lowerP.hasPrefix("/"))
+ : lowerP.hasPrefix(lowerRefused + "/")
if isExactMatch {
throw SafetyError.protectedPath(refused)
@@ -404,7 +566,7 @@ public struct SafetyManager: Sendable {
guard isSubdirectory else { continue }
- if refused == "/Applications" && policy == .uninstall {
+ if lowerRefused == "/applications" && policy.isUninstall {
continue
}
@@ -415,8 +577,26 @@ public struct SafetyManager: Sendable {
/// True for paths inside (or being) a browser user-data root — logins, cookies, profiles.
public func isBrowserUserDataPath(_ path: String) -> Bool {
- let standardized = URL(fileURLWithPath: path).standardizedFileURL.path
- return browserUserDataRoots.contains { standardized == $0 || standardized.hasPrefix($0 + "/") }
+ let stdLower = NormalizedPath.lowercaseKey(path)
+ let resolvedLower = NormalizedPath.resolvedLowercaseKey(path)
+ return browserSpecs.contains { spec in
+ NormalizedPath.isEqualOrDescendant(stdLower, of: spec.lowerRoot)
+ || NormalizedPath.isEqualOrDescendant(resolvedLower, of: spec.lowerRoot)
+ }
+ }
+
+ /// True if uninstalling `bundleID` must not touch `path` because it is a browser user-data
+ /// root (or ancestor) owned by another browser or protected by the system.
+ public func isProtectedBrowserTarget(_ path: String, uninstallingBundleID bundleID: String?) -> Bool {
+ let std = NormalizedPath.string(URL(fileURLWithPath: path).standardizedFileURL.path)
+ let resolved = NormalizedPath.resolvedString(std)
+ let policy = DeletionPolicy.uninstallApp(bundleID: bundleID)
+ for candidate in [std, resolved] {
+ if browserProtectedPath(candidate, lowerP: candidate.lowercased(), policy: policy) != nil {
+ return true
+ }
+ }
+ return false
}
/// Whether a directory URL is a symlink and must not be traversed into.
@@ -428,12 +608,184 @@ public struct SafetyManager: Sendable {
return isSymlink(at: url)
}
- private func isUnderImmutableRefuseRoot(_ path: String) -> Bool {
- immutableRefuseRoots.contains { path == $0 || path.hasPrefix($0 + "/") }
+ private static let protectedExternalVolumeNames: Set = [
+ "recovery", "preboot", "vm", "update", "iscpreboot", "xarts",
+ "hardware", "base system", "macos base system", "timemachine",
+ ]
+ private static let protectedExternalVolumeSegments: Set = [
+ ".spotlight-v100", ".fseventsd", ".documentrevisions-v100",
+ ".trashes", ".temporaryitems", "backups.backupdb", ".vol", ".mobilebackups",
+ ]
+ private static let protectedExternalTopLevelDirs: Set = [
+ "system", "usr", "bin", "sbin", "private", "etc", "var", "dev", "cores",
+ ]
+
+ /// True if `volumeName` is a safe user-accessible mounted external volume (not hidden, system, or Time Machine).
+ public static func isAllowedExternalVolumeName(_ volumeName: String) -> Bool {
+ let trimmed = volumeName.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty, !trimmed.hasPrefix(".") else { return false }
+ let lower = trimmed.lowercased()
+ if protectedExternalVolumeNames.contains(lower) { return false }
+ if lower.contains("timemachine") || lower.contains("time machine") || lower.contains("backups.backupdb") {
+ return false
+ }
+ return true
}
- private func immutableRefuseRoot(matching path: String) -> String? {
- immutableRefuseRoots.first { path == $0 || path.hasPrefix($0 + "/") }
+ /// Allows explicit user-driven operations (`.uninstall`, `.uninstallApp`, `.userSelected`)
+ /// on files/apps inside a mounted non-root external volume (`/Volumes//`).
+ /// Automated `.cleanup` never operates on external volumes, and `/Volumes` or `/Volumes/`
+ /// mount roots themselves are always refused.
+ public static func isAllowedExternalVolumePath(_ path: String, policy: DeletionPolicy) -> Bool {
+ guard policy.isUninstall || policy == .userSelected else { return false }
+ let normalized = NormalizedPath.string(URL(fileURLWithPath: path).standardizedFileURL.path)
+ let components = normalized.split(separator: "/", omittingEmptySubsequences: true).map(String.init)
+ guard components.count >= 3, components[0].lowercased() == "volumes" else { return false }
+
+ let volumeName = components[1]
+ guard isAllowedExternalVolumeName(volumeName) else { return false }
+
+ let lowerComponents = components.dropFirst(2).map { $0.lowercased() }
+ if let top = lowerComponents.first, protectedExternalTopLevelDirs.contains(top) {
+ return false
+ }
+ if lowerComponents.contains(where: { protectedExternalVolumeSegments.contains($0) }) {
+ return false
+ }
+ let lowerPath = normalized.lowercased()
+ if lowerPath.contains("/library/application support/apple")
+ || lowerPath.contains("/library/application support/com.apple.tcc") {
+ return false
+ }
+ return true
+ }
+
+ private func browserProtectedPath(_ path: String, lowerP: String, policy: DeletionPolicy) -> String? {
+ // Strict ancestors of any browser root (e.g. ~/Library/Application Support/Google)
+ // must never be deleted wholesale under any policy.
+ for spec in browserSpecs where NormalizedPath.isStrictAncestor(lowerP, of: spec.lowerRoot) {
+ return path
+ }
+
+ // Check most specific matching spec (longest root wins if any overlap exists).
+ let matchingSpecs = browserSpecs
+ .filter { NormalizedPath.isEqualOrDescendant(lowerP, of: $0.lowerRoot) }
+ .sorted { $0.lowerRoot.count > $1.lowerRoot.count }
+
+ guard let spec = matchingSpecs.first else {
+ return nil
+ }
+
+ switch policy {
+ case .cleanup:
+ if lowerP == spec.lowerRoot {
+ return spec.canonicalRoot
+ }
+ return isAllowedBrowserCachePath(spec: spec, lowerP: lowerP) ? nil : path
+
+ case .uninstall:
+ // Generic uninstall without an owning app bundleID must never touch browser profiles.
+ return spec.canonicalRoot
+
+ case .uninstallApp(let bundleID):
+ guard !spec.isSystemProtected else {
+ return spec.canonicalRoot
+ }
+ guard let rawBundleID = bundleID?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !rawBundleID.isEmpty,
+ !BrowserRule.isBrowserPWAShimBundleID(rawBundleID)
+ else {
+ return spec.canonicalRoot
+ }
+ return spec.ownerBundleIDs.contains(rawBundleID.lowercased()) ? nil : spec.canonicalRoot
+
+ case .userSelected:
+ return spec.isSystemProtected ? spec.canonicalRoot : nil
+ }
+ }
+
+ private func isAllowedBrowserCachePath(spec: BrowserRootSpec, lowerP: String) -> Bool {
+ let relPath = String(lowerP.dropFirst(spec.lowerRoot.count))
+ let components = relPath.split(separator: "/", omittingEmptySubsequences: true).map(String.init)
+ guard !components.isEmpty else { return false }
+
+ if components.contains(where: { Self.browserProtectedSegments.contains($0) }) {
+ return false
+ }
+
+ switch spec.layout {
+ case .opaqueUserData:
+ if spec.isSystemProtected {
+ return false
+ }
+ return components[0] == "crashpad"
+
+ case .safariLibrary:
+ return Self.safariLibraryCacheDirs.contains(components[0])
+
+ case .browserContainer:
+ if components.count >= 3,
+ components[0] == "data",
+ components[1] == "library",
+ (components[2] == "caches" || components[2] == "logs") {
+ return true
+ }
+ if components.count >= 2,
+ components[0] == "data",
+ components[1] == "tmp" {
+ return true
+ }
+ return false
+
+ case .firefox:
+ if components[0] == "crashpad" {
+ return true
+ }
+ let idx = components[0] == "firefox" ? 1 : 0
+ guard components.count >= idx + 3 else { return false }
+ guard components[idx] == "profiles" else { return false }
+ return Self.firefoxProfileCacheDirs.contains(components[idx + 2])
+
+ case .chromium(let channelSubdirs):
+ let startIdx = channelSubdirs.contains(components[0]) ? 1 : 0
+ guard components.count > startIdx else { return false }
+
+ if Self.chromiumRootCacheDirs.contains(components[startIdx]) {
+ return true
+ }
+
+ guard components.count >= startIdx + 2 else { return false }
+ let profile = components[startIdx]
+ guard Self.isChromiumProfileDirName(profile) else { return false }
+
+ let dir = components[startIdx + 1]
+ if Self.chromiumProfileCacheDirs.contains(dir) {
+ return true
+ }
+ if dir == "service worker", components.count >= startIdx + 3 {
+ return components[startIdx + 2] == "cachestorage" || components[startIdx + 2] == "scriptcache"
+ }
+ return false
+ }
+ }
+
+ private static func isChromiumProfileDirName(_ lowerName: String) -> Bool {
+ lowerName == "default"
+ || lowerName == "guest profile"
+ || lowerName == "system profile"
+ || lowerName.hasPrefix("profile ")
+ }
+
+ private func isUnderImmutableRefuseRoot(_ lowerPath: String) -> Bool {
+ immutableRefuseRoots.contains {
+ NormalizedPath.isEqualOrDescendant(lowerPath, of: $0.lowercased())
+ }
+ }
+
+ private func immutableRefuseRoot(matchingLowerPath lowerPath: String) -> String? {
+ immutableRefuseRoots.first {
+ NormalizedPath.isEqualOrDescendant(lowerPath, of: $0.lowercased())
+ }
}
/// Walk each path component; intermediate symlink directories that escape are refused.
@@ -481,33 +833,13 @@ public struct SafetyManager: Sendable {
return (st.st_mode & S_IFMT) == S_IFLNK
}
- private func cleanupProtectedPath(_ path: String) -> String? {
- let lowerPath = path.lowercased()
-
+ private func cleanupProtectedPath(_ path: String, lowerPath: String) -> String? {
// Protect Mail wholesale during cleanup (never touch attachments or mailbox databases)
- if lowerPath == "\(home.lowercased())/library/mail" || lowerPath.hasPrefix("\(home.lowercased())/library/mail/") {
- return "\(home)/Library/Mail"
- }
-
- for root in browserUserDataRoots {
- if path == root || root.hasPrefix(path + "/") {
- return path
- }
- guard path.hasPrefix(root + "/") else { continue }
- let components = path.dropFirst(root.count + 1)
- .split(separator: "/")
- .map { $0.lowercased() }
- // Only CacheStorage / ScriptCache under Service Worker, not registration/state.
- if components.contains("service worker") {
- if components.contains("cachestorage") || components.contains("scriptcache") {
- return nil
- }
- return path
+ for h in homeVariants {
+ let lowerMail = "\(h.lowercased())/library/mail"
+ if NormalizedPath.isEqualOrDescendant(lowerPath, of: lowerMail) {
+ return "\(h)/Library/Mail"
}
- if components.contains(where: { browserCacheDirNames.contains($0) }) {
- return nil
- }
- return path
}
// Project settings and IDE configurations (e.g. .vscode, .idea, .zed)
@@ -586,26 +918,37 @@ public struct SafetyManager: Sendable {
/// True when `path` matches a known regenerable dot-cache template from `EmbeddedCleanupPaths`.
public static func isRegenerableCachePath(_ path: String, home: String) -> Bool {
- let standardized = URL(fileURLWithPath: path).standardizedFileURL.path
- let baseHome = home.hasSuffix("/") ? String(home.dropLast()) : home
- for template in EmbeddedCleanupPaths.regenerableDotCacheTemplates() {
- let resolved = template.hasPrefix("~") ? baseHome + template.dropFirst() : template
- let normalized = URL(fileURLWithPath: resolved).standardizedFileURL.path
- if standardized == normalized || standardized.hasPrefix(normalized + "/") {
- return true
+ let stdHome = NormalizedPath.string(URL(fileURLWithPath: home).standardizedFileURL.path)
+ let resolvedHome = NormalizedPath.resolvedString(stdHome)
+ let variants = resolvedHome == stdHome ? [stdHome] : [stdHome, resolvedHome]
+ return isRegenerableCachePath(path, homeVariants: variants)
+ }
+
+ private static func isRegenerableCachePath(_ path: String, homeVariants: [String]) -> Bool {
+ let lowerPath = NormalizedPath.lowercaseKey(path)
+ for h in homeVariants {
+ let baseHome = h.hasSuffix("/") ? String(h.dropLast()) : h
+ for template in EmbeddedCleanupPaths.regenerableDotCacheTemplates() {
+ let resolved = template.hasPrefix("~") ? baseHome + template.dropFirst() : template
+ let lowerTarget = NormalizedPath.lowercaseKey(resolved)
+ if NormalizedPath.isEqualOrDescendant(lowerPath, of: lowerTarget) {
+ return true
+ }
}
}
return false
}
- private static func isReviewableAIModelPath(_ path: String, home: String) -> Bool {
- let standardized = URL(fileURLWithPath: path).standardizedFileURL.path
- let baseHome = home.hasSuffix("/") ? String(home.dropLast()) : home
- for template in GeneratedCleanupPaths.aiUserContentTemplates() {
- let resolved = PathToken.home.resolveTemplate(template, home: baseHome)
- let normalized = URL(fileURLWithPath: resolved).standardizedFileURL.path
- if standardized == normalized || standardized.hasPrefix(normalized + "/") {
- return true
+ private static func isReviewableAIModelPath(_ path: String, homeVariants: [String]) -> Bool {
+ let lowerPath = NormalizedPath.lowercaseKey(path)
+ for h in homeVariants {
+ let baseHome = h.hasSuffix("/") ? String(h.dropLast()) : h
+ for template in GeneratedCleanupPaths.aiUserContentTemplates() {
+ let resolved = PathToken.home.resolveTemplate(template, home: baseHome)
+ let lowerTarget = NormalizedPath.lowercaseKey(resolved)
+ if NormalizedPath.isEqualOrDescendant(lowerPath, of: lowerTarget) {
+ return true
+ }
}
}
return false
@@ -623,13 +966,13 @@ public struct SafetyManager: Sendable {
/// Never allows `~/Backups` or arbitrary nested user content.
static func isReviewableBackupLeaf(_ path: String, home: String) -> Bool {
let standardized = URL(fileURLWithPath: path).standardizedFileURL
- let parent = standardized.deletingLastPathComponent().path
+ let parentLower = standardized.deletingLastPathComponent().path.lowercased()
let allowedParents = [
"\(home)/Desktop",
"\(home)/Documents",
"\(home)/Downloads",
- ].map { URL(fileURLWithPath: $0).standardizedFileURL.path }
- guard allowedParents.contains(parent) else { return false }
+ ].map { NormalizedPath.lowercaseKey($0) }
+ guard allowedParents.contains(parentLower) else { return false }
let name = standardized.lastPathComponent.lowercased()
return name.hasSuffix(".backup")
@@ -668,20 +1011,20 @@ public struct SafetyManager: Sendable {
private static func reviewableDownloadLeafName(_ path: String, home: String) -> String? {
let standardized = URL(fileURLWithPath: path).standardizedFileURL
- let parent = standardized.deletingLastPathComponent().path
+ let parentLower = standardized.deletingLastPathComponent().path.lowercased()
let allowedParents = [
"\(home)/Desktop",
"\(home)/Documents",
"\(home)/Downloads",
- ].map { URL(fileURLWithPath: $0).standardizedFileURL.path }
- guard allowedParents.contains(parent) else { return nil }
+ ].map { NormalizedPath.lowercaseKey($0) }
+ guard allowedParents.contains(parentLower) else { return nil }
return standardized.lastPathComponent.lowercased()
}
private static func isMessengerOrHomebrewInstallerPath(_ standardizedPath: String, home: String) -> Bool {
let baseHome = URL(fileURLWithPath: home).standardizedFileURL.path
- let parent = URL(fileURLWithPath: standardizedPath).deletingLastPathComponent().path
- let exactDownloadDirs: Set = [
+ let parentLower = URL(fileURLWithPath: standardizedPath).deletingLastPathComponent().path.lowercased()
+ let exactDownloadDirs: Set = Set([
"\(baseHome)/Library/Caches/Homebrew/downloads",
"\(baseHome)/Library/Application Support/Slack/Downloads",
"\(baseHome)/Library/Containers/com.tinyspeck.slackmacgap/Data/Downloads",
@@ -690,14 +1033,23 @@ public struct SafetyManager: Sendable {
"\(baseHome)/Library/Containers/net.whatsapp.WhatsApp/Data/Downloads",
"\(baseHome)/Library/Containers/net.whatsapp.WhatsApp/Data/Library/Application Support/WhatsApp/Downloads",
"\(baseHome)/Library/Group Containers/group.net.whatsapp.WhatsApp.shared/Message/Media",
- ]
- if exactDownloadDirs.contains(parent) {
+ ].map { $0.lowercased() })
+ if exactDownloadDirs.contains(parentLower) {
return true
}
- let telegramRoot = "\(baseHome)/Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram/"
- if parent.hasPrefix(telegramRoot) && parent.hasSuffix("/postbox/media") {
+ let telegramRoot = "\(baseHome)/Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram/".lowercased()
+ if parentLower.hasPrefix(telegramRoot) && parentLower.hasSuffix("/postbox/media") {
return true
}
return false
}
+
+ private static func dedupePreservingOrder(_ paths: [String]) -> [String] {
+ var seen = Set()
+ var result: [String] = []
+ for path in paths where seen.insert(path).inserted {
+ result.append(path)
+ }
+ return result
+ }
}
diff --git a/MacOSCleaner/Infrastructure/SpotlightMetadata.swift b/MacOSCleaner/Infrastructure/SpotlightMetadata.swift
new file mode 100644
index 0000000..e6eac40
--- /dev/null
+++ b/MacOSCleaner/Infrastructure/SpotlightMetadata.swift
@@ -0,0 +1,76 @@
+import CoreServices
+import Foundation
+
+/// Safe wrapper over Spotlight `MDItem*` APIs.
+/// When Spotlight indexing is disabled (`mdutil -a -i off`), `MDItemCreate` returns `nil`;
+/// passing `nil` to `MDItemCopyAttribute` crashes with a memory error.
+public enum SpotlightMetadata {
+ private struct Provider: Sendable {
+ let isIndexingAvailable: @Sendable (String) -> Bool
+ let lastUsedDate: @Sendable (URL) -> Date?
+ }
+
+ private final class State: @unchecked Sendable {
+ let lock = NSLock()
+ var overrideProvider: Provider?
+ }
+
+ private static let state = State()
+
+ private static let productionProvider = Provider(
+ isIndexingAvailable: { path in
+ let probePath = FileManager.default.fileExists(atPath: path) ? path : "/Applications"
+ if MDItemCreate(nil, probePath as CFString) != nil {
+ return true
+ }
+ return MDItemCreate(nil, "/System/Applications" as CFString) != nil
+ },
+ lastUsedDate: { url in
+ guard let mdItem = MDItemCreate(nil, url.path as CFString) else {
+ return nil
+ }
+ return MDItemCopyAttribute(mdItem, kMDItemLastUsedDate) as? Date
+ }
+ )
+
+ private static var activeProvider: Provider {
+ state.lock.lock()
+ defer { state.lock.unlock() }
+ return state.overrideProvider ?? productionProvider
+ }
+
+ public static func isIndexingAvailable(at path: String = NSHomeDirectory()) -> Bool {
+ activeProvider.isIndexingAvailable(path)
+ }
+
+ /// Returns Spotlight's `kMDItemLastUsedDate` when available, falling back to filesystem
+ /// `contentAccessDate` when Spotlight is disabled or unindexed, or `nil` if unknown.
+ public static func lastUsedDate(for url: URL) -> Date? {
+ if let spotlightDate = activeProvider.lastUsedDate(url) {
+ return spotlightDate
+ }
+ return (try? url.resourceValues(forKeys: [.contentAccessDateKey]))?.contentAccessDate
+ }
+
+ /// Test seam — overrides Spotlight probes to simulate `mdutil -a -i off` or synthetic dates.
+ static func setOverrideForTesting(
+ isIndexingAvailable: (@Sendable (String) -> Bool)? = nil,
+ lastUsedDate: (@Sendable (URL) -> Date?)? = nil
+ ) {
+ state.lock.lock()
+ defer { state.lock.unlock() }
+ if isIndexingAvailable == nil && lastUsedDate == nil {
+ state.overrideProvider = nil
+ } else {
+ let base = productionProvider
+ state.overrideProvider = Provider(
+ isIndexingAvailable: isIndexingAvailable ?? base.isIndexingAvailable,
+ lastUsedDate: lastUsedDate ?? base.lastUsedDate
+ )
+ }
+ }
+
+ static func resetForTesting() {
+ setOverrideForTesting()
+ }
+}
diff --git a/MacOSCleaner/MacOSCleaner.xcodeproj/project.pbxproj b/MacOSCleaner/MacOSCleaner.xcodeproj/project.pbxproj
index a1429e5..5e4c425 100644
--- a/MacOSCleaner/MacOSCleaner.xcodeproj/project.pbxproj
+++ b/MacOSCleaner/MacOSCleaner.xcodeproj/project.pbxproj
@@ -20,10 +20,12 @@
0949E633A8B50FC53569593A /* NavigationRailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 267C8C93E377155321CB29E5 /* NavigationRailView.swift */; };
09824927A11CC992B106D4CD /* ProcessInfoProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37A116D669586B4CCC7108FC /* ProcessInfoProvider.swift */; };
0C6462E222FBB78EEDB1E781 /* CleanupEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7F3794501798DF583436B09 /* CleanupEngine.swift */; };
+ 0D628AAD81B4CE2F0FAC2F47 /* CachedFileIconView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79E5453A30CC9E63BD51AD07 /* CachedFileIconView.swift */; };
0D71B75F7521BAECEAEF7119 /* DockerRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C8AC033173B97C266D97DF2 /* DockerRule.swift */; };
0EC337EF82F7F025681B3725 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 725A7CDFB17CB2FC1AC59560 /* Assets.xcassets */; };
0F49E436FD65F782BFFD75D4 /* IntentCleanupRunner.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED69987E7FC019A219261B04 /* IntentCleanupRunner.swift */; };
11A7D2871426F39EFA6D740B /* EvidenceProbeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5ED4199D09AC66B4B220BDC8 /* EvidenceProbeTests.swift */; };
+ 15A8DDD1B7953B44C4E56D51 /* SpotlightMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2BFF8AAC9BBCBA519C5A3EC /* SpotlightMetadata.swift */; };
162CB83D7194D6BD718593A0 /* CommandRunning.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9BB7DDAA6BEB78C47B1EAD3 /* CommandRunning.swift */; };
1665896332214762C62ED272 /* EpicGames.json in Resources */ = {isa = PBXBuildFile; fileRef = 26A12A1159CFA31A969B390C /* EpicGames.json */; };
1B1A4ECA59DA1C797866ED70 /* DuplicatesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 103AADAB692813C6D04C0E97 /* DuplicatesView.swift */; };
@@ -58,6 +60,7 @@
338946DFC3F61C72FCC52D5E /* AdobeRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A8D50E5702E806D30909278 /* AdobeRule.swift */; };
34D1B8763C0163ACA7381A89 /* ForeignDeveloperTreeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D4251DA018132DF4D638D81 /* ForeignDeveloperTreeTests.swift */; };
354AAEA23A1C58900843BF36 /* AppQuitter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32353266D095839796FBAC34 /* AppQuitter.swift */; };
+ 359A5D8064F96042B6D5FBF0 /* AppIconCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0CDAB14905C0320EC2F6F8A /* AppIconCache.swift */; };
370555A1E46A82B05D6374B0 /* CleanupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16400AE1862B76A844B01CFC /* CleanupView.swift */; };
38463081179925B73D842021 /* GetStorageStatusIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAB97CBC44CD5A5FE9BCD2B9 /* GetStorageStatusIntent.swift */; };
3922CCC01F73A38F68A94C2A /* PosixScanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = F514077EE94AA6AF042FE5B0 /* PosixScanner.swift */; };
@@ -99,6 +102,7 @@
5805C9625FA33C2762194266 /* MockCommandRunner.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8F77DB5F928748036C709D4 /* MockCommandRunner.swift */; };
593544F1466D0044893E58C3 /* SettingsComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = F44FD61E268AB84EE05CE97A /* SettingsComponents.swift */; };
597C46E020148F9810D9763B /* FinalCutProRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18DB8F9D655F658EFAE5FCA3 /* FinalCutProRule.swift */; };
+ 5A37285FA27E2643E72AFE01 /* WorkspaceStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAB123331AB8158A17DD2D05 /* WorkspaceStore.swift */; };
5A80FF0AAC67C55F53950A6A /* OperationRisk.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C739CAEB68AC6D0D4EF63BD /* OperationRisk.swift */; };
5D2C3AC6D520ED512CFDE893 /* AboutView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4036BE6AD403CC0E552B386A /* AboutView.swift */; };
60B681FF2018B69AE6F42A8E /* PermissionsManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70E3A139737CC8A7ECBD1900 /* PermissionsManager.swift */; };
@@ -135,7 +139,10 @@
852AC0C436784EF858B714D0 /* SettingsAutomationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E40B2438A97B18D4B6418C2C /* SettingsAutomationView.swift */; };
87EDEF516A814FC99DCA0B31 /* BackgroundItemsReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70C3847C35AB0FA0E8C80210 /* BackgroundItemsReader.swift */; };
89BAEC96A8994A5092900B77 /* LiquidGlass+Compatibility.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F30EB8C917D9A5DB59EB765 /* LiquidGlass+Compatibility.swift */; };
+ 8BCC68E6073167D5461A58D8 /* PreReleaseAuditTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9D97AF5D11A34E4AE0B853F /* PreReleaseAuditTests.swift */; };
+ 8C793CF8075DF8122AD8A90C /* CrashSignalHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA9CA5A89EB62AA27FA5D524 /* CrashSignalHandler.swift */; };
8E3DECCD5B86A373058DED54 /* StartupServicesViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0086F9F7800BFD540E5F25E /* StartupServicesViewModel.swift */; };
+ 8E41A27853E6D68E9FEF0A4C /* ResidualScanIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 188DC3E0ED256C5925C31FF1 /* ResidualScanIndex.swift */; };
8E85254D5D4361719099D2E9 /* LiveResidualAuditTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1157C1A1D919A5A05D6F76FE /* LiveResidualAuditTests.swift */; };
8F1C2ACF00DF4A34A6CA9862 /* AnimatedScanView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C6703835CE5100161449E56 /* AnimatedScanView.swift */; };
92E0F73F02E1797F191A0BCD /* RaycastRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB502AA9A1CC1FB93686DC00 /* RaycastRule.swift */; };
@@ -219,6 +226,7 @@
D664F8B31004BF2B0D3B1560 /* NordVPN.json in Resources */ = {isa = PBXBuildFile; fileRef = DD4DB6F7DA427DA269274700 /* NordVPN.json */; };
D768D4102DD98AD91B8F4EEA /* CandidateCollectorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF1797889E54A02B080F3BE6 /* CandidateCollectorTests.swift */; };
D8118B025E0B8314EC7AF314 /* HelperAppCollapser.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD67C865E2D4BF1DF1A3E454 /* HelperAppCollapser.swift */; };
+ D9FF841D6649E7C18A2FCA37 /* ScanStatusPill.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB348303094A1F0694628051 /* ScanStatusPill.swift */; };
DA751D9D2C2235BC30A8039B /* DiskScannerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F8E546AF7573B471B314407 /* DiskScannerTests.swift */; };
DDF1A3BD13DF7AA1C39EA144 /* LaunchServiceManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE5A3FFB9EF8E6D7D62FD68D /* LaunchServiceManager.swift */; };
DE4F65F07814A5139023D54F /* SystemInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 180E53446953349EB5FB2E04 /* SystemInfo.swift */; };
@@ -252,6 +260,7 @@
F094BF7BF4EA75B947A0DF3F /* DuplicateFinderEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 340615D1892577153030AAAC /* DuplicateFinderEngine.swift */; };
F0AC9987DA2D81F6707391FE /* SettingsCleanupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C98C7B7FC3C6CF1967423B7 /* SettingsCleanupView.swift */; };
F1F55759F1B26018639582D4 /* PrivacyView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7BB84FF2DB8D04CE58CA964 /* PrivacyView.swift */; };
+ F3560430362797A000BFF43F /* UninstallerViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39F1CD42DCCDEF1ECC4F8E2F /* UninstallerViewModel.swift */; };
F5CE26A3F2741242F54A0428 /* PrivacyModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9436DABA958A58B51BA1581D /* PrivacyModels.swift */; };
F66F8B5C81F0594E86965308 /* ConfidenceEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21CB088C6253EADF3B4E7AE7 /* ConfidenceEngine.swift */; };
F6FA71CE2DE763D8605DE9B9 /* CommandCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9B27F13D467CB9E08F5B350 /* CommandCache.swift */; };
@@ -299,6 +308,7 @@
1587E61B0489D075EE10BA3D /* AppSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppSettings.swift; sourceTree = ""; };
16400AE1862B76A844B01CFC /* CleanupView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CleanupView.swift; sourceTree = ""; };
180E53446953349EB5FB2E04 /* SystemInfo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SystemInfo.swift; sourceTree = ""; };
+ 188DC3E0ED256C5925C31FF1 /* ResidualScanIndex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResidualScanIndex.swift; sourceTree = ""; };
18DB8F9D655F658EFAE5FCA3 /* FinalCutProRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FinalCutProRule.swift; sourceTree = ""; };
197DA9FDB4A034B4100A2AFB /* AppDiscovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDiscovery.swift; sourceTree = ""; };
19CCFAD2C8F9A825ED7D6932 /* Stage3RegressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Stage3RegressionTests.swift; sourceTree = ""; };
@@ -336,6 +346,7 @@
37A116D669586B4CCC7108FC /* ProcessInfoProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProcessInfoProvider.swift; sourceTree = ""; };
37CE50232E4BB5BDF0EDB99C /* known_residual_catalog_snapshot.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = known_residual_catalog_snapshot.json; sourceTree = ""; };
3969A61F0C8E47F833E258AB /* PrivacyViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrivacyViewModel.swift; sourceTree = ""; };
+ 39F1CD42DCCDEF1ECC4F8E2F /* UninstallerViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UninstallerViewModel.swift; sourceTree = ""; };
3A0F61F1833BCBAD84509BE0 /* LogicProRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogicProRule.swift; sourceTree = ""; };
3A8D50E5702E806D30909278 /* AdobeRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AdobeRule.swift; sourceTree = ""; };
3A917B441A9E588D76A1B96E /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = ""; };
@@ -413,6 +424,7 @@
78EEF9CB2BE762A51083464F /* FileManager+Size.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FileManager+Size.swift"; sourceTree = ""; };
78F806B7312BFC1297D8E172 /* DirectorySizeCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectorySizeCache.swift; sourceTree = ""; };
78FDC715A4051976C6D377DF /* ProjectArtifactRules.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProjectArtifactRules.swift; sourceTree = ""; };
+ 79E5453A30CC9E63BD51AD07 /* CachedFileIconView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CachedFileIconView.swift; sourceTree = ""; };
7A3CAAC952028CD7C4FAFCF7 /* SettingsAdvancedView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsAdvancedView.swift; sourceTree = ""; };
7B1DD590DCE0D34A3129D242 /* CommandRunner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandRunner.swift; sourceTree = ""; };
7BA3A02A464DC643AB220B58 /* JetBrainsRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JetBrainsRule.swift; sourceTree = ""; };
@@ -447,6 +459,7 @@
9F655CB3931FC097B4A8836C /* VerificationEngineTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VerificationEngineTests.swift; sourceTree = ""; };
9FE18494B602F06C4A577ABB /* WeightABTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeightABTests.swift; sourceTree = ""; };
A09871694E5D848CE7929087 /* LocalizationCompletenessTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalizationCompletenessTests.swift; sourceTree = ""; };
+ A2BFF8AAC9BBCBA519C5A3EC /* SpotlightMetadata.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpotlightMetadata.swift; sourceTree = ""; };
A3BC06C9BBE41099A9D54344 /* AppIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppIdentity.swift; sourceTree = ""; };
A5EFE9DE1E343AF8F2490C67 /* DashboardViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardViewModel.swift; sourceTree = ""; };
A9B27F13D467CB9E08F5B350 /* CommandCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandCache.swift; sourceTree = ""; };
@@ -477,6 +490,7 @@
BE06D2D275499CE3A8A513EF /* UnityRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnityRule.swift; sourceTree = ""; };
BFC6DDA4FC825892B619F2CD /* UpdateChecker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateChecker.swift; sourceTree = ""; };
C00863531D986D093838A6B3 /* pl */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = pl; path = pl.lproj/Localizable.strings; sourceTree = ""; };
+ C0CDAB14905C0320EC2F6F8A /* AppIconCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppIconCache.swift; sourceTree = ""; };
C1C7373D2284E648D835B122 /* ProcessManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProcessManager.swift; sourceTree = ""; };
C26CC1A76E88A0BBF3B47E5A /* CodeSignatureInfo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeSignatureInfo.swift; sourceTree = ""; };
C4675926C2C0B155F7EF8126 /* DuplicateFileItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DuplicateFileItem.swift; sourceTree = ""; };
@@ -504,6 +518,7 @@
D8F77DB5F928748036C709D4 /* MockCommandRunner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCommandRunner.swift; sourceTree = ""; };
D976632F4535BD8561654197 /* ElectronRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ElectronRule.swift; sourceTree = ""; };
DA8B28911DC4508EB90A34A5 /* Arc.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = Arc.json; sourceTree = ""; };
+ DA9CA5A89EB62AA27FA5D524 /* CrashSignalHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CrashSignalHandler.swift; sourceTree = ""; };
DAB05B780E52D2EA5A76D570 /* XcodeRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = XcodeRule.swift; sourceTree = ""; };
DB52F3DF71B7B07A274D5E20 /* LaunchdControl.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LaunchdControl.swift; sourceTree = ""; };
DBA64165D2FBAC03ACE56DC6 /* ConfidenceEngineTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfidenceEngineTests.swift; sourceTree = ""; };
@@ -541,6 +556,9 @@
F6F9B22B36D401D28509CF70 /* ArtifactClassifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactClassifier.swift; sourceTree = ""; };
F7DCEB09D6881AEFA6981530 /* DockTileManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DockTileManager.swift; sourceTree = ""; };
F9D80391D31B2181E0D29B17 /* ScoringWeights.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoringWeights.swift; sourceTree = ""; };
+ F9D97AF5D11A34E4AE0B853F /* PreReleaseAuditTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PreReleaseAuditTests.swift; sourceTree = ""; };
+ FAB123331AB8158A17DD2D05 /* WorkspaceStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceStore.swift; sourceTree = ""; };
+ FB348303094A1F0694628051 /* ScanStatusPill.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScanStatusPill.swift; sourceTree = ""; };
FB93BAD2C057E76B2E0DBD80 /* CommandRunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandRunnerTests.swift; sourceTree = ""; };
FBAF8D65EF28A9DB89B6020A /* GeneratedCleanupPaths.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneratedCleanupPaths.swift; sourceTree = ""; };
FBE143C9DCB1484CADF91FF1 /* OrphanedResidualsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrphanedResidualsView.swift; sourceTree = ""; };
@@ -686,6 +704,7 @@
32C30D4CD2BF26C221E7FFBB /* OrphanScannerTests.swift */,
637D5DB2746C5365E95163AC /* PathTokenNormalizeTests.swift */,
8EEC779D41CFF0EB28C98F7C /* PermissionsManagerTests.swift */,
+ F9D97AF5D11A34E4AE0B853F /* PreReleaseAuditTests.swift */,
64D599678A74F74F9971F86A /* PrivacyTests.swift */,
F26F6770FD70ABF80ADDB3D2 /* PrivateCatalogLoaderTests.swift */,
DBAB945DBFACF08A8FE86FB4 /* PrivilegedScriptTests.swift */,
@@ -819,10 +838,12 @@
44C2514ADFBB5E6A83A2FB55 /* ParentLinker.swift */,
9F3C14ACE1F94B5CA8FFCEAC /* PostUninstallLeftoversSheet.swift */,
543E2F8CAD125A9356D10CCB /* RegistryPathTemplates.swift */,
+ 188DC3E0ED256C5925C31FF1 /* ResidualScanIndex.swift */,
F9D80391D31B2181E0D29B17 /* ScoringWeights.swift */,
5D23B7F7FCB2071E33A02DE4 /* UIMetadataProvider.swift */,
6B3C1F6747CB777D0BD96AF9 /* UninstallerService.swift */,
55FC1AE8DD7419C6804C170D /* UninstallerView.swift */,
+ 39F1CD42DCCDEF1ECC4F8E2F /* UninstallerViewModel.swift */,
E18410CA889BB8667BE08176 /* VerificationEngine.swift */,
6BCE01589664A4F3C4EA3182 /* VerificationReport.swift */,
B9FD9F355181631D203038E5 /* Caches */,
@@ -981,9 +1002,11 @@
CF272FC6297E9EB5BF6CAC7A /* Infrastructure */ = {
isa = PBXGroup;
children = (
+ C0CDAB14905C0320EC2F6F8A /* AppIconCache.swift */,
A9B27F13D467CB9E08F5B350 /* CommandCache.swift */,
7B1DD590DCE0D34A3129D242 /* CommandRunner.swift */,
B9BB7DDAA6BEB78C47B1EAD3 /* CommandRunning.swift */,
+ DA9CA5A89EB62AA27FA5D524 /* CrashSignalHandler.swift */,
78F806B7312BFC1297D8E172 /* DirectorySizeCache.swift */,
BCD1414A4103E729B6946047 /* FileCleanupActor.swift */,
78EEF9CB2BE762A51083464F /* FileManager+Size.swift */,
@@ -1002,6 +1025,7 @@
37A116D669586B4CCC7108FC /* ProcessInfoProvider.swift */,
78FDC715A4051976C6D377DF /* ProjectArtifactRules.swift */,
4EA68BEDE6F540E3477849FC /* SafetyManager.swift */,
+ A2BFF8AAC9BBCBA519C5A3EC /* SpotlightMetadata.swift */,
0F6BA430DBA22418A7A0D0D8 /* String+Localization.swift */,
180E53446953349EB5FB2E04 /* SystemInfo.swift */,
93C5FD8CA29FB9E59A400223 /* TrashManager.swift */,
@@ -1023,8 +1047,10 @@
E20CCD5C925DFD6D3587BEDA /* SharedViews */ = {
isa = PBXGroup;
children = (
+ 79E5453A30CC9E63BD51AD07 /* CachedFileIconView.swift */,
FFBAE8BB47EF2370E33AA43F /* CompactSearchField.swift */,
60941639B01D13FFFDAC8E36 /* GlassPillPicker.swift */,
+ FB348303094A1F0694628051 /* ScanStatusPill.swift */,
6C89B688828C26F999A174D1 /* WorkspaceHeaderBar.swift */,
);
path = SharedViews;
@@ -1045,6 +1071,7 @@
90BF90F2E933654B06A18BA4 /* MacOSCleanerApp.swift */,
267C8C93E377155321CB29E5 /* NavigationRailView.swift */,
34E0A4F6821D870D3E6D7222 /* RootView.swift */,
+ FAB123331AB8158A17DD2D05 /* WorkspaceStore.swift */,
);
path = App;
sourceTree = "";
@@ -1097,7 +1124,7 @@
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
- LastUpgradeCheck = 1430;
+ LastUpgradeCheck = 1600;
TargetAttributes = {
CEC36BF64813DCAC65122CF7 = {
DevelopmentTeam = "";
@@ -1254,6 +1281,7 @@
AA617FBF4572D43230BA56F9 /* OrphanScannerTests.swift in Sources */,
709EC6CB285002C70A3A1690 /* PathTokenNormalizeTests.swift in Sources */,
54A11DC7412ABFBC4E10F20E /* PermissionsManagerTests.swift in Sources */,
+ 8BCC68E6073167D5461A58D8 /* PreReleaseAuditTests.swift in Sources */,
4BA9A2AD4743A60CBB33F293 /* PrivacyTests.swift in Sources */,
D3F350B7A1D63625E68FFC11 /* PrivateCatalogLoaderTests.swift in Sources */,
CB27D2BE8DAE420461F4C9DE /* PrivilegedScriptTests.swift in Sources */,
@@ -1284,6 +1312,7 @@
E4F0A81CD5CD475EE439F95B /* AndroidStudioRule.swift in Sources */,
8F1C2ACF00DF4A34A6CA9862 /* AnimatedScanView.swift in Sources */,
CFA170D8C84D477F84A53303 /* AppDiscovery.swift in Sources */,
+ 359A5D8064F96042B6D5FBF0 /* AppIconCache.swift in Sources */,
AEA91CD04EACACE4AB9C75B6 /* AppIdentity.swift in Sources */,
354AAEA23A1C58900843BF36 /* AppQuitter.swift in Sources */,
2282CB50ADC015170FFA009C /* AppSettings.swift in Sources */,
@@ -1294,6 +1323,7 @@
87EDEF516A814FC99DCA0B31 /* BackgroundItemsReader.swift in Sources */,
827162E1B7CDF5B49840F176 /* BrowserExtensionScanner.swift in Sources */,
81622E787C1700C4F73D32CB /* BrowserRule.swift in Sources */,
+ 0D628AAD81B4CE2F0FAC2F47 /* CachedFileIconView.swift in Sources */,
77C8FDB4576E9419A7ACE1E6 /* CandidateCollector.swift in Sources */,
A292F5B0235283E514C9DC98 /* CleanCategoryIntent.swift in Sources */,
E6939DD5DC9C1298F2B0504A /* CleanDeveloperCachesIntent.swift in Sources */,
@@ -1321,6 +1351,7 @@
EEB5DCE33EB7B341CD0E8074 /* CompactSearchField.swift in Sources */,
CF451E1D986FDEB59A0B0F05 /* Confidence.swift in Sources */,
F66F8B5C81F0594E86965308 /* ConfidenceEngine.swift in Sources */,
+ 8C793CF8075DF8122AD8A90C /* CrashSignalHandler.swift in Sources */,
570CFBFA60E8F00EE0061637 /* CustomSiriCommand.swift in Sources */,
BA45213B9E4C9FC0430EBC68 /* DaVinciResolveRule.swift in Sources */,
BE3FBA22FA22D8E3A69F5A34 /* DashboardView.swift in Sources */,
@@ -1416,10 +1447,12 @@
92E0F73F02E1797F191A0BCD /* RaycastRule.swift in Sources */,
FA96D45AFA0FCF6E94C1032B /* RegistryPathTemplates.swift in Sources */,
B9FEEA903909722CAAB16EFE /* RegistryTypes.swift in Sources */,
+ 8E41A27853E6D68E9FEF0A4C /* ResidualScanIndex.swift in Sources */,
E16DD32548BBD2D1A11C9C92 /* RootView.swift in Sources */,
66763C6A242E5249D7133F25 /* RunScheduledCleanupIntent.swift in Sources */,
A663BEC17B22AFC47D7098AC /* RunningProcess.swift in Sources */,
CCDEB1A2EE6B7006D95A7ADC /* SafetyManager.swift in Sources */,
+ D9FF841D6649E7C18A2FCA37 /* ScanStatusPill.swift in Sources */,
1CA1BC5393BE23A5F8B3F20B /* ScoringWeights.swift in Sources */,
6298346D2C66782409770E87 /* SettingsAboutView.swift in Sources */,
EE98F8870E81508DA3DD855F /* SettingsAdvancedView.swift in Sources */,
@@ -1430,6 +1463,7 @@
CEE774995B3B626F0CEC13B1 /* SettingsModel.swift in Sources */,
A5B744E07A1193B0AC7C474A /* SettingsProcessesView.swift in Sources */,
BC7F5459F452CC98A955FAEB /* SettingsView.swift in Sources */,
+ 15A8DDD1B7953B44C4E56D51 /* SpotlightMetadata.swift in Sources */,
A5582FB3CC44494C2D0C5863 /* StartupService.swift in Sources */,
4E95B67B22946FA1B8D60565 /* StartupServicesView.swift in Sources */,
8E3DECCD5B86A373058DED54 /* StartupServicesViewModel.swift in Sources */,
@@ -1446,6 +1480,7 @@
1E8FBA40BF362852FD68AB34 /* UIMetadataProvider.swift in Sources */,
E656F0232A7C09D30D3A8B70 /* UninstallerService.swift in Sources */,
2005604ECBBC2DF0D8C637F0 /* UninstallerView.swift in Sources */,
+ F3560430362797A000BFF43F /* UninstallerViewModel.swift in Sources */,
7C4418AE4F14E22136AA7514 /* UnityRule.swift in Sources */,
329DBA7EA718B80A63BFC447 /* UpdateAvailableView.swift in Sources */,
28F537E447426249322A7AE8 /* UpdateChecker.swift in Sources */,
@@ -1455,6 +1490,7 @@
2D792A2983E94EDE263F97BC /* VerificationReport.swift in Sources */,
FCA4F949ED18C01812E53B56 /* VirtualizationRule.swift in Sources */,
3326F555CDC8D278F1551AD3 /* WorkspaceHeaderBar.swift in Sources */,
+ 5A37285FA27E2643E72AFE01 /* WorkspaceStore.swift in Sources */,
622E4977F3A1981F681C3D8B /* XcodeRule.swift in Sources */,
504605C5C782593AC1432966 /* ZipCentralDirectoryInspector.swift in Sources */,
);
@@ -1498,6 +1534,7 @@
3EE1EE7C3E9466314561B89D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ ARCHS = arm64;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOLS = NO;
BUILD_ACTIVE_RESOURCES_ONLY = YES;
@@ -1506,7 +1543,7 @@
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 3;
+ CURRENT_PROJECT_VERSION = 4;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = "";
ENABLE_DEBUG_DYLIB = NO;
@@ -1516,14 +1553,14 @@
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities";
- INFOPLIST_KEY_NSAppleEventsUsageDescription = "MacOSCleaner needs to send Apple Events to close applications before cleaning their caches and to open specific extension pages in your browser.";
+ INFOPLIST_KEY_NSAppleEventsUsageDescription = "MacOSCleaner needs to send Apple Events to close applications before cleaning their caches, open specific extension pages in your browser, and request a standard macOS restart when you choose to restart.";
INFOPLIST_KEY_NSHumanReadableCopyright = "Copyright © 2026 AlexTkDev (ORCID 0009-0002-8907-5406). All rights reserved.";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 26.0;
- MARKETING_VERSION = 3.0.0;
+ MARKETING_VERSION = 3.0.1;
ONLY_ACTIVE_ARCH = YES;
PRODUCT_BUNDLE_IDENTIFIER = input.MacOSCleaner;
SDKROOT = macosx;
@@ -1599,6 +1636,7 @@
72A90B907FE2813B16326360 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ ARCHS = arm64;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOLS = NO;
CLANG_ANALYZER_NONNULL = YES;
@@ -1606,7 +1644,7 @@
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 3;
+ CURRENT_PROJECT_VERSION = 4;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = "";
ENABLE_DEBUG_DYLIB = NO;
@@ -1616,14 +1654,14 @@
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities";
- INFOPLIST_KEY_NSAppleEventsUsageDescription = "MacOSCleaner needs to send Apple Events to close applications before cleaning their caches and to open specific extension pages in your browser.";
+ INFOPLIST_KEY_NSAppleEventsUsageDescription = "MacOSCleaner needs to send Apple Events to close applications before cleaning their caches, open specific extension pages in your browser, and request a standard macOS restart when you choose to restart.";
INFOPLIST_KEY_NSHumanReadableCopyright = "Copyright © 2026 AlexTkDev (ORCID 0009-0002-8907-5406). All rights reserved.";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 26.0;
- MARKETING_VERSION = 3.0.0;
+ MARKETING_VERSION = 3.0.1;
PRODUCT_BUNDLE_IDENTIFIER = input.MacOSCleaner;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
diff --git a/MacOSCleaner/MacOSCleanerTests/AIExplanationServiceTests.swift b/MacOSCleaner/MacOSCleanerTests/AIExplanationServiceTests.swift
index ddc7fe3..811b5a5 100644
--- a/MacOSCleaner/MacOSCleanerTests/AIExplanationServiceTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/AIExplanationServiceTests.swift
@@ -22,6 +22,16 @@ final class AIExplanationServiceTests: XCTestCase {
await AIExplanationService.shared.prewarm()
}
+ func testPrewarmIfNeeded_isIdempotent() async {
+ await AIExplanationService.shared.resetPrewarmForTesting()
+ for _ in 0..<5 {
+ await AIExplanationService.shared.prewarmIfNeeded()
+ }
+ let count = await AIExplanationService.shared.prewarmAttemptCountForTesting()
+ XCTAssertEqual(count, 1)
+ await AIExplanationService.shared.resetPrewarmForTesting()
+ }
+
func testVerdictExtraction() {
let safeResult = AIExplanationResult.extractVerdict(from: "[SAFE] This cache is temporary and safe to delete.")
XCTAssertEqual(safeResult.verdict, .safe)
diff --git a/MacOSCleaner/MacOSCleanerTests/CandidateCollectorTests.swift b/MacOSCleaner/MacOSCleanerTests/CandidateCollectorTests.swift
index 71563d9..b65dd67 100644
--- a/MacOSCleaner/MacOSCleanerTests/CandidateCollectorTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/CandidateCollectorTests.swift
@@ -727,8 +727,10 @@ final class CandidateCollectorTests: XCTestCase {
let candidates = await makeCollector(tmpScanDirectory: tmpRoot)
.collect(identity: identity, mode: .balanced)
let paths = Set(candidates.map { $0.resolvingSymlinksInPath().path })
- XCTAssertTrue(paths.contains(vendor.resolvingSymlinksInPath().path)
- || paths.contains(vendor.deletingLastPathComponent().resolvingSymlinksInPath().path))
+ if CatalogTestSupport.hasPrivateCatalog {
+ XCTAssertTrue(paths.contains(vendor.resolvingSymlinksInPath().path)
+ || paths.contains(vendor.deletingLastPathComponent().resolvingSymlinksInPath().path))
+ }
XCTAssertTrue(paths.contains(buildApp.resolvingSymlinksInPath().path))
}
@@ -980,4 +982,261 @@ final class CandidateCollectorTests: XCTestCase {
EvidenceProbe.bundleIDSuffixMatch("OfficeWordWidget", bundleID: "com.microsoft.excel")
)
}
+
+ func test_collect_googleDriveAndChromePWADoNotCollectChromeProfile() async throws {
+ let chromeExt = URL(fileURLWithPath: home)
+ .appendingPathComponent("Library/Application Support/Google/Chrome/Default/Extensions/ext1/1.0")
+ let driveSupport = URL(fileURLWithPath: home)
+ .appendingPathComponent("Library/Application Support/Google/DriveFS")
+ let chromeCache = URL(fileURLWithPath: home)
+ .appendingPathComponent("Library/Caches/com.google.Chrome")
+ for dir in [chromeExt, driveSupport, chromeCache] {
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ }
+ defer { try? FileManager.default.removeItem(at: URL(fileURLWithPath: home).appendingPathComponent("Library")) }
+
+ let collector = makeCollector()
+
+ let driveIdentity = AppIdentity(
+ bundleID: "com.google.drivefs",
+ appName: "Google Drive",
+ bundleName: "Google Drive",
+ bundleVersion: nil,
+ executableName: "Google Drive",
+ teamID: "EQHXZ8M8AV",
+ signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "/Applications/Google Drive.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: ["Google", "Drive"],
+ helperNames: [], frameworkNames: [], xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false,
+ isJava: false, isQt: false, isDocker: false
+ )
+ let driveCollection = await collector.collectDetailed(identity: driveIdentity, mode: .balanced)
+ XCTAssertFalse(driveCollection.candidates.contains { $0.path.lowercased().contains("/google/chrome") })
+ XCTAssertFalse(driveCollection.candidates.contains { $0.path.lowercased().contains("com.google.chrome") })
+
+ let pwaIdentity = AppIdentity(
+ bundleID: "com.google.Chrome.app.aghbiahbpaij",
+ appName: "Bank App",
+ bundleName: "Chrome",
+ bundleVersion: nil,
+ executableName: "app_mode_loader",
+ teamID: "EQHXZ8M8AV",
+ signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "\(home)/Applications/Chrome Apps.localized/Bank App.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: ["Google"],
+ helperNames: [], frameworkNames: [], xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false,
+ isJava: false, isQt: false, isDocker: false
+ )
+ let pwaCollection = await collector.collectDetailed(identity: pwaIdentity, mode: .balanced)
+ XCTAssertFalse(pwaCollection.candidates.contains { $0.path.lowercased().contains("/google/chrome") })
+ XCTAssertFalse(pwaCollection.candidates.contains { $0.path.lowercased().contains("com.google.chrome") })
+
+ let canaryIdentity = AppIdentity(
+ bundleID: "com.google.Chrome.canary",
+ appName: "Google Chrome Canary",
+ bundleName: "Chrome Canary",
+ bundleVersion: nil,
+ executableName: "Google Chrome Canary",
+ teamID: "EQHXZ8M8AV",
+ signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "/Applications/Google Chrome Canary.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: ["Google"],
+ helperNames: [], frameworkNames: [], xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false,
+ isJava: false, isQt: false, isDocker: false
+ )
+ let canaryCollection = await collector.collectDetailed(identity: canaryIdentity, mode: .balanced)
+ XCTAssertFalse(canaryCollection.candidates.contains { $0.path.lowercased().hasSuffix("/google/chrome") || $0.path.lowercased().contains("/google/chrome/") })
+ }
+
+ func test_runMdfind_skipsSubprocessWhenSpotlightDisabled() async {
+ let runner = MockCommandRunner()
+ final class Counter: @unchecked Sendable {
+ let lock = NSLock()
+ var mdfindCalls = 0
+ func inc() { lock.lock(); mdfindCalls += 1; lock.unlock() }
+ func value() -> Int { lock.lock(); defer { lock.unlock() }; return mdfindCalls }
+ }
+ let counter = Counter()
+ runner.runHandler = { cmd, _ in
+ if cmd == "/usr/bin/mdfind" {
+ counter.inc()
+ }
+ return CommandResult(stdout: "", stderr: "", exitCode: 0)
+ }
+
+ SpotlightMetadata.setOverrideForTesting(isIndexingAvailable: { _ in false })
+ defer { SpotlightMetadata.resetForTesting() }
+
+ let collector = makeCollector(commandRunner: runner)
+ let identity = AppIdentity(
+ bundleID: "com.example.spotlighttest",
+ appName: "SpotlightTest",
+ bundleName: nil, bundleVersion: nil,
+ executableName: "SpotlightTest",
+ teamID: nil, signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "/Applications/SpotlightTest.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: [], helperNames: [], frameworkNames: [], xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false,
+ isJava: false, isQt: false, isDocker: false
+ )
+
+ _ = await collector.collectDetailed(identity: identity, mode: .balanced)
+ XCTAssertEqual(counter.value(), 0, "mdfind must not spawn when Spotlight indexing is off")
+
+ SpotlightMetadata.setOverrideForTesting(isIndexingAvailable: { _ in true })
+ _ = await collector.collectDetailed(identity: identity, mode: .balanced)
+ XCTAssertGreaterThan(counter.value(), 0, "mdfind should run in balanced mode when Spotlight is enabled")
+ }
+
+ func test_residualScanIndex_matchesUnindexedCollectionAndAvoidsReenumeration() async throws {
+ let lib = URL(fileURLWithPath: home).appendingPathComponent("Library", isDirectory: true)
+ let appScripts = lib.appendingPathComponent("Application Scripts/com.apple.OFDThumbnail", isDirectory: true)
+ let studio = lib.appendingPathComponent("Application Support/Google/AndroidStudio2026.1.2", isDirectory: true)
+ let openCodeNested = lib.appendingPathComponent("Caches/ai.opencode.desktop/UpdaterCache/opencode-desktop_br", isDirectory: true)
+ let groupContainer = lib.appendingPathComponent("Group Containers/HUAQ24HBR6.dev.orbstack", isDirectory: true)
+ let prefs = lib.appendingPathComponent("Preferences", isDirectory: true)
+ let launchAgents = lib.appendingPathComponent("LaunchAgents", isDirectory: true)
+ let anydeskDot = URL(fileURLWithPath: home).appendingPathComponent(".anydesk", isDirectory: true)
+
+ for dir in [appScripts, studio, openCodeNested, groupContainer, prefs, launchAgents, anydeskDot] {
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ }
+ try Data().write(to: prefs.appendingPathComponent("com.google.android.studio.plist"))
+ try Data().write(to: launchAgents.appendingPathComponent("dev.orbstack.agent.plist"))
+ defer { try? FileManager.default.removeItem(at: lib) }
+
+ final class PkgutilCounter: @unchecked Sendable {
+ let lock = NSLock()
+ var pkgsCalls = 0
+ func inc() { lock.lock(); pkgsCalls += 1; lock.unlock() }
+ func value() -> Int { lock.lock(); defer { lock.unlock() }; return pkgsCalls }
+ }
+ let pkgCounter = PkgutilCounter()
+ let runner = MockCommandRunner()
+ runner.runDelay = .zero
+ runner.runHandler = { cmd, args in
+ if cmd == "/usr/sbin/pkgutil", args == ["--pkgs"] {
+ pkgCounter.inc()
+ return CommandResult(stdout: "com.apple.pkg.SomeOther\n", stderr: "", exitCode: 0)
+ }
+ return CommandResult(stdout: "", stderr: "", exitCode: 0)
+ }
+
+ let index = await ResidualScanIndex.build(
+ fileSystemContext: fileSystemContext,
+ homebrewCellarDirectories: [],
+ commandRunner: runner
+ )
+ XCTAssertEqual(pkgCounter.value(), 1, "ResidualScanIndex must call pkgutil --pkgs only once")
+
+ let identities = [
+ AppIdentity(
+ bundleID: "com.google.android.studio",
+ appName: "Android Studio",
+ bundleName: nil, bundleVersion: nil, executableName: "studio",
+ teamID: nil, signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "/Applications/Android Studio.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: ["Google"], helperNames: [], frameworkNames: [], xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false, isJava: true, isQt: false, isDocker: false
+ ),
+ AppIdentity(
+ bundleID: "ai.opencode.desktop",
+ appName: "OpenCode",
+ bundleName: "OpenCode", bundleVersion: nil, executableName: "OpenCode",
+ teamID: nil, signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "/Applications/OpenCode.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: ["opencode"], helperNames: [], frameworkNames: [], xpcServiceNames: [], plugInNames: [],
+ isElectron: true, isJetBrains: false, isFlutter: false, isJava: false, isQt: false, isDocker: false
+ ),
+ AppIdentity(
+ bundleID: "dev.orbstack",
+ appName: "OrbStack",
+ bundleName: "OrbStack", bundleVersion: nil, executableName: "OrbStack",
+ teamID: "HUAQ24HBR6", signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "/Applications/OrbStack.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: [], helperNames: [], frameworkNames: [], xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false, isJava: false, isQt: false, isDocker: true
+ ),
+ AppIdentity(
+ bundleID: "com.philandro.anydesk",
+ appName: "AnyDesk",
+ bundleName: "AnyDesk", bundleVersion: nil, executableName: "AnyDesk",
+ teamID: nil, signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "/Applications/AnyDesk.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: ["philandro"], helperNames: [], frameworkNames: [], xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false, isJava: false, isQt: false, isDocker: false
+ ),
+ ]
+
+ let indexedCollector = CandidateCollector(
+ commandRunner: runner,
+ homebrewCellarDirectories: [],
+ fileSystemContext: fileSystemContext,
+ scanIndex: index
+ )
+ let unindexedCollector = makeCollector(commandRunner: runner)
+
+ var indexedResults: [String: Set] = [:]
+ for identity in identities {
+ let indexed = await indexedCollector.collectDetailed(identity: identity, mode: .balanced)
+ indexedResults[identity.bundleID] = Set(indexed.candidates.map { $0.resolvingSymlinksInPath().path })
+ }
+
+ XCTAssertEqual(pkgCounter.value(), 1, "Indexed collection must not re-invoke pkgutil --pkgs")
+
+ for identity in identities {
+ let unindexed = await unindexedCollector.collectDetailed(identity: identity, mode: .balanced)
+ let unindexedPaths = Set(unindexed.candidates.map { $0.resolvingSymlinksInPath().path })
+ XCTAssertEqual(indexedResults[identity.bundleID], unindexedPaths, "Indexed collection must match unindexed for \(identity.bundleID)")
+ }
+ }
+
+ func test_evidenceProbe_skipsCodesignSubprocessForPlainDirectories() async throws {
+ let dir = URL(fileURLWithPath: home).appendingPathComponent("Library/Application Support/PlainFolder", isDirectory: true)
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ final class CallCounter: @unchecked Sendable {
+ let lock = NSLock()
+ var codesignCalls = 0
+ func inc() { lock.lock(); codesignCalls += 1; lock.unlock() }
+ func value() -> Int { lock.lock(); defer { lock.unlock() }; return codesignCalls }
+ }
+ let counter = CallCounter()
+ let runner = MockCommandRunner()
+ runner.runDelay = .zero
+ runner.runHandler = { cmd, _ in
+ if cmd == "/usr/bin/codesign" {
+ counter.inc()
+ }
+ return CommandResult(stdout: "", stderr: "", exitCode: 0)
+ }
+
+ let probe = EvidenceProbe(commandRunner: runner, codesignCache: CodesignCache(), plistCache: PlistContentCache())
+ let identity = AppIdentity(
+ bundleID: "com.example.plain",
+ appName: "PlainFolder",
+ bundleName: nil, bundleVersion: nil, executableName: "PlainFolder",
+ teamID: "TEAM123456", signingAuthority: "Developer ID Application: Test",
+ bundleURL: URL(fileURLWithPath: "/Applications/PlainFolder.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: [], helperNames: [], frameworkNames: [], xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false, isJava: false, isQt: false, isDocker: false
+ )
+
+ let evidence = await probe.probe(url: dir, identity: identity)
+ XCTAssertTrue(evidence.contains(.appNameExact))
+ XCTAssertEqual(counter.value(), 0, "EvidenceProbe must not spawn /usr/bin/codesign subprocesses")
+ }
}
diff --git a/MacOSCleaner/MacOSCleanerTests/CleanupEngineTests.swift b/MacOSCleaner/MacOSCleanerTests/CleanupEngineTests.swift
index 354ad25..fefefd1 100644
--- a/MacOSCleaner/MacOSCleanerTests/CleanupEngineTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/CleanupEngineTests.swift
@@ -1141,6 +1141,64 @@ extension CleanupEngineTests {
_ = try await engine.run(categories: [.iosSimulators], dryRun: false, options: options)
#expect(!box.values.contains { $0.contains("simctl delete") || $0.contains("runtime delete") })
}
+
+ @Test("appCaches discovers third-party caches while preserving system and Google updater trees")
+ func appCachesDiscoversThirdPartyAndSkipsProtected() async throws {
+ let ctx = try FileSystemContext.isolatedTestRoot()
+ defer { try? FileManager.default.removeItem(at: ctx.allowedRoots[0]) }
+ let fm = FileManager.default
+
+ let customCache = ctx.homePath + "/Library/Caches/com.example.customapp"
+ let appleCache = ctx.homePath + "/Library/Caches/com.apple.Safari"
+ let cloudKitCache = ctx.homePath + "/Library/Caches/CloudKit"
+ let googleCache = ctx.homePath + "/Library/Caches/Google"
+ let keystoneCache = ctx.homePath + "/Library/Caches/com.google.Keystone"
+
+ for dir in [customCache, appleCache, cloudKitCache, googleCache, keystoneCache] {
+ try fm.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ try Data(repeating: 0xAB, count: 4096).write(to: URL(fileURLWithPath: dir + "/blob.bin"))
+ }
+
+ let engine = CleanupEngine(commandRunner: MockCommandRunner(), fileSystemContext: ctx)
+ _ = try await engine.run(categories: [.appCaches], dryRun: false)
+
+ #expect(!fm.fileExists(atPath: customCache + "/blob.bin"))
+ #expect(fm.fileExists(atPath: appleCache + "/blob.bin"))
+ #expect(fm.fileExists(atPath: cloudKitCache + "/blob.bin"))
+ #expect(fm.fileExists(atPath: googleCache + "/blob.bin"))
+ #expect(fm.fileExists(atPath: keystoneCache + "/blob.bin"))
+ }
+
+ @Test("dynamicCacheDiscovery skips caches owned by dedicated planned categories and Google")
+ func testDynamicCacheDiscovery_skipsDedicatedCategoryCaches() async throws {
+ let ctx = try FileSystemContext.isolatedTestRoot()
+ defer { try? FileManager.default.removeItem(at: ctx.allowedRoots[0]) }
+ let fm = FileManager.default
+
+ let cacheNames = ["Google", "Homebrew", "CloudKit", "UnknownCustomCache"]
+ let payload = Data(repeating: 0xAB, count: 6 * 1024 * 1024)
+ for name in cacheNames {
+ let dir = ctx.homePath + "/Library/Caches/" + name
+ try fm.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ try payload.write(to: URL(fileURLWithPath: dir + "/cache.bin"))
+ }
+
+ let collector = PreviewCollector()
+ let engine = CleanupEngine(commandRunner: MockCommandRunner(), fileSystemContext: ctx)
+ _ = try await engine.scan(
+ categories: [.browserCaches, .packageManagers, .cloudKitCache, .dynamicCacheDiscovery]
+ ) { event in
+ if case .preview(let label, _, _, let parent, _) = event, parent == "Review manually" {
+ collector.append(label)
+ }
+ }
+
+ let reviewLabels = collector.values
+ #expect(reviewLabels.contains { $0.hasPrefix("UnknownCustomCache") })
+ #expect(!reviewLabels.contains { $0.hasPrefix("Google") })
+ #expect(!reviewLabels.contains { $0.hasPrefix("Homebrew") })
+ #expect(!reviewLabels.contains { $0.hasPrefix("CloudKit") })
+ }
}
private final class CommandLog: @unchecked Sendable {
@@ -1149,3 +1207,10 @@ private final class CommandLog: @unchecked Sendable {
var values: [String] { lock.withLock { items } }
func append(_ value: String) { lock.withLock { items.append(value) } }
}
+
+private final class PreviewCollector: @unchecked Sendable {
+ private let lock = NSLock()
+ private var labels: [String] = []
+ var values: [String] { lock.withLock { labels } }
+ func append(_ label: String) { lock.withLock { labels.append(label) } }
+}
diff --git a/MacOSCleaner/MacOSCleanerTests/CleanupTrashTests.swift b/MacOSCleaner/MacOSCleanerTests/CleanupTrashTests.swift
index 5c74f8e..426cb9e 100644
--- a/MacOSCleaner/MacOSCleanerTests/CleanupTrashTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/CleanupTrashTests.swift
@@ -308,4 +308,44 @@ final class CleanupTrashTests: XCTestCase {
XCTAssertEqual(op?.deletionMode, OperationRecord.DeletionMode.trash.rawValue)
XCTAssertEqual(op?.failed, 0)
}
+
+ func testExecuteCleanup_tracksCleanedFontCacheAndResets() async throws {
+ let mockRunner = MockCommandRunner()
+ let customEngine = CleanupEngine(
+ commandRunner: mockRunner,
+ safetyManager: SafetyManager(homeDirectory: fileSystemContext.homePath, fileSystemContext: fileSystemContext),
+ fileSystemContext: fileSystemContext
+ )
+ let customCoordinator = CleanupCoordinator(
+ engine: customEngine,
+ journal: journal,
+ settings: settings,
+ trashManager: trashManager,
+ itemManager: itemManager,
+ trashDirectoryURL: trashDirectory
+ )
+ coordinator = customCoordinator
+
+ customCoordinator.startScan(options: CleanupOptions(targetCategories: []))
+ try await waitForState(.preview)
+
+ let fontLabel = CleanupCategory.fontCache.localizedTitle
+ itemManager.appendFileItem(
+ path: "command://font/cache-clear",
+ sizeBytes: 0,
+ modificationDate: nil,
+ isDirectory: false,
+ category: fontLabel,
+ parentName: fontLabel,
+ isSelected: true,
+ isCommandBacked: true
+ )
+
+ customCoordinator.executeCleanup(options: CleanupOptions(targetCategories: [.fontCache], cleanFontCache: true))
+ try await waitForState(.completed)
+
+ XCTAssertTrue(customCoordinator.cleanedFontCache)
+ customCoordinator.reset()
+ XCTAssertFalse(customCoordinator.cleanedFontCache)
+ }
}
diff --git a/MacOSCleaner/MacOSCleanerTests/DashboardViewModelTests.swift b/MacOSCleaner/MacOSCleanerTests/DashboardViewModelTests.swift
index a94d838..ffcb297 100644
--- a/MacOSCleaner/MacOSCleanerTests/DashboardViewModelTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/DashboardViewModelTests.swift
@@ -85,4 +85,18 @@ final class DashboardViewModelTests: XCTestCase {
let nonexistentSize = await DashboardViewModel.calculatePathSize(testDir.appendingPathComponent("missing").path)
XCTAssertEqual(nonexistentSize, 0)
}
+
+ func testRefresh_updatesCategoriesProgressivelyAndMarksComplete() async {
+ await viewModel.refresh()
+
+ XCTAssertFalse(viewModel.isCategoriesLoading)
+ XCTAssertEqual(viewModel.completedCategoriesCount, viewModel.totalScanCategoriesCount)
+ XCTAssertFalse(viewModel.diskCategories.isEmpty)
+ XCTAssertTrue(viewModel.diskCategories.allSatisfy { !$0.isScanning })
+
+ let ids = viewModel.diskCategories.map(\.id)
+ XCTAssertEqual(Set(ids).count, ids.count)
+ let allowedIDs: Set = ["caches", "logs", "dev", "apps", "media", "other"]
+ XCTAssertTrue(Set(ids).isSubset(of: allowedIDs))
+ }
}
diff --git a/MacOSCleaner/MacOSCleanerTests/FileSystemIsolationTests.swift b/MacOSCleaner/MacOSCleanerTests/FileSystemIsolationTests.swift
index 44534aa..7915624 100644
--- a/MacOSCleaner/MacOSCleanerTests/FileSystemIsolationTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/FileSystemIsolationTests.swift
@@ -153,6 +153,17 @@ final class FileSystemIsolationTests: XCTestCase {
let allowedPaths = prod.allowedRoots.map(\.path)
XCTAssertFalse(allowedPaths.contains("/Users"), "Allowed roots must never include wholesale /Users")
XCTAssertTrue(allowedPaths.contains(FileManager.default.homeDirectoryForCurrentUser.resolvingSymlinksInPath().path))
+ XCTAssertTrue(allowedPaths.contains("/Applications"))
+
+ let prodSafety = SafetyManager(homeDirectory: prod.homePath, fileSystemContext: prod)
+ XCTAssertNoThrow(
+ try prodSafety.validate(url: URL(fileURLWithPath: "/Applications/Sample.app"), policy: .uninstall),
+ "Production uninstaller safety check must allow /Applications/*.app"
+ )
+ XCTAssertThrowsError(
+ try prodSafety.validate(url: URL(fileURLWithPath: "/Applications"), policy: .uninstall),
+ "Wholesale /Applications must stay protected"
+ )
}
func test_cleanupPathExpanderDoesNotExpandForeignUsers() throws {
diff --git a/MacOSCleaner/MacOSCleanerTests/HelperAppCollapserTests.swift b/MacOSCleaner/MacOSCleanerTests/HelperAppCollapserTests.swift
index df58fc6..fe3ee04 100644
--- a/MacOSCleaner/MacOSCleanerTests/HelperAppCollapserTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/HelperAppCollapserTests.swift
@@ -121,8 +121,7 @@ final class HelperAppCollapserTests: XCTestCase {
scanState: .discovered,
size: 100,
version: "1",
- lastUsed: nil,
- iconData: nil
+ lastUsed: nil
)
}
}
diff --git a/MacOSCleaner/MacOSCleanerTests/LocalizationCompletenessTests.swift b/MacOSCleaner/MacOSCleanerTests/LocalizationCompletenessTests.swift
index 90ed2ab..ea1514a 100644
--- a/MacOSCleaner/MacOSCleanerTests/LocalizationCompletenessTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/LocalizationCompletenessTests.swift
@@ -141,7 +141,32 @@ final class LocalizationCompletenessTests: XCTestCase {
"risk.user_data",
"risk.protected",
"about_transparency_button",
- "about_limitations_title"
+ "about_limitations_title",
+ "uninstaller_browser_data_warning",
+ "uninstaller_browser_data_badge",
+ "uninstaller_browser_data_confirm_warning",
+ "uninstaller_spotlight_disabled",
+ "scan_updated_at",
+ "scan_updated_just_now",
+ "cleanup_restart_recommended_title",
+ "cleanup_restart_recommended_body",
+ "cleanup_restart_required_title",
+ "cleanup_restart_font_cache_body",
+ "uninstaller_restart_recommended_title",
+ "uninstaller_restart_recommended_body",
+ "restart_mac_button",
+ "uninstaller_orphan_scanning_dirs",
+ "uninstaller_orphan_analyzing_count",
+ "uninstaller_orphan_analyzing_progress",
+ "uninstaller_orphan_cat_caches",
+ "uninstaller_orphan_cat_preferences",
+ "uninstaller_orphan_cat_app_support",
+ "uninstaller_orphan_cat_logs",
+ "uninstaller_orphan_cat_containers",
+ "uninstaller_orphan_cat_developer",
+ "uninstaller_orphan_cat_launch_agents",
+ "uninstaller_orphan_cat_other",
+ "uninstaller_evidence_score"
]
func testAllSupportedLanguagesContainRequiredLeftoverKeys() {
diff --git a/MacOSCleaner/MacOSCleanerTests/OrphanScannerTests.swift b/MacOSCleaner/MacOSCleanerTests/OrphanScannerTests.swift
index 748b1fb..569fb6d 100644
--- a/MacOSCleaner/MacOSCleanerTests/OrphanScannerTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/OrphanScannerTests.swift
@@ -84,5 +84,179 @@ final class OrphanScannerTests: XCTestCase {
XCTAssertGreaterThanOrEqual(found.confidence, .possible)
}
}
+
+ func testOrphanScanner_homebrewFormulaInstalledInCellar_notFlaggedAsOrphan() async throws {
+ let cellar = fileSystemContext.allowedRoots[0].appendingPathComponent("Homebrew/Cellar", isDirectory: true)
+ let formulaVersionDir = cellar.appendingPathComponent("languagetool/6.5", isDirectory: true)
+ try FileManager.default.createDirectory(at: formulaVersionDir, withIntermediateDirectories: true)
+
+ let launchAgents = testRoot.appendingPathComponent("Library/LaunchAgents", isDirectory: true)
+ try FileManager.default.createDirectory(at: launchAgents, withIntermediateDirectories: true)
+ let plistURL = launchAgents.appendingPathComponent("homebrew.mxcl.languagetool.plist")
+ let plistData = try PropertyListSerialization.data(
+ fromPropertyList: [
+ "Label": "homebrew.mxcl.languagetool",
+ "ProgramArguments": ["/opt/homebrew/opt/languagetool/bin/languagetool-server"]
+ ],
+ format: .xml,
+ options: 0
+ )
+ try plistData.write(to: plistURL)
+
+ let customScanner = OrphanScanner(
+ safetyManager: safetyManager,
+ commandRunner: CommandRunner(),
+ fileSystemContext: fileSystemContext,
+ codesignCache: codesignCache,
+ plistCache: plistCache,
+ homebrewCellarDirectories: [cellar]
+ )
+
+ let orphans = try await customScanner.scanOrphans()
+ XCTAssertFalse(
+ orphans.contains { $0.url.lastPathComponent == "homebrew.mxcl.languagetool.plist" },
+ "Installed Homebrew formula LaunchAgent must not be flagged as orphan"
+ )
+ }
+
+ func testOrphanScanner_homebrewLaunchAgentWithExistingBinary_notFlaggedAsOrphan() async throws {
+ let emptyCellar = fileSystemContext.allowedRoots[0].appendingPathComponent("EmptyCellar", isDirectory: true)
+ try FileManager.default.createDirectory(at: emptyCellar, withIntermediateDirectories: true)
+
+ let customBinDir = fileSystemContext.allowedRoots[0].appendingPathComponent("custom-brew/opt/myservice/bin", isDirectory: true)
+ try FileManager.default.createDirectory(at: customBinDir, withIntermediateDirectories: true)
+ let binaryURL = customBinDir.appendingPathComponent("myservice")
+ try Data("#!/bin/sh\n".utf8).write(to: binaryURL)
+
+ let launchAgents = testRoot.appendingPathComponent("Library/LaunchAgents", isDirectory: true)
+ try FileManager.default.createDirectory(at: launchAgents, withIntermediateDirectories: true)
+ let plistURL = launchAgents.appendingPathComponent("homebrew.mxcl.myservice.plist")
+ let plistData = try PropertyListSerialization.data(
+ fromPropertyList: [
+ "Label": "homebrew.mxcl.myservice",
+ "ProgramArguments": [binaryURL.path, "--daemon"]
+ ],
+ format: .xml,
+ options: 0
+ )
+ try plistData.write(to: plistURL)
+
+ let customScanner = OrphanScanner(
+ safetyManager: safetyManager,
+ commandRunner: CommandRunner(),
+ fileSystemContext: fileSystemContext,
+ codesignCache: codesignCache,
+ plistCache: plistCache,
+ homebrewCellarDirectories: [emptyCellar]
+ )
+
+ let orphans = try await customScanner.scanOrphans()
+ XCTAssertFalse(
+ orphans.contains { $0.url.lastPathComponent == "homebrew.mxcl.myservice.plist" },
+ "Homebrew LaunchAgent whose binary exists on disk must not be flagged as orphan"
+ )
+ }
+
+ func testOrphanScanner_homebrewFormulaUninstalled_neverMarkedGuaranteed() async throws {
+ let emptyCellar = fileSystemContext.allowedRoots[0].appendingPathComponent("EmptyCellar", isDirectory: true)
+ try FileManager.default.createDirectory(at: emptyCellar, withIntermediateDirectories: true)
+
+ let launchAgents = testRoot.appendingPathComponent("Library/LaunchAgents", isDirectory: true)
+ try FileManager.default.createDirectory(at: launchAgents, withIntermediateDirectories: true)
+ let plistURL = launchAgents.appendingPathComponent("homebrew.mxcl.removedtool.plist")
+ let missingBin = fileSystemContext.allowedRoots[0].appendingPathComponent("missing-opt/removedtool/bin/removedtool").path
+ let plistData = try PropertyListSerialization.data(
+ fromPropertyList: [
+ "Label": "homebrew.mxcl.removedtool",
+ "ProgramArguments": [missingBin]
+ ],
+ format: .xml,
+ options: 0
+ )
+ try plistData.write(to: plistURL)
+
+ let customScanner = OrphanScanner(
+ safetyManager: safetyManager,
+ commandRunner: CommandRunner(),
+ fileSystemContext: fileSystemContext,
+ codesignCache: codesignCache,
+ plistCache: plistCache,
+ homebrewCellarDirectories: [emptyCellar]
+ )
+
+ let orphans = try await customScanner.scanOrphans()
+ let found = try XCTUnwrap(orphans.first { $0.url.lastPathComponent == "homebrew.mxcl.removedtool.plist" })
+ XCTAssertLessThan(found.confidence, .guaranteed, "Uninstalled Homebrew service plist must never be marked Guaranteed")
+ XCTAssertEqual(found.confidence, .veryLikely)
+ XCTAssertEqual(found.category, "Launch Agents")
+ }
+
+ func testExtractBundleIDAndName_versionedPlistAndReverseDNS() {
+ let py38 = OrphanScanner.extractBundleIDAndName(from: URL(fileURLWithPath: "/Users/test/Library/Preferences/python3.8.plist"))
+ XCTAssertEqual(py38.bundleID, "python3.8")
+ XCTAssertEqual(py38.name, "python3.8")
+
+ let py312 = OrphanScanner.extractBundleIDAndName(from: URL(fileURLWithPath: "/Users/test/Library/Preferences/python3.12.plist"))
+ XCTAssertEqual(py312.name, "python3.12")
+
+ let orgPy38 = OrphanScanner.extractBundleIDAndName(from: URL(fileURLWithPath: "/Users/test/Library/Preferences/org.python.python3.8.plist"))
+ XCTAssertEqual(orgPy38.name, "python3.8")
+
+ let photoshop = OrphanScanner.extractBundleIDAndName(from: URL(fileURLWithPath: "/Users/test/Library/Preferences/com.adobe.Photoshop.2024.plist"))
+ XCTAssertEqual(photoshop.name, "Photoshop 2024")
+
+ let oneDrive = OrphanScanner.extractBundleIDAndName(from: URL(fileURLWithPath: "/Users/test/Library/Preferences/com.microsoft.OneDrive.plist"))
+ XCTAssertEqual(oneDrive.name, "OneDrive")
+
+ let container = OrphanScanner.extractBundleIDAndName(from: URL(fileURLWithPath: "/Users/test/Library/Containers/com.unknown.orphanapp"))
+ XCTAssertEqual(container.bundleID, "com.unknown.orphanapp")
+ XCTAssertEqual(container.name, "Orphanapp")
+
+ let cacheFolder = OrphanScanner.extractBundleIDAndName(from: URL(fileURLWithPath: "/Users/test/Library/Caches/com.example.MyApp"))
+ XCTAssertEqual(cacheFolder.bundleID, "com.example.MyApp")
+ XCTAssertEqual(cacheFolder.name, "MyApp")
+ }
+
+ func testOrphanItem_localizedCategory_spanish() {
+ LanguageManager.testingLock.lock()
+ defer {
+ LanguageManager.shared.setLanguage(.english)
+ LanguageManager.testingLock.unlock()
+ }
+
+ LanguageManager.shared.setLanguage(.spanish)
+ XCTAssertEqual(OrphanItem.localizedCategoryName(for: "Preferences"), "Preferencias")
+ XCTAssertEqual(OrphanItem.localizedCategoryName(for: "Other"), "Otros")
+ XCTAssertEqual(OrphanItem.localizedCategoryName(for: "Launch Agents"), "Agentes de inicio")
+ }
+
+ func testScanOrphans_ignoresSystemTVAppServicesAndSharedSentrySDK() async throws {
+ let fm = FileManager.default
+ let payload = Data(repeating: 0xAA, count: 8192)
+
+ let protectedDirs = [
+ testRoot.appendingPathComponent("Library/Group Containers/group.tvappservices.container", isDirectory: true),
+ testRoot.appendingPathComponent("Library/Containers/tvappservices.container", isDirectory: true),
+ testRoot.appendingPathComponent("Library/Caches/io.sentry", isDirectory: true),
+ testRoot.appendingPathComponent("Library/Caches/com.plausiblelabs.crashreporter.data", isDirectory: true),
+ ]
+ for dir in protectedDirs {
+ try fm.createDirectory(at: dir, withIntermediateDirectories: true)
+ try payload.write(to: dir.appendingPathComponent("blob.bin"))
+ }
+
+ let realOrphan = testRoot.appendingPathComponent("Library/Containers/com.unknown.deletedtool", isDirectory: true)
+ try fm.createDirectory(at: realOrphan, withIntermediateDirectories: true)
+ try payload.write(to: realOrphan.appendingPathComponent("blob.bin"))
+
+ let orphans = try await scanner.scanOrphans()
+ let paths = Set(orphans.map { $0.url.lastPathComponent.lowercased() })
+
+ XCTAssertFalse(paths.contains("group.tvappservices.container"))
+ XCTAssertFalse(paths.contains("tvappservices.container"))
+ XCTAssertFalse(paths.contains("io.sentry"))
+ XCTAssertFalse(paths.contains("com.plausiblelabs.crashreporter.data"))
+ XCTAssertTrue(paths.contains("com.unknown.deletedtool"))
+ }
}
diff --git a/MacOSCleaner/MacOSCleanerTests/PermissionsManagerTests.swift b/MacOSCleaner/MacOSCleanerTests/PermissionsManagerTests.swift
index 9517fdc..881ab7a 100644
--- a/MacOSCleaner/MacOSCleanerTests/PermissionsManagerTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/PermissionsManagerTests.swift
@@ -101,4 +101,15 @@ final class PermissionsManagerTests: XCTestCase {
XCTAssertTrue(manager.showGuidance)
XCTAssertFalse(manager.guidanceDismissed)
}
+
+ func testFDAProbeTargets_excludeWorldReadableTimeMachinePlist() {
+ let targets = PermissionsManager.fdaProbeTargets(homeDirectory: "/Users/test")
+ XCTAssertFalse(
+ targets.files.contains("/Library/Preferences/com.apple.TimeMachine.plist"),
+ "World-readable TimeMachine.plist causes false-positive FDA detection"
+ )
+ XCTAssertTrue(targets.files.contains("/Library/Application Support/com.apple.TCC/TCC.db"))
+ XCTAssertTrue(targets.directories.contains("/Users/test/Library/Mail"))
+ XCTAssertTrue(targets.directories.contains("/Users/test/Library/Safari"))
+ }
}
diff --git a/MacOSCleaner/MacOSCleanerTests/PreReleaseAuditTests.swift b/MacOSCleaner/MacOSCleanerTests/PreReleaseAuditTests.swift
new file mode 100644
index 0000000..76884bd
--- /dev/null
+++ b/MacOSCleaner/MacOSCleanerTests/PreReleaseAuditTests.swift
@@ -0,0 +1,627 @@
+import XCTest
+@testable import MacOSCleaner
+
+final class PreReleaseAuditTests: XCTestCase {
+ private var fileSystemContext: FileSystemContext!
+
+ override func setUpWithError() throws {
+ try super.setUpWithError()
+ fileSystemContext = try FileSystemContext.isolatedTestRoot()
+ }
+
+ override func tearDownWithError() throws {
+ SpotlightMetadata.resetForTesting()
+ if let root = fileSystemContext?.allowedRoots.first {
+ try? FileManager.default.removeItem(at: root)
+ }
+ fileSystemContext = nil
+ try super.tearDownWithError()
+ }
+
+ // MARK: - Helpers
+
+ @discardableResult
+ private func createSyntheticApp(
+ in directory: URL,
+ name: String,
+ bundleID: String,
+ version: String = "1.0.0",
+ isElectron: Bool = false,
+ payloadBytes: Int = 512
+ ) throws -> URL {
+ let fm = FileManager.default
+ let appURL = directory.appendingPathComponent("\(name).app", isDirectory: true)
+ let contents = appURL.appendingPathComponent("Contents", isDirectory: true)
+ try fm.createDirectory(at: contents, withIntermediateDirectories: true)
+
+ let plist: [String: Any] = [
+ "CFBundleIdentifier": bundleID,
+ "CFBundleName": name,
+ "CFBundleExecutable": name,
+ "CFBundleShortVersionString": version,
+ ]
+ let plistData = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
+ try plistData.write(to: contents.appendingPathComponent("Info.plist"))
+
+ if payloadBytes > 0 {
+ let macOSDir = contents.appendingPathComponent("MacOS", isDirectory: true)
+ try fm.createDirectory(at: macOSDir, withIntermediateDirectories: true)
+ try Data(repeating: 0x5A, count: payloadBytes).write(to: macOSDir.appendingPathComponent(name))
+ }
+
+ if isElectron {
+ let framework = contents.appendingPathComponent("Frameworks/Electron Framework.framework", isDirectory: true)
+ try fm.createDirectory(at: framework, withIntermediateDirectories: true)
+ }
+
+ return appURL
+ }
+
+ // MARK: - 1. 400+ Apps Stress Simulation (Spotlight off + bounded concurrency + icon cache)
+
+ func testStress_420Apps_discoveryWithSpotlightDisabledAndBrokenSymlinks() async throws {
+ let fm = FileManager.default
+ let appsDir = fileSystemContext.homeDirectory.appendingPathComponent("Applications", isDirectory: true)
+ let utilitiesDir = appsDir.appendingPathComponent("Utilities", isDirectory: true)
+ try fm.createDirectory(at: utilitiesDir, withIntermediateDirectories: true)
+
+ // 410 normal apps + 5 Electron apps + 5 nested utilities = 420 listable apps
+ for i in 0..<410 {
+ try createSyntheticApp(
+ in: appsDir,
+ name: String(format: "StressApp%03d", i),
+ bundleID: String(format: "com.example.stressapp%03d", i),
+ payloadBytes: 256
+ )
+ }
+ for i in 0..<5 {
+ let name = "ElectronTool\(i)"
+ let bid = "com.example.electrontool\(i)"
+ try createSyntheticApp(in: appsDir, name: name, bundleID: bid, isElectron: true, payloadBytes: 256)
+ // Companion helper bundle that should collapse into parent
+ try createSyntheticApp(in: appsDir, name: "\(name) Helper", bundleID: "\(bid).helper", payloadBytes: 128)
+ }
+ for i in 0..<5 {
+ try createSyntheticApp(
+ in: utilitiesDir,
+ name: "NestedUtil\(i)",
+ bundleID: "com.example.nestedutil\(i)",
+ payloadBytes: 256
+ )
+ }
+
+ // Malformed .app without Info.plist (must be skipped cleanly, not crash)
+ let malformed = appsDir.appendingPathComponent("CorruptEmpty.app", isDirectory: true)
+ try fm.createDirectory(at: malformed, withIntermediateDirectories: true)
+
+ // Broken symlink simulating an unplugged USB drive app (must be skipped cleanly)
+ let brokenLink = appsDir.appendingPathComponent("UnpluggedUSBApp.app")
+ try fm.createSymbolicLink(atPath: brokenLink.path, withDestinationPath: "/Volumes/UnpluggedUSB_\(UUID().uuidString)/Missing.app")
+
+ // Simulate Spotlight completely disabled (issue #39)
+ SpotlightMetadata.setOverrideForTesting(
+ isIndexingAvailable: { _ in false },
+ lastUsedDate: { _ in nil }
+ )
+
+ let discovery = AppDiscovery(
+ homebrewCellarDirectories: [],
+ searchDirectories: [appsDir]
+ )
+ let service = UninstallerService(
+ fileSystemContext: fileSystemContext,
+ appDiscovery: discovery
+ )
+
+ let clock = ContinuousClock()
+ let start = clock.now
+ let discovered = try await service.scanAllApplications()
+ let elapsed = clock.now - start
+
+ XCTAssertEqual(discovered.count, 420, "All 420 primary apps should be discovered while helpers collapse and broken/corrupt bundles skip")
+ XCTAssertLessThan(elapsed, .seconds(15), "420-app discovery with in-process SecStaticCode should finish fast, took \(elapsed)")
+ XCTAssertFalse(discovered.contains { $0.name == "CorruptEmpty" })
+ XCTAssertFalse(discovered.contains { $0.name == "UnpluggedUSBApp" })
+ }
+
+ func testStress_420Icons_appIconCacheBoundsConcurrencyAndDownsamples() async throws {
+ let fm = FileManager.default
+ let appsDir = fileSystemContext.homeDirectory.appendingPathComponent("IconStressApps", isDirectory: true)
+ try fm.createDirectory(at: appsDir, withIntermediateDirectories: true)
+
+ var paths: [String] = []
+ for i in 0..<420 {
+ let dir = appsDir.appendingPathComponent("App\(i).app", isDirectory: true)
+ try fm.createDirectory(at: dir, withIntermediateDirectories: true)
+ paths.append(dir.path)
+ }
+
+ final class ConcurrencyTracker: @unchecked Sendable {
+ let lock = NSLock()
+ var active = 0
+ var peak = 0
+ var totalRenders = 0
+ var anyOnMain = false
+ }
+ let tracker = ConcurrencyTracker()
+
+ let cache = AppIconCache(
+ countLimit: 512,
+ totalCostLimit: 32 * 1024 * 1024,
+ maxConcurrentRenders: 4,
+ iconRenderer: { _, _ in
+ tracker.lock.lock()
+ tracker.active += 1
+ tracker.peak = max(tracker.peak, tracker.active)
+ tracker.totalRenders += 1
+ tracker.anyOnMain = tracker.anyOnMain || Thread.isMainThread
+ tracker.lock.unlock()
+
+ let cs = CGColorSpaceCreateDeviceRGB()
+ let info = CGImageAlphaInfo.premultipliedFirst.rawValue | CGImageByteOrderInfo.order32Host.rawValue
+ let img: NSImage? = CGContext(data: nil, width: 256, height: 256, bitsPerComponent: 8, bytesPerRow: 256 * 4, space: cs, bitmapInfo: info)
+ .flatMap { $0.makeImage() }
+ .map { NSImage(cgImage: $0, size: NSSize(width: 128, height: 128)) }
+
+ tracker.lock.lock()
+ tracker.active -= 1
+ tracker.lock.unlock()
+ return img
+ }
+ )
+
+ var loadedCount = 0
+ await withTaskGroup(of: NSImage?.self) { group in
+ for path in paths {
+ group.addTask {
+ await cache.icon(forPath: path, pixelSize: 64)
+ }
+ }
+ for await image in group {
+ if let image {
+ loadedCount += 1
+ if let rep = image.representations.first {
+ XCTAssertLessThanOrEqual(rep.pixelsWide, 64)
+ XCTAssertLessThanOrEqual(rep.pixelsHigh, 64)
+ }
+ }
+ }
+ }
+
+ XCTAssertEqual(loadedCount, 420)
+ XCTAssertLessThanOrEqual(tracker.peak, 4, "RenderGate must cap concurrent icon renders at 4")
+ XCTAssertFalse(tracker.anyOnMain, "Icon rasterization must never run on MainThread")
+ }
+
+ @MainActor
+ func testUninstallerViewModel_userCheckboxEditSurvivesBackgroundDeepScanAndSpotlightUpdatesAsync() async throws {
+ SpotlightMetadata.setOverrideForTesting(
+ isIndexingAvailable: { _ in false },
+ lastUsedDate: { _ in nil }
+ )
+
+ let apps = (0..<25).map { i in
+ UninstallerService.AppInfo(
+ url: fileSystemContext.homeDirectory.appendingPathComponent("Applications/App\(i).app"),
+ bundleID: "com.example.app\(i)",
+ name: "App\(i)",
+ scanState: .discovered
+ )
+ }
+ let targetApp = apps[20]
+ let relatedURL = fileSystemContext.homeDirectory.appendingPathComponent("Library/Caches/com.example.app20")
+
+ let vm = UninstallerViewModel(
+ discoverAppsHandler: { apps },
+ deepScanHandler: { app, _ in
+ try? await Task.sleep(for: .milliseconds(10))
+ var copy = app
+ copy.scanState = .deepScanned
+ if app.bundleID == targetApp.bundleID {
+ copy.relatedFiles = [
+ UninstallerService.RelatedFile(url: relatedURL, isSelected: true, size: 4096)
+ ]
+ }
+ return copy
+ }
+ )
+
+ vm.loadApps(mode: .safe)
+ // Wait for discovery to finish
+ for _ in 0..<50 where vm.isLoading {
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ XCTAssertEqual(vm.allApps.count, 25)
+
+ // User clicks App #20 while background deep scan is still at early apps
+ vm.selectApp(targetApp, mode: .safe)
+ for _ in 0..<50 where vm.selectedApp?.scanState != .deepScanned {
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ let file = try XCTUnwrap(vm.selectedApp?.relatedFiles.first)
+ XCTAssertTrue(file.isSelected)
+
+ // User unchecks the related file
+ vm.toggleSelection(file, in: try XCTUnwrap(vm.selectedApp))
+ XCTAssertEqual(vm.selectedApp?.relatedFiles.first?.isSelected, false)
+
+ // Wait for background deep scan loop to finish all 25 apps
+ for _ in 0..<100 where vm.isDeepScanning {
+ try await Task.sleep(for: .milliseconds(20))
+ }
+
+ // User's checkbox edit must NOT be overwritten by background deepScan loop
+ let finalApp = try XCTUnwrap(vm.allApps.first(where: { $0.bundleID == targetApp.bundleID }))
+ XCTAssertEqual(finalApp.relatedFiles.first?.isSelected, false, "Background deepScan must preserve user checkbox toggles")
+ XCTAssertEqual(vm.selectedApp?.relatedFiles.first?.isSelected, false)
+ XCTAssertFalse(vm.isSpotlightAvailable, "Async Spotlight probe must reflect disabled Spotlight")
+ }
+
+ // MARK: - 2. External SSD & USB Flash Drive Scenarios
+
+ func testExternalVolumes_safetyPolicyMatrix() {
+ let prod = FileSystemContext.production
+ let safety = SafetyManager(homeDirectory: prod.homePath, fileSystemContext: prod)
+
+ // Apps & user files on external SSD / USB flash drive: allowed for uninstall & userSelected, NEVER cleanup
+ let ssdApp = URL(fileURLWithPath: "/Volumes/SamsungSSD/Applications/BigGame.app")
+ let usbApp = URL(fileURLWithPath: "/Volumes/USB_Flash/PortableTool.app")
+ let ssdVideo = URL(fileURLWithPath: "/Volumes/SamsungSSD/Movies/clip.mov")
+
+ XCTAssertNoThrow(try safety.validate(url: ssdApp, policy: .uninstall))
+ XCTAssertNoThrow(try safety.validate(url: ssdApp, policy: .uninstallApp(bundleID: "com.example.biggame")))
+ XCTAssertNoThrow(try safety.validate(url: usbApp, policy: .uninstall))
+ XCTAssertNoThrow(try safety.validate(url: ssdVideo, policy: .userSelected))
+
+ // Automated cleanup must NEVER touch external volumes
+ XCTAssertThrowsError(try safety.validate(url: ssdApp, policy: .cleanup))
+ XCTAssertThrowsError(try safety.validate(url: ssdVideo, policy: .cleanup))
+
+ // Mount roots, Time Machine, volume metadata, and OS dirs on bootable external disks must ALWAYS be refused
+ let alwaysRefused: [String] = [
+ "/Volumes",
+ "/Volumes/SamsungSSD",
+ "/Volumes/TimeMachine/Backups.backupdb/Mac/file",
+ "/Volumes/My Time Machine/Apps/Foo.app",
+ "/Volumes/.timemachine/snapshot/Foo.app",
+ "/Volumes/Recovery/boot",
+ "/Volumes/SamsungSSD/.Spotlight-V100/Store-V2",
+ "/Volumes/SamsungSSD/.fseventsd/00001",
+ "/Volumes/SamsungSSD/.Trashes/501/item",
+ "/Volumes/SamsungSSD/Backups.backupdb/snap",
+ "/Volumes/SamsungSSD/System/Library/CoreServices",
+ "/Volumes/SamsungSSD/usr/bin/env",
+ "/Volumes/SamsungSSD/Library/Application Support/Apple/Asset",
+ "/Volumes/SamsungSSD/Library/Application Support/com.apple.TCC/TCC.db",
+ ]
+ for path in alwaysRefused {
+ let url = URL(fileURLWithPath: path)
+ XCTAssertThrowsError(try safety.validate(url: url, policy: .uninstall), "Must refuse \(path) in .uninstall")
+ XCTAssertThrowsError(try safety.validate(url: url, policy: .userSelected), "Must refuse \(path) in .userSelected")
+ XCTAssertThrowsError(try safety.validate(url: url, policy: .cleanup), "Must refuse \(path) in .cleanup")
+ }
+
+ // Root volume symlink (/Volumes/Macintosh HD/System/...) must remain hard-refused
+ if FileManager.default.fileExists(atPath: "/Volumes/Macintosh HD") {
+ let rootViaVolumes = URL(fileURLWithPath: "/Volumes/Macintosh HD/System/Library")
+ XCTAssertThrowsError(try safety.validate(url: rootViaVolumes, policy: .userSelected))
+ XCTAssertThrowsError(try safety.validate(url: rootViaVolumes, policy: .uninstall))
+ }
+ }
+
+ func testExternalVolumes_appDiscoveryFindsExternalSSDAppsAndSymlinksAndProtectsFromOrphanScanner() async throws {
+ let fm = FileManager.default
+ let root = fileSystemContext.allowedRoots[0]
+ let localApps = fileSystemContext.homeDirectory.appendingPathComponent("Applications", isDirectory: true)
+ let fakeVolumes = root.appendingPathComponent("FakeVolumes", isDirectory: true)
+ let ssdApps = fakeVolumes.appendingPathComponent("ExternalSSD/Applications", isDirectory: true)
+ let ssdOffload = fakeVolumes.appendingPathComponent("ExternalSSD/Offloaded", isDirectory: true)
+ let tmApps = fakeVolumes.appendingPathComponent("TimeMachineBackup/Applications", isDirectory: true)
+
+ try fm.createDirectory(at: localApps, withIntermediateDirectories: true)
+ try fm.createDirectory(at: ssdApps, withIntermediateDirectories: true)
+ try fm.createDirectory(at: ssdOffload, withIntermediateDirectories: true)
+ try fm.createDirectory(at: tmApps, withIntermediateDirectories: true)
+
+ // 1. App installed directly on ExternalSSD/Applications
+ try createSyntheticApp(in: ssdApps, name: "ExternalGame", bundleID: "com.example.externalgame")
+
+ // 2. App stored on ExternalSSD and symlinked into ~/Applications
+ let offloadedTarget = try createSyntheticApp(in: ssdOffload, name: "SymlinkedEditor", bundleID: "com.example.symlinkededitor")
+ let appSymlink = localApps.appendingPathComponent("SymlinkedEditor.app")
+ try fm.createSymbolicLink(at: appSymlink, withDestinationURL: offloadedTarget)
+
+ // 3. App on Time Machine backup volume (must NOT be discovered!)
+ try createSyntheticApp(in: tmApps, name: "BackupOnlyApp", bundleID: "com.example.backuponly")
+
+ // 4. Broken symlink for unplugged flash drive (must NOT crash or appear)
+ let unpluggedLink = localApps.appendingPathComponent("UnpluggedStickApp.app")
+ try fm.createSymbolicLink(atPath: unpluggedLink.path, withDestinationPath: "/Volumes/MissingUSB_\(UUID().uuidString)/App.app")
+
+ let discovery = AppDiscovery(
+ homebrewCellarDirectories: [],
+ searchDirectories: [localApps],
+ externalVolumesRoot: fakeVolumes
+ )
+ let discoveredURLs = await discovery.findAll()
+ let discoveredNames = Set(discoveredURLs.map { $0.deletingPathExtension().lastPathComponent })
+
+ XCTAssertTrue(discoveredNames.contains("ExternalGame"), "Should discover apps under /Applications")
+ XCTAssertTrue(discoveredNames.contains("SymlinkedEditor"), "Should discover symlinked .app bundles pointing to external SSD")
+ XCTAssertFalse(discoveredNames.contains("BackupOnlyApp"), "Must skip Time Machine backup volumes")
+ XCTAssertFalse(discoveredNames.contains("UnpluggedStickApp"), "Must safely skip broken symlinks to unplugged USB drives")
+
+ // Verify OrphanScanner does NOT treat ExternalGame's ~/Library data as orphaned!
+ let appSupport = fileSystemContext.homeDirectory
+ .appendingPathComponent("Library/Application Support/com.example.externalgame", isDirectory: true)
+ try fm.createDirectory(at: appSupport, withIntermediateDirectories: true)
+ try Data(repeating: 1, count: 16 * 1024).write(to: appSupport.appendingPathComponent("save.dat"))
+
+ let safety = SafetyManager(homeDirectory: fileSystemContext.homePath, fileSystemContext: fileSystemContext)
+ let orphanScanner = OrphanScanner(
+ safetyManager: safety,
+ fileSystemContext: fileSystemContext,
+ appDiscovery: discovery
+ )
+ let orphans = try await orphanScanner.scanOrphans()
+ XCTAssertFalse(
+ orphans.contains { $0.url.path.lowercased().contains("externalgame") },
+ "Data belonging to an app installed on an external SSD must NEVER be flagged as an orphan"
+ )
+ }
+
+ func testExternalVolumes_duplicateFinderAllowsExplicitExternalVolumeOnly() async {
+ let engine = DuplicateFinderEngine()
+ let extPhoto = "/Volumes/ExternalSSD/Photos/IMG_0001.jpg"
+ let tmFile = "/Volumes/TimeMachine/Backups.backupdb/IMG_0001.jpg"
+ let extSystem = "/Volumes/ExternalSSD/System/Library/data.bin"
+
+ let allowedExplicit = await engine.isSafeUserFilePath(extPhoto, allowExternalVolumes: true)
+ let blockedImplicit = await engine.isSafeUserFilePath(extPhoto, allowExternalVolumes: false)
+ let blockedTM = await engine.isSafeUserFilePath(tmFile, allowExternalVolumes: true)
+ let blockedSys = await engine.isSafeUserFilePath(extSystem, allowExternalVolumes: true)
+
+ XCTAssertTrue(allowedExplicit, "Explicitly chosen external SSD folder must be scannable in Duplicates")
+ XCTAssertFalse(blockedImplicit, "Implicit home scan must never roam into /Volumes")
+ XCTAssertFalse(blockedTM, "Time Machine backups on external drives must never be scanned")
+ XCTAssertFalse(blockedSys, "OS system dirs on bootable external drives must never be scanned")
+ }
+
+ func testUninstall_unpluggedOrReadOnlyAppReportsFailureInsteadOfSilentSuccess() async throws {
+ let fm = FileManager.default
+ let appsDir = fileSystemContext.homeDirectory.appendingPathComponent("Applications", isDirectory: true)
+ let cacheDir = fileSystemContext.homeDirectory.appendingPathComponent("Library/Caches/com.example.lockedapp", isDirectory: true)
+ let trashDir = fileSystemContext.allowedRoots[0].appendingPathComponent("IsolatedTrash", isDirectory: true)
+ try fm.createDirectory(at: appsDir, withIntermediateDirectories: true)
+ try fm.createDirectory(at: cacheDir, withIntermediateDirectories: true)
+ try fm.createDirectory(at: trashDir, withIntermediateDirectories: true)
+ try Data(repeating: 7, count: 4096).write(to: cacheDir.appendingPathComponent("cache.bin"))
+
+ // Case 1: App bundle disappeared (unplugged USB drive) before uninstall — fails cleanly, no crash
+ let missingApp = UninstallerService.AppInfo(
+ url: appsDir.appendingPathComponent("Unplugged.app"),
+ bundleID: "com.example.unplugged",
+ name: "Unplugged"
+ )
+ let safety = SafetyManager(homeDirectory: fileSystemContext.homePath, fileSystemContext: fileSystemContext)
+ let trash = TrashManager(safetyManager: safety, trashDirectoryURL: trashDir)
+ let service = UninstallerService(
+ safetyManager: safety,
+ trashManager: trash,
+ fileSystemContext: fileSystemContext
+ )
+
+ do {
+ _ = try await service.uninstall(app: missingApp, bypassTrash: false, removeFromDock: false)
+ XCTFail("Uninstalling an unplugged/missing app with no other targets should throw")
+ } catch {
+ // Expected failure
+ }
+
+ // Case 2: App bundle on read-only directory while related cache succeeds — app.url must appear in failedDeletions
+ let readOnlyDir = appsDir.appendingPathComponent("ReadOnlyVolume", isDirectory: true)
+ try fm.createDirectory(at: readOnlyDir, withIntermediateDirectories: true)
+ let lockedAppURL = try createSyntheticApp(in: readOnlyDir, name: "LockedApp", bundleID: "com.example.lockedapp")
+ // Make parent read-only so moving LockedApp.app fails (simulates read-only DMG/USB)
+ try fm.setAttributes([.posixPermissions: 0o555], ofItemAtPath: readOnlyDir.path)
+ defer { try? fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: readOnlyDir.path) }
+
+ let lockedInfo = UninstallerService.AppInfo(
+ url: lockedAppURL,
+ bundleID: "com.example.lockedapp",
+ name: "LockedApp",
+ relatedFiles: [
+ UninstallerService.RelatedFile(url: cacheDir, isSelected: true, size: 4096)
+ ]
+ )
+
+ let report = try await service.uninstall(app: lockedInfo, bypassTrash: false, removeFromDock: false)
+ XCTAssertTrue(fm.fileExists(atPath: lockedAppURL.path), "App in read-only parent should remain on disk")
+ let failedURLs = Set((report?.failedDeletions ?? []).map { NormalizedPath.key($0.url) })
+ XCTAssertTrue(
+ failedURLs.contains(NormalizedPath.key(lockedAppURL)),
+ "Uninstall must report failed app.url in failedDeletions instead of silently claiming success"
+ )
+ }
+
+ // MARK: - 3. Disabled macOS Features (Spotlight, FDA, Time Machine, Xcode/CLT, Apple Intelligence)
+
+ func testDisabledFeatures_noXcodeCLTDoesNotInvokeXcrun() async throws {
+ final class CallRecorder: @unchecked Sendable {
+ let lock = NSLock()
+ var commands: [String] = []
+ func record(_ cmd: String) {
+ lock.lock(); commands.append(cmd); lock.unlock()
+ }
+ func snapshot() -> [String] {
+ lock.lock(); defer { lock.unlock() }; return commands
+ }
+ }
+ let recorder = CallRecorder()
+ let mock = MockCommandRunner()
+ mock.runHandler = { cmd, args in
+ recorder.record(([cmd] + args).joined(separator: " "))
+ if cmd == "/usr/bin/xcode-select" {
+ return CommandResult(stdout: "", stderr: "xcode-select: error: unable to get active developer directory", exitCode: 2)
+ }
+ return CommandResult(stdout: "", stderr: "", exitCode: 1)
+ }
+
+ // Create CoreSimulator folder so the guard actually reaches xcode-select check
+ let simDir = fileSystemContext.homeDirectory.appendingPathComponent("Library/Developer/CoreSimulator", isDirectory: true)
+ try FileManager.default.createDirectory(at: simDir, withIntermediateDirectories: true)
+
+ let engine = CleanupEngine(commandRunner: mock, fileSystemContext: fileSystemContext)
+ _ = try await engine.run(categories: [.iosSimulators], dryRun: true)
+
+ let ran = recorder.snapshot()
+ XCTAssertFalse(
+ ran.contains { $0.contains("xcrun") || $0.contains("simctl") },
+ "Must never invoke /usr/bin/xcrun shim when Xcode is absent (avoids macOS CLT install popup): \(ran)"
+ )
+ }
+
+ func testDisabledFeatures_timeMachineDisabledAndTCCNoFDAAndAppleIntelligenceRestricted() async {
+ // 1. Time Machine daemon disabled / tmutil fails
+ let tmMock = MockCommandRunner()
+ tmMock.runHandler = { _, _ in
+ CommandResult(stdout: "", stderr: "The operation couldn't be completed (Time Machine disabled)", exitCode: 1)
+ }
+ let snapshots = await TimeMachineScanner.listLocalSnapshots(commandRunner: tmMock)
+ XCTAssertTrue(snapshots.isEmpty)
+
+ // 2. TCC database inaccessible without FDA
+ let missingDB = fileSystemContext.homeDirectory.appendingPathComponent("NoSuchTCC.db").path
+ let tccService = TCCService(
+ commandRunner: MockCommandRunner(),
+ userDBPath: missingDB,
+ systemDBPath: missingDB,
+ hasFullDiskAccessProvider: { false }
+ )
+ let tccSnapshot = await tccService.loadSnapshot()
+ XCTAssertTrue(tccSnapshot.groups.isEmpty)
+
+ // 3. Apple Intelligence assets missing / restricted
+ let missingAssets = fileSystemContext.homeDirectory.appendingPathComponent("MissingAssetsV2").path
+ let aiSnap = AppleIntelligenceStorageReader.inspect(
+ components: [.init(id: "test", titleKey: "test", path: missingAssets)],
+ baseModelPath: missingAssets
+ )
+ XCTAssertTrue(aiSnap.components.isEmpty)
+ XCTAssertTrue(aiSnap.isBaseModelAccessRestricted)
+ XCTAssertNil(aiSnap.baseModelReadableBytes)
+ }
+
+ func testDisabledFeatures_cleanupHandlesUnreadableCacheDirWithoutCrashing() async throws {
+ let fm = FileManager.default
+ let cachesDir = fileSystemContext.homeDirectory.appendingPathComponent("Library/Caches", isDirectory: true)
+ let lockedDir = cachesDir.appendingPathComponent("com.example.lockedcache", isDirectory: true)
+ let readableDir = cachesDir.appendingPathComponent("com.example.readablecache", isDirectory: true)
+ try fm.createDirectory(at: lockedDir, withIntermediateDirectories: true)
+ try fm.createDirectory(at: readableDir, withIntermediateDirectories: true)
+ try Data(repeating: 0x11, count: 8192).write(to: lockedDir.appendingPathComponent("secret.bin"))
+ try Data(repeating: 0x22, count: 8192).write(to: readableDir.appendingPathComponent("temp.bin"))
+
+ try fm.setAttributes([.posixPermissions: 0o000], ofItemAtPath: lockedDir.path)
+ defer { try? fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: lockedDir.path) }
+
+ let safety = SafetyManager(homeDirectory: fileSystemContext.homePath, fileSystemContext: fileSystemContext)
+ let engine = CleanupEngine(safetyManager: safety, fileSystemContext: fileSystemContext)
+
+ var options = CleanupOptions()
+ options.bypassTrash = true
+ let results = try await engine.run(categories: [.appCaches], dryRun: false, options: options)
+ XCTAssertFalse(results.isEmpty)
+ XCTAssertFalse(fm.fileExists(atPath: readableDir.appendingPathComponent("temp.bin").path), "Readable third-party cache must still clean despite EPERM sibling")
+ }
+
+ // MARK: - 4. End-to-End Browser Extensions & Banking Data Protection (Jovo complaint)
+
+ func testBrowserProtection_fullCleanupAndChromeUninstallAndPWAShimNeverDestroyExtensions() async throws {
+ let fm = FileManager.default
+ let home = fileSystemContext.homeDirectory
+ let chromeRoot = home.appendingPathComponent("Library/Application Support/Google/Chrome", isDirectory: true)
+ let profile = chromeRoot.appendingPathComponent("Default", isDirectory: true)
+
+ // Critical user/banking extension & session artifacts that must NEVER be touched by Cleanup
+ let protectedFiles: [URL] = [
+ profile.appendingPathComponent("Extensions/bankext123/1.0/manifest.json"),
+ profile.appendingPathComponent("Extensions/bankext123/1.0/cache/payment_cert.bin"),
+ profile.appendingPathComponent("Local Extension Settings/bankext123/000003.log"),
+ profile.appendingPathComponent("Local Storage/leveldb/000003.log"),
+ profile.appendingPathComponent("IndexedDB/https_bank.example.com_0.indexeddb.leveldb/000003.log"),
+ profile.appendingPathComponent("Cookies"),
+ profile.appendingPathComponent("Login Data"),
+ profile.appendingPathComponent("Secure Preferences"),
+ chromeRoot.appendingPathComponent("NativeMessagingHosts/com.bank.signer.json"),
+ ]
+ for file in protectedFiles {
+ try fm.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(repeating: 0xAB, count: 4096).write(to: file)
+ }
+
+ // Allowed regenerable Chrome caches
+ let allowedCacheFile = profile.appendingPathComponent("Cache/Cache_Data/f_0001")
+ let allowedCodeCache = profile.appendingPathComponent("Code Cache/js/c_0001")
+ for file in [allowedCacheFile, allowedCodeCache] {
+ try fm.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(repeating: 0xCD, count: 8192).write(to: file)
+ }
+
+ let trashDir = fileSystemContext.allowedRoots[0].appendingPathComponent("CleanupTrash", isDirectory: true)
+ try fm.createDirectory(at: trashDir, withIntermediateDirectories: true)
+ let safety = SafetyManager(homeDirectory: fileSystemContext.homePath, fileSystemContext: fileSystemContext)
+ let trash = TrashManager(safetyManager: safety, trashDirectoryURL: trashDir)
+
+ // Step 1: Run Cleanup across browser, chromeExtra, appCaches, ideCaches, dynamicCacheDiscovery
+ let engine = CleanupEngine(safetyManager: safety, fileSystemContext: fileSystemContext)
+ var cleanupOptions = CleanupOptions()
+ cleanupOptions.bypassTrash = true
+ _ = try await engine.run(
+ categories: [.browserCaches, .chromeExtraCaches, .appCaches, .ideCaches, .dynamicCacheDiscovery],
+ dryRun: false,
+ options: cleanupOptions
+ )
+
+ for file in protectedFiles {
+ XCTAssertTrue(fm.fileExists(atPath: file.path), "Cleanup MUST NEVER delete \(file.path)")
+ }
+ XCTAssertFalse(fm.fileExists(atPath: allowedCacheFile.path), "Allowed Chrome Cache_Data should be cleaned")
+ XCTAssertFalse(fm.fileExists(atPath: allowedCodeCache.path), "Allowed Chrome Code Cache should be cleaned")
+
+ // Step 2: Uninstall a Chrome PWA banking app — Chrome profile & extensions must stay 100% untouched
+ let appsDir = home.appendingPathComponent("Applications", isDirectory: true)
+ let pwaApp = try createSyntheticApp(in: appsDir, name: "MyBank Payment", bundleID: "com.google.Chrome.app.bankpay123")
+ let service = UninstallerService(safetyManager: safety, trashManager: trash, fileSystemContext: fileSystemContext)
+
+ let scannedPWA = try await service.scan(appURL: pwaApp)
+ let deepPWA = try await service.deepScan(scannedPWA, mode: .balanced)
+ XCTAssertFalse(deepPWA.relatedFiles.contains { $0.url.path.lowercased().contains("/google/chrome") })
+ _ = try await service.uninstall(app: deepPWA, bypassTrash: false, removeFromDock: false)
+
+ for file in protectedFiles {
+ XCTAssertTrue(fm.fileExists(atPath: file.path), "Uninstalling Chrome PWA must NEVER touch \(file.path)")
+ }
+
+ // Step 3: Uninstall Chrome with browser data left unselected (default) —
+ // VerificationEngine must NOT surface intentionally kept browser data as pre-selected leftovers.
+ let chromeApp = try createSyntheticApp(in: appsDir, name: "Google Chrome", bundleID: "com.google.Chrome")
+ let scannedChrome = try await service.scan(appURL: chromeApp)
+ let deepChrome = try await service.deepScan(scannedChrome, mode: .balanced)
+ XCTAssertTrue(
+ deepChrome.relatedFiles.filter(\.isBrowserData).allSatisfy { !$0.isSelected },
+ "Chrome browser data must be unselected by default"
+ )
+
+ let report = try await service.uninstall(app: deepChrome, bypassTrash: false, removeFromDock: false)
+ for file in protectedFiles {
+ XCTAssertTrue(fm.fileExists(atPath: file.path), "Keeping Chrome profile unchecked must preserve \(file.path)")
+ }
+ if let report {
+ XCTAssertFalse(
+ report.items.contains { $0.isSelected && safety.isBrowserUserDataPath($0.url.path) },
+ "Post-uninstall verification must never pre-select kept browser user data"
+ )
+ }
+ }
+}
diff --git a/MacOSCleaner/MacOSCleanerTests/RegistryPathsTests.swift b/MacOSCleaner/MacOSCleanerTests/RegistryPathsTests.swift
index 78c96cf..9d96d9b 100644
--- a/MacOSCleaner/MacOSCleanerTests/RegistryPathsTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/RegistryPathsTests.swift
@@ -338,6 +338,34 @@ final class RegistryPathsTests: XCTestCase {
XCTAssertTrue(RegistryPathTemplates.uninstallTemplates(forBundleID: "com.google.Chrome").isEmpty)
}
+ func test_chromePWAShimDoesNotMatchParentPrefixIndex() {
+ let wire = PrivateCatalogWire(
+ formatVersion: PrivateCatalogFormat.formatVersion,
+ engineHash: "fixture",
+ uiHash: "fixture-ui",
+ watermarks: [],
+ apps: [
+ PrivateCatalogWireApp(
+ key: "com.google.Chrome",
+ bundleIDs: ["com.google.Chrome"],
+ bundleIDPrefixes: ["com.google.Chrome."],
+ category: CleanupCategory.browserCaches.rawValue,
+ paths: [
+ PrivateCatalogWirePath(template: "/Google/Chrome", purpose: "app_data", isGlob: false, requiresAdmin: false),
+ ]
+ ),
+ ],
+ toolchains: [],
+ uiApps: [],
+ uiToolchains: []
+ )
+ PrivateCatalogStore.setOverrideForTesting(PrivateCatalogCodec.snapshot(from: wire, source: .privateAsset))
+ defer { PrivateCatalogStore.resetForTesting() }
+
+ XCTAssertNotNil(GeneratedCleanupPaths.appPaths(forBundleID: "com.google.Chrome"))
+ XCTAssertNil(GeneratedCleanupPaths.appPaths(forBundleID: "com.google.Chrome.app.aghbiahbpaij"))
+ }
+
func test_watermarksNeverBecomeCleanupPaths() throws {
try CatalogTestSupport.requirePrivateCatalog()
let marks = GeneratedCleanupPaths.watermarks
diff --git a/MacOSCleaner/MacOSCleanerTests/Rules/ApplicationRuleRegistryTests.swift b/MacOSCleaner/MacOSCleanerTests/Rules/ApplicationRuleRegistryTests.swift
index 6743be9..f67c89f 100644
--- a/MacOSCleaner/MacOSCleanerTests/Rules/ApplicationRuleRegistryTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/Rules/ApplicationRuleRegistryTests.swift
@@ -144,6 +144,86 @@ final class BrowserRuleTests: XCTestCase {
let evidence = rule.evidence(for: url, identity: identity)
XCTAssertTrue(evidence.contains { $0.source == .appName })
}
+
+ func test_doesNotMatch_googleDrive_chromePWA_or_substringApps() {
+ let rule = BrowserRule()
+
+ let googleDrive = AppIdentity(
+ bundleID: "com.google.drivefs",
+ appName: "Google Drive",
+ bundleName: "Google Drive", bundleVersion: nil,
+ executableName: "Google Drive",
+ teamID: "EQHXZ8M8AV", signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "/Applications/Google Drive.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: ["Google"], helperNames: [], frameworkNames: [],
+ xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false,
+ isJava: false, isQt: false, isDocker: false
+ )
+ XCTAssertFalse(rule.matches(identity: googleDrive))
+ XCTAssertTrue(
+ rule.evidence(
+ for: URL(fileURLWithPath: "/Users/test/Library/Application Support/Google/Chrome/Default"),
+ identity: googleDrive
+ ).isEmpty
+ )
+
+ let chromePWA = AppIdentity(
+ bundleID: "com.google.Chrome.app.aghbiahbpaij",
+ appName: "Banking Portal",
+ bundleName: "Chrome", bundleVersion: nil,
+ executableName: "app_mode_loader",
+ teamID: "EQHXZ8M8AV", signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "/Users/test/Applications/Chrome Apps.localized/Banking Portal.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: ["Google"], helperNames: [], frameworkNames: [],
+ xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false,
+ isJava: false, isQt: false, isDocker: false
+ )
+ XCTAssertFalse(rule.matches(identity: chromePWA))
+ XCTAssertTrue(
+ rule.evidence(
+ for: URL(fileURLWithPath: "/Users/test/Library/Application Support/Google/Chrome/Default"),
+ identity: chromePWA
+ ).isEmpty
+ )
+
+ let pixelmator = AppIdentity(
+ bundleID: "com.pixelmatorteam.pixelmator.x",
+ appName: "Pixelmator Pro",
+ bundleName: nil, bundleVersion: nil,
+ executableName: "Pixelmator Pro",
+ teamID: nil, signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "/Applications/Pixelmator Pro.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: [], helperNames: [], frameworkNames: [],
+ xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false,
+ isJava: false, isQt: false, isDocker: false
+ )
+ XCTAssertFalse(rule.matches(identity: pixelmator))
+ }
+
+ func test_chromeCanary_doesNotScoreStableChromeFolder() {
+ let rule = BrowserRule()
+ let canary = AppIdentity(
+ bundleID: "com.google.Chrome.canary",
+ appName: "Google Chrome Canary",
+ bundleName: "Chrome Canary", bundleVersion: nil,
+ executableName: "Google Chrome Canary",
+ teamID: "EQHXZ8M8AV", signingAuthority: nil,
+ bundleURL: URL(fileURLWithPath: "/Applications/Google Chrome Canary.app"),
+ isAppStore: false, isSandboxed: false, isAdHocSigned: false,
+ vendorNames: ["Google"], helperNames: [], frameworkNames: [],
+ xpcServiceNames: [], plugInNames: [],
+ isElectron: false, isJetBrains: false, isFlutter: false,
+ isJava: false, isQt: false, isDocker: false
+ )
+ let stableDefault = URL(fileURLWithPath: "/Users/test/Library/Application Support/Google/Chrome/Default")
+ XCTAssertTrue(rule.evidence(for: stableDefault, identity: canary).isEmpty)
+ }
}
final class DockerRuleTests: XCTestCase {
diff --git a/MacOSCleaner/MacOSCleanerTests/SafetyManagerTests.swift b/MacOSCleaner/MacOSCleanerTests/SafetyManagerTests.swift
index c9a9922..e424280 100644
--- a/MacOSCleaner/MacOSCleanerTests/SafetyManagerTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/SafetyManagerTests.swift
@@ -257,19 +257,141 @@ final class SafetyManagerTests: XCTestCase {
}
}
- func testUninstallPolicyAllowsBrowserUserDataRemoval() {
- let allowed = [
- "\(home)/Library/Application Support/Google/Chrome",
- "\(home)/Library/Application Support/Google/Chrome/Default",
- "\(home)/Library/Application Support/Google",
+ func testUninstallPolicyBlocksBrowserUserDataForGenericAndForeignApps() {
+ let chromeRoot = "\(home)/Library/Application Support/Google/Chrome"
+ let chromeDefault = "\(chromeRoot)/Default"
+ let googleParent = "\(home)/Library/Application Support/Google"
+ let loginData = "\(chromeDefault)/Login Data"
+ let sysChrome = "/Library/Application Support/Google/Chrome"
+
+ // Generic .uninstall (e.g. OrphanScanner) must NEVER delete browser profiles or ancestors.
+ for path in [chromeRoot, chromeDefault, googleParent, sysChrome] {
+ XCTAssertThrowsError(
+ try safetyManager.validate(url: URL(fileURLWithPath: path), policy: .uninstall),
+ "Generic .uninstall must block \(path)"
+ )
+ }
+
+ // Foreign apps (Google Drive with same Team ID, Chrome Canary, Chrome PWA shim) must be blocked.
+ for foreignBundleID in ["com.google.drivefs", "com.google.Chrome.canary", "com.google.Chrome.app.aghbiahbpaij"] {
+ let policy = DeletionPolicy.uninstallApp(bundleID: foreignBundleID)
+ for path in [chromeRoot, chromeDefault, googleParent, sysChrome] {
+ XCTAssertThrowsError(
+ try safetyManager.validate(url: URL(fileURLWithPath: path), policy: policy),
+ "Uninstalling \(foreignBundleID) must not touch \(path)"
+ )
+ }
+ }
+
+ // Uninstalling Chrome itself may target Chrome's own user-data folder,
+ // while keeping the shared Google parent, system host folder, and credentials blocked.
+ let chromePolicy = DeletionPolicy.uninstallApp(bundleID: "com.google.Chrome")
+ XCTAssertNoThrow(try safetyManager.validate(url: URL(fileURLWithPath: chromeRoot), policy: chromePolicy))
+ XCTAssertNoThrow(try safetyManager.validate(url: URL(fileURLWithPath: chromeDefault), policy: chromePolicy))
+ XCTAssertThrowsError(try safetyManager.validate(url: URL(fileURLWithPath: googleParent), policy: chromePolicy))
+ XCTAssertThrowsError(try safetyManager.validate(url: URL(fileURLWithPath: sysChrome), policy: chromePolicy))
+ XCTAssertThrowsError(try safetyManager.validate(url: URL(fileURLWithPath: loginData), policy: chromePolicy))
+ }
+
+ func testCleanupBlocksExtensionsAndNestedCacheFoldersInProfiles() {
+ let blocked = [
+ "\(home)/Library/Application Support/Google/Chrome/Default/Extensions/cjpalhdlnbpafiamejdnhcphjbkeiagm/1.60.0_0/cache/data.bin",
+ "\(home)/Library/Application Support/Google/Chrome/Default/Local Extension Settings/cjpalhdlnbpafiamejdnhcphjbkeiagm/thumbnails/icon.png",
+ "\(home)/Library/Application Support/Google/Chrome/Default/Local Extension Storage/cjpalhdlnbpafiamejdnhcphjbkeiagm/cache",
+ "\(home)/Library/Application Support/Google/Chrome/Default/IndexedDB/https_bank.example_0.indexeddb.leveldb/cachestorage",
+ "\(home)/Library/Application Support/Google/Chrome/Default/Service Worker",
+ "\(home)/Library/Application Support/Google/Chrome/Default/Service Worker/Database",
+ "\(home)/Library/Application Support/Google/Chrome/Default/Session Storage",
+ "\(home)/Library/Application Support/Google/Chrome/Default/Sync Data",
+ "\(home)/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.bank.token.json",
+ "\(home)/Library/Application Support/Google/Chrome/External Extensions/ext.json",
+ "\(home)/Library/Application Support/Firefox/Profiles/abcd.default-release/storage/default/https+++bank/cache",
+ "/Library/Application Support/Google/Chrome/External Extensions/ext.json",
+ "/Library/Google/Chrome/NativeMessagingHosts/com.bank.token.json",
]
- for path in allowed {
+ for path in blocked {
+ XCTAssertThrowsError(
+ try safetyManager.validate(url: URL(fileURLWithPath: path), policy: .cleanup),
+ "Cleanup must block nested/protected browser path \(path)"
+ )
+ }
+ }
+
+ func testBrowserProtectionIsCaseInsensitiveAndHandlesSymlinkedHome() throws {
+ // Mixed/wrong casing on APFS must still be protected.
+ let casedPaths = [
+ "\(home)/library/application support/google/CHROME/Default/Extensions/ext/1.0/cache/file",
+ "\(home)/LIBRARY/Application Support/Google/chrome/Default/Bookmarks",
+ "\(home)/Library/Application Support/ARC/User Data/Default/History",
+ ]
+ for path in casedPaths {
let url = URL(fileURLWithPath: path)
- XCTAssertNoThrow(try safetyManager.validate(url: url, policy: .uninstall), "Uninstall must allow \(path)")
+ XCTAssertThrowsError(try safetyManager.validate(url: url, policy: .cleanup))
+ XCTAssertThrowsError(try safetyManager.validate(url: url, policy: .uninstall))
+ XCTAssertThrowsError(try safetyManager.validate(url: url, policy: .uninstallApp(bundleID: "com.google.drivefs")))
+ }
+
+ // Symlinked home directory (e.g. /Users/alex -> /Volumes/Data/Users/alex)
+ let parentRoot = fileSystemContext.allowedRoots[0]
+ let realHome = parentRoot.appendingPathComponent("RealHome", isDirectory: true)
+ let symlinkHome = parentRoot.appendingPathComponent("SymlinkHome", isDirectory: true)
+ let chromeDefault = realHome.appendingPathComponent("Library/Application Support/Google/Chrome/Default/Extensions/ext/cache", isDirectory: true)
+ try FileManager.default.createDirectory(at: chromeDefault, withIntermediateDirectories: true)
+ try FileManager.default.createSymbolicLink(at: symlinkHome, withDestinationURL: realHome)
+
+ let ctx = FileSystemContext(homeDirectory: symlinkHome, allowedRoots: [parentRoot], enforceAllowedRoots: true)
+ let managerReal = SafetyManager(homeDirectory: realHome.path, fileSystemContext: ctx)
+ let managerSym = SafetyManager(homeDirectory: symlinkHome.path, fileSystemContext: ctx)
+
+ let viaSym = symlinkHome.appendingPathComponent("Library/Application Support/Google/Chrome/Default/Extensions/ext/cache")
+ let viaReal = realHome.appendingPathComponent("Library/Application Support/Google/Chrome/Default/Extensions/ext/cache")
+ let viaSymRoot = symlinkHome.appendingPathComponent("Library/Application Support/Google/Chrome")
+
+ XCTAssertThrowsError(try managerReal.validate(url: viaSym, policy: .cleanup))
+ XCTAssertThrowsError(try managerSym.validate(url: viaReal, policy: .cleanup))
+ XCTAssertThrowsError(try managerReal.validate(url: viaSymRoot, policy: .uninstallApp(bundleID: "com.google.drivefs")))
+ XCTAssertThrowsError(try managerSym.validate(url: viaSymRoot, policy: .uninstall))
+ }
+
+ func testAllBrowserRootsProtectedAndCachesAllowed() {
+ let protectedAllPolicies = [
+ "\(home)/Library/Application Support/Arc/StorableSidebar.json",
+ "\(home)/Library/Application Support/Orion/Defaults",
+ "\(home)/Library/Application Support/DuckDuckGo/SessionData",
+ "\(home)/Library/Application Support/Yandex/YandexBrowser/Default/Bookmarks",
+ "\(home)/Library/Application Support/Firefox/Crash Reports",
+ "\(home)/Library/Application Support/Mozilla/Firefox/Profiles/abc/cookies.sqlite",
+ "\(home)/Library/Application Support/Waterfox/Profiles/abc/logins.json",
+ "\(home)/Library/Application Support/LibreWolf/Profiles/abc/places.sqlite",
+ "\(home)/Library/Application Support/MullvadBrowser/Profiles/abc/cookies.sqlite",
+ "\(home)/Library/Application Support/TorBrowser-Data/Browser/profile.default",
+ "\(home)/Library/Safari/Bookmarks.plist",
+ "\(home)/Library/Containers/com.apple.Safari/Data/Library/Safari/History.db",
+ "\(home)/Library/WebKit/com.apple.Safari",
+ ]
+ for path in protectedAllPolicies {
+ let url = URL(fileURLWithPath: path)
+ XCTAssertThrowsError(try safetyManager.validate(url: url, policy: .cleanup), "Cleanup must block \(path)")
+ XCTAssertThrowsError(try safetyManager.validate(url: url, policy: .uninstall), "Uninstall must block \(path)")
+ XCTAssertThrowsError(try safetyManager.validate(url: url, policy: .uninstallApp(bundleID: "com.example.other")))
+ }
+
+ // System-protected Safari cannot be deleted even when passing Safari's bundle ID.
+ XCTAssertThrowsError(try safetyManager.validate(
+ url: URL(fileURLWithPath: "\(home)/Library/Safari"),
+ policy: .uninstallApp(bundleID: "com.apple.Safari")
+ ))
+
+ // Narrow caches stay cleanable under .cleanup.
+ let allowedCaches = [
+ "\(home)/Library/Application Support/Arc/User Data/Default/Cache",
+ "\(home)/Library/Application Support/BraveSoftware/Brave-Browser/Default/Code Cache",
+ "\(home)/Library/Application Support/Yandex/YandexBrowser/Default/GPUCache",
+ "\(home)/Library/Safari/Favicon Cache",
+ ]
+ for path in allowedCaches {
+ XCTAssertNoThrow(try safetyManager.validate(url: URL(fileURLWithPath: path), policy: .cleanup), "Cleanup must allow \(path)")
}
- // Credential files stay hard-protected even during uninstall
- let loginData = URL(fileURLWithPath: "\(home)/Library/Application Support/Google/Chrome/Default/Login Data")
- XCTAssertThrowsError(try safetyManager.validate(url: loginData, policy: .uninstall))
}
func testCleanupBlocksCredentialFilesInApplicationSupport() {
diff --git a/MacOSCleaner/MacOSCleanerTests/UninstallerServiceTests.swift b/MacOSCleaner/MacOSCleanerTests/UninstallerServiceTests.swift
index e0e5afe..0482c83 100644
--- a/MacOSCleaner/MacOSCleanerTests/UninstallerServiceTests.swift
+++ b/MacOSCleaner/MacOSCleanerTests/UninstallerServiceTests.swift
@@ -345,4 +345,347 @@ final class UninstallerServiceTests: XCTestCase {
)
XCTAssertFalse(app.isIntelOnly)
}
+
+ func testDeepScan_chromeProfileNeverPreselectedAndDriveDoesNotTouchChrome() async throws {
+ let ctx = try FileSystemContext.isolatedTestRoot()
+ defer { try? FileManager.default.removeItem(at: ctx.allowedRoots[0]) }
+
+ let appsDir = ctx.homeDirectory.appendingPathComponent("Applications", isDirectory: true)
+ let chromeApp = appsDir.appendingPathComponent("Google Chrome.app", isDirectory: true)
+ let driveApp = appsDir.appendingPathComponent("Google Drive.app", isDirectory: true)
+ let chromeProfile = ctx.homeDirectory.appendingPathComponent("Library/Application Support/Google/Chrome", isDirectory: true)
+ let chromeDefault = chromeProfile.appendingPathComponent("Default/Extensions/ext1", isDirectory: true)
+ let chromeCache = ctx.homeDirectory.appendingPathComponent("Library/Caches/com.google.Chrome", isDirectory: true)
+
+ for (app, bid, name) in [
+ (chromeApp, "com.google.Chrome", "Google Chrome"),
+ (driveApp, "com.google.drivefs", "Google Drive"),
+ ] {
+ let contents = app.appendingPathComponent("Contents", isDirectory: true)
+ try FileManager.default.createDirectory(at: contents, withIntermediateDirectories: true)
+ let plist: [String: Any] = [
+ "CFBundleIdentifier": bid,
+ "CFBundleName": name,
+ "CFBundleExecutable": name,
+ "CFBundleShortVersionString": "1.0",
+ ]
+ let data = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
+ try data.write(to: contents.appendingPathComponent("Info.plist"))
+ }
+ try FileManager.default.createDirectory(at: chromeDefault, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: chromeCache, withIntermediateDirectories: true)
+
+ let isolatedService = UninstallerService(
+ fileSystemContext: ctx
+ )
+
+ let scannedChrome = try await isolatedService.scan(appURL: chromeApp)
+ let deepChrome = try await isolatedService.deepScan(scannedChrome, mode: .balanced)
+ let browserItems = deepChrome.relatedFiles.filter { $0.isBrowserData }
+ XCTAssertFalse(browserItems.isEmpty)
+ XCTAssertTrue(browserItems.allSatisfy { !$0.isSelected && $0.deletionRisk == .normal })
+
+ let scannedDrive = try await isolatedService.scan(appURL: driveApp)
+ let deepDrive = try await isolatedService.deepScan(scannedDrive, mode: .balanced)
+ XCTAssertFalse(deepDrive.relatedFiles.contains { $0.url.path.lowercased().contains("/google/chrome") })
+ }
+
+ func testSpotlightDisabled_doesNotCrashAndFallsBackSafely() async throws {
+ let ctx = try FileSystemContext.isolatedTestRoot()
+ defer { try? FileManager.default.removeItem(at: ctx.allowedRoots[0]) }
+
+ let appURL = ctx.homeDirectory.appendingPathComponent("Applications/NoSpotlight.app", isDirectory: true)
+ let contents = appURL.appendingPathComponent("Contents", isDirectory: true)
+ try FileManager.default.createDirectory(at: contents, withIntermediateDirectories: true)
+ let plist: [String: Any] = [
+ "CFBundleIdentifier": "com.example.nospotlight",
+ "CFBundleName": "NoSpotlight",
+ "CFBundleExecutable": "NoSpotlight",
+ "CFBundleShortVersionString": "1.0",
+ ]
+ try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
+ .write(to: contents.appendingPathComponent("Info.plist"))
+
+ SpotlightMetadata.setOverrideForTesting(
+ isIndexingAvailable: { _ in false },
+ lastUsedDate: { _ in nil }
+ )
+ defer { SpotlightMetadata.resetForTesting() }
+
+ XCTAssertFalse(SpotlightMetadata.isIndexingAvailable(at: ctx.homePath))
+ let missingURL = ctx.homeDirectory.appendingPathComponent("Missing.app")
+ XCTAssertNil(SpotlightMetadata.lastUsedDate(for: missingURL))
+
+ let isolatedService = UninstallerService(
+ fileSystemContext: ctx
+ )
+ let info = try await isolatedService.scan(appURL: appURL)
+ XCTAssertEqual(info.bundleID, "com.example.nospotlight")
+ }
+
+ func testCrashSignalHandler_installsResethandSigaction() {
+ var previous = sigaction()
+ sigaction(SIGWINCH, nil, &previous)
+ defer { sigaction(SIGWINCH, &previous, nil) }
+
+ CrashSignalHandler.install(signals: [SIGWINCH], installExceptionHandler: false)
+
+ var installed = sigaction()
+ let rc = sigaction(SIGWINCH, nil, &installed)
+ XCTAssertEqual(rc, 0)
+ XCTAssertNotEqual(installed.sa_flags & SA_NODEFER, 0)
+ XCTAssertNotNil(installed.__sigaction_u.__sa_handler)
+
+ // Raising a harmless signal (default disposition: ignore) exercises the async-signal-safe
+ // handler end-to-end and verifies disposition resets to SIG_DFL.
+ Darwin.raise(SIGWINCH)
+
+ var after = sigaction()
+ XCTAssertEqual(sigaction(SIGWINCH, nil, &after), 0)
+ XCTAssertNil(after.__sigaction_u.__sa_handler)
+ }
+
+ func testAppIconCache_downsamplesCachesAndRunsOffMainThread() async throws {
+ let ctx = try FileSystemContext.isolatedTestRoot()
+ defer { try? FileManager.default.removeItem(at: ctx.allowedRoots[0]) }
+
+ let dummyFile = ctx.homeDirectory.appendingPathComponent("DummyApp.app")
+ try FileManager.default.createDirectory(at: dummyFile, withIntermediateDirectories: true)
+
+ final class Box: @unchecked Sendable {
+ let lock = NSLock()
+ var renderCount = 0
+ var ranOnMain = false
+ }
+ let box = Box()
+
+ let cache = AppIconCache(
+ countLimit: 10,
+ totalCostLimit: 4 * 1024 * 1024,
+ maxConcurrentRenders: 2,
+ iconRenderer: { _, _ in
+ box.lock.lock()
+ box.renderCount += 1
+ box.ranOnMain = box.ranOnMain || Thread.isMainThread
+ box.lock.unlock()
+
+ // Create a large 512x512 bitmap image to verify downsampling.
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
+ let bitmapInfo = CGImageAlphaInfo.premultipliedFirst.rawValue | CGImageByteOrderInfo.order32Host.rawValue
+ guard let cgCtx = CGContext(
+ data: nil,
+ width: 512,
+ height: 512,
+ bitsPerComponent: 8,
+ bytesPerRow: 512 * 4,
+ space: colorSpace,
+ bitmapInfo: bitmapInfo
+ ), let cg = cgCtx.makeImage() else {
+ return nil
+ }
+ return NSImage(cgImage: cg, size: NSSize(width: 256, height: 256))
+ }
+ )
+
+ let firstIcon = await cache.icon(forPath: dummyFile.path, pixelSize: 64)
+ let first = try XCTUnwrap(firstIcon)
+ XCTAssertFalse(box.ranOnMain, "Icon rasterization must happen off MainThread")
+ let rep = try XCTUnwrap(first.representations.first)
+ XCTAssertLessThanOrEqual(rep.pixelsWide, 64)
+ XCTAssertLessThanOrEqual(rep.pixelsHigh, 64)
+
+ let second = await cache.icon(forPath: dummyFile.path, pixelSize: 64)
+ XCTAssertNotNil(second)
+ XCTAssertEqual(box.renderCount, 1, "Second lookup must hit NSCache")
+
+ let missing = await cache.icon(forPath: ctx.homeDirectory.appendingPathComponent("Missing.app").path, pixelSize: 64)
+ XCTAssertNil(missing)
+ }
+
+ func testBoundedConcurrency_capsActiveWorkers() async throws {
+ final class Tracker: @unchecked Sendable {
+ let lock = NSLock()
+ var active = 0
+ var peak = 0
+ func enter() {
+ lock.lock()
+ active += 1
+ peak = max(peak, active)
+ lock.unlock()
+ }
+ func exit() {
+ lock.lock()
+ active -= 1
+ lock.unlock()
+ }
+ }
+ let tracker = Tracker()
+ let inputs = Array(0..<30)
+ let results = try await UninstallerService.mapWithBoundedConcurrency(
+ items: inputs,
+ maxConcurrent: 6
+ ) { value in
+ tracker.enter()
+ try await Task.sleep(for: .milliseconds(15))
+ tracker.exit()
+ return value * 2
+ }
+
+ XCTAssertEqual(results.count, 30)
+ XCTAssertLessThanOrEqual(tracker.peak, 6)
+ XCTAssertGreaterThan(tracker.peak, 1)
+ }
+
+ @MainActor
+ func testUninstallerViewModel_loadAppsIfNeededCachesAcrossTabSwitches() async throws {
+ final class Counter: @unchecked Sendable {
+ let lock = NSLock()
+ var count = 0
+ func inc() { lock.lock(); count += 1; lock.unlock() }
+ func value() -> Int { lock.lock(); defer { lock.unlock() }; return count }
+ }
+ let counter = Counter()
+ let stubApp = UninstallerService.AppInfo(
+ url: URL(fileURLWithPath: "/Applications/StubApp.app"),
+ bundleID: "com.example.stub",
+ name: "StubApp",
+ scanState: .deepScanned
+ )
+
+ let vm = UninstallerViewModel(
+ discoverAppsHandler: {
+ counter.inc()
+ return [stubApp]
+ },
+ deepScanHandler: { app, _ in
+ var copy = app
+ copy.scanState = .deepScanned
+ return copy
+ }
+ )
+
+ vm.loadAppsIfNeeded(mode: .safe)
+ try await Task.sleep(for: .milliseconds(50))
+ XCTAssertEqual(counter.value(), 1)
+ XCTAssertNotNil(vm.lastUpdatedAt)
+ XCTAssertEqual(vm.allApps.count, 1)
+
+ // Repeated calls (tab switches) must not rescan.
+ for _ in 0..<5 {
+ vm.loadAppsIfNeeded(mode: .safe)
+ }
+ try await Task.sleep(for: .milliseconds(50))
+ XCTAssertEqual(counter.value(), 1)
+
+ // Explicit refresh reloads.
+ vm.loadApps(mode: .safe)
+ try await Task.sleep(for: .milliseconds(50))
+ XCTAssertEqual(counter.value(), 2)
+ }
+
+ @MainActor
+ func testWorkspaceStore_diskAnalyzerStartsIdleAndViewModelsCache() async {
+ let store = WorkspaceStore(journal: TransactionJournal())
+ XCTAssertNil(store.diskAnalyzerViewModel.rootURL)
+ XCTAssertFalse(store.diskAnalyzerViewModel.isScanning)
+ XCTAssertNil(store.diskAnalyzerViewModel.lastUpdatedAt)
+
+ let fixedDate = Date(timeIntervalSince1970: 1_700_000_000)
+ store.processesViewModel.lastUpdatedAt = fixedDate
+ await store.processesViewModel.scanIfNeeded()
+ XCTAssertEqual(store.processesViewModel.lastUpdatedAt, fixedDate)
+
+ store.startupServicesViewModel.lastUpdatedAt = fixedDate
+ await store.startupServicesViewModel.scanIfNeeded()
+ XCTAssertEqual(store.startupServicesViewModel.lastUpdatedAt, fixedDate)
+ }
+
+ func testRequiresRestartForRemovedPaths() {
+ XCTAssertTrue(UninstallerService.requiresRestartForRemovedPaths([
+ URL(fileURLWithPath: "/Library/LaunchDaemons/com.example.helper.plist")
+ ]))
+ XCTAssertTrue(UninstallerService.requiresRestartForRemovedPaths([
+ URL(fileURLWithPath: "/Library/SystemExtensions/1234/com.example.ext.systemextension")
+ ]))
+ XCTAssertTrue(UninstallerService.requiresRestartForRemovedPaths([
+ URL(fileURLWithPath: "/Library/Extensions/ExampleDriver.kext")
+ ]))
+ XCTAssertTrue(UninstallerService.requiresRestartForRemovedPaths([
+ URL(fileURLWithPath: "/Library/PrivilegedHelperTools/com.example.tool")
+ ]))
+ XCTAssertTrue(UninstallerService.requiresRestartForRemovedPaths([
+ URL(fileURLWithPath: "/Library/Audio/Plug-Ins/HAL/ExampleAudio.driver")
+ ]))
+ XCTAssertTrue(UninstallerService.requiresRestartForRemovedPaths([
+ URL(fileURLWithPath: "/Applications/Example.app"),
+ URL(fileURLWithPath: "/tmp/Custom.kext")
+ ]))
+
+ XCTAssertFalse(UninstallerService.requiresRestartForRemovedPaths([
+ URL(fileURLWithPath: "/Applications/Example.app"),
+ URL(fileURLWithPath: "/Users/test/Library/LaunchAgents/com.example.agent.plist"),
+ URL(fileURLWithPath: "/Users/test/Library/Caches/com.example.app"),
+ URL(fileURLWithPath: "/Users/test/Library/Preferences/com.example.app.plist")
+ ]))
+ }
+
+ func testPhysicalSize_symlinkRoot_nestedSymlink_andCancellation() async throws {
+ FileManager.clearSizeCache()
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("POSIXSizeTest-\(UUID().uuidString)", isDirectory: true)
+ let realApp = root.appendingPathComponent("External/RealApp.app", isDirectory: true)
+ let contents = realApp.appendingPathComponent("Contents", isDirectory: true)
+ try FileManager.default.createDirectory(at: contents, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ // 16 KB payload file
+ let payload = contents.appendingPathComponent("payload.bin")
+ try Data(repeating: 0x5A, count: 16_384).write(to: payload)
+
+ // Nested symlink pointing back to root (cycle) — must not loop or double-count
+ let nestedLink = contents.appendingPathComponent("LoopLink")
+ try FileManager.default.createSymbolicLink(at: nestedLink, withDestinationURL: realApp)
+
+ // Symlinked root `.app` (like an app offloaded to an external SSD)
+ let symlinkedApp = root.appendingPathComponent("LinkedApp.app", isDirectory: false)
+ try FileManager.default.createSymbolicLink(at: symlinkedApp, withDestinationURL: realApp)
+
+ let directSize = FileManager.default.getPhysicalDirectorySize(url: realApp, excludedPaths: [])
+ let symlinkSize = FileManager.default.getPhysicalDirectorySize(url: symlinkedApp, excludedPaths: [])
+ XCTAssertGreaterThanOrEqual(directSize, 16_384)
+ XCTAssertEqual(directSize, symlinkSize, "Symlinked root app must report same physical size without following nested symlink cycles")
+
+ // Cancelled task must not cache a partial zero/incomplete result
+ let cancelDir = root.appendingPathComponent("CancelDir", isDirectory: true)
+ try FileManager.default.createDirectory(at: cancelDir, withIntermediateDirectories: true)
+ try Data(repeating: 0x3C, count: 8192).write(to: cancelDir.appendingPathComponent("data.bin"))
+
+ let cancelledTask = Task.detached {
+ while !Task.isCancelled {
+ await Task.yield()
+ }
+ return FileManager.default.getPhysicalDirectorySize(url: cancelDir, excludedPaths: [])
+ }
+ cancelledTask.cancel()
+ _ = await cancelledTask.value
+
+ let measured = FileManager.default.getPhysicalDirectorySize(url: cancelDir, excludedPaths: [])
+ XCTAssertGreaterThanOrEqual(measured, 8192)
+ }
+
+ func testLSRegisterCache_coalescesConcurrentDumpCalls() async {
+ let cache = LSRegisterCache()
+ async let first = cache.paths(matching: "com.apple.finder")
+ async let second = cache.paths(matching: "com.apple.finder")
+ async let third = cache.paths(matching: "com.apple.safari")
+ let (r1, r2, r3) = await (first, second, third)
+ XCTAssertEqual(r1, r2)
+ _ = r3
+ }
+
+ @MainActor
+ func testAppQuitter_isRunningUnderTests_blocksLiveAppTermination() {
+ XCTAssertTrue(AppQuitter.isRunningUnderTests)
+ XCTAssertTrue(AppQuitter.cleanupTargets().isEmpty)
+ }
}
diff --git a/MacOSCleaner/Models/DiskCategoryItem.swift b/MacOSCleaner/Models/DiskCategoryItem.swift
index c0e0b94..a033762 100644
--- a/MacOSCleaner/Models/DiskCategoryItem.swift
+++ b/MacOSCleaner/Models/DiskCategoryItem.swift
@@ -1,28 +1,33 @@
import SwiftUI
public struct DiskCategoryItem: Identifiable, Sendable, Hashable {
- public let id = UUID()
+ public let id: String
public let label: String
public let bytes: Int64
public let color: Color
public let gradientColors: [Color]
public let iconName: String
-
+ public let isScanning: Bool
+
public init(
+ id: String = UUID().uuidString,
label: String,
bytes: Int64,
color: Color,
gradientColors: [Color] = [],
- iconName: String = "circle.fill"
+ iconName: String = "circle.fill",
+ isScanning: Bool = false
) {
+ self.id = id
self.label = label
self.bytes = bytes
self.color = color
self.gradientColors = gradientColors.isEmpty ? [color.opacity(0.8), color] : gradientColors
self.iconName = iconName
+ self.isScanning = isScanning
}
-
+
public var formattedValue: String {
- return bytes.formattedByteCount()
+ bytes.formattedByteCount()
}
}
diff --git a/MacOSCleaner/Resources/ar.lproj/Localizable.strings b/MacOSCleaner/Resources/ar.lproj/Localizable.strings
index 1715e7b..1dc465b 100644
--- a/MacOSCleaner/Resources/ar.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/ar.lproj/Localizable.strings
@@ -1198,3 +1198,28 @@
"privacy_uninstaller_show_less" = "عرض أقل";
"privacy_ext_open_in_browser_help" = "يفتح صفحة هذه الإضافة في المتصفح عبر نص برمجي (قد يطلب macOS إذن الأتمتة مرة واحدة).";
"privacy_ext_automation_denied_hint" = "تم رفض إذن الأتمتة لـ %1$@. تم نسخ رابط «%2$@» — الصقه في شريط العنوان.";
+"uninstaller_browser_data_warning" = "ملفات تعريف المتصفح والإضافات وجلسات المواقع غير محددة افتراضيًا. سيؤدي حذفها إلى تسجيل الخروج من المواقع وإزالة الإضافات.";
+"uninstaller_browser_data_badge" = "بيانات المتصفح";
+"uninstaller_browser_data_confirm_warning" = "تحذير: ستؤدي إزالة بيانات ملف تعريف المتصفح المحددة إلى تسجيل خروجك من المواقع وإزالة الإضافات وبيانات تطبيقات الويب نهائيًا.";
+"uninstaller_spotlight_disabled" = "فهرسة Spotlight متوقفة. تعتمد تواريخ آخر استخدام على بيانات الوصول للملف ويقتصر البحث على المسارات الاستدلالية.";
+"scan_updated_at" = "تم التحديث %@";
+"scan_updated_just_now" = "الآن";
+"cleanup_restart_recommended_title" = "يُوصى بإعادة التشغيل";
+"cleanup_restart_recommended_body" = "قد تحتفظ خدمات macOS الخلفية بمراجع في الذاكرة للملفات المؤقتة المحذوفة. تساعد إعادة التشغيل في تحرير كتل APFS المتبقية وتحديث فهارس النظام.";
+"cleanup_restart_required_title" = "يلزم إعادة التشغيل";
+"cleanup_restart_font_cache_body" = "تم مسح ذاكرة التخزين المؤقت لخطوط النظام. أعد تشغيل Mac لتجنب أخطاء عرض النص في التطبيقات المفتوحة.";
+"uninstaller_restart_recommended_title" = "يُوصى بإعادة التشغيل";
+"uninstaller_restart_recommended_body" = "تمت إزالة مكونات النظام (الخدمات الخلفية أو الملحقات أو الإضافات). أعد تشغيل Mac لإفراغها بالكامل من الذاكرة.";
+"restart_mac_button" = "إعادة تشغيل Mac…";
+"uninstaller_orphan_scanning_dirs" = "جارٍ فحص المجلدات المستهدفة...";
+"uninstaller_orphan_analyzing_count" = "جارٍ تحليل %lld بقايا محتملة...";
+"uninstaller_orphan_analyzing_progress" = "جارٍ التحليل %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "ذاكرة التخزين المؤقت";
+"uninstaller_orphan_cat_preferences" = "التفضيلات";
+"uninstaller_orphan_cat_app_support" = "دعم التطبيقات";
+"uninstaller_orphan_cat_logs" = "السجلات";
+"uninstaller_orphan_cat_containers" = "الحاويات";
+"uninstaller_orphan_cat_developer" = "المطور";
+"uninstaller_orphan_cat_launch_agents" = "وكلاء التشغيل";
+"uninstaller_orphan_cat_other" = "أخرى";
+"uninstaller_evidence_score" = "النتيجة: %lld";
diff --git a/MacOSCleaner/Resources/de.lproj/Localizable.strings b/MacOSCleaner/Resources/de.lproj/Localizable.strings
index e626d7e..2e1b420 100644
--- a/MacOSCleaner/Resources/de.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/de.lproj/Localizable.strings
@@ -1162,3 +1162,28 @@
"privacy_uninstaller_show_less" = "Weniger anzeigen";
"privacy_ext_open_in_browser_help" = "Öffnet die Erweiterungsseite im Browser per Automations-Skript (macOS fragt ggf. einmalig nach Berechtigung).";
"privacy_ext_automation_denied_hint" = "Automationszugriff auf %1$@ wurde verweigert. Link für „%2$@“ wurde kopiert — bitte in die Adressleiste einfügen.";
+"uninstaller_browser_data_warning" = "Browserprofile, Erweiterungen und Anmeldesitzungen sind standardmäßig abgewählt. Das Löschen meldet Sie von Websites ab und entfernt Erweiterungen.";
+"uninstaller_browser_data_badge" = "Browserdaten";
+"uninstaller_browser_data_confirm_warning" = "Warnung: Ausgewählte Browserprofildaten melden Sie von Websites ab und entfernen Erweiterungen sowie lokale Web-App-Daten.";
+"uninstaller_spotlight_disabled" = "Die Spotlight-Indizierung ist deaktiviert. Zuletzt-verwendet-Daten nutzen Dateizugriffsmetadaten und die Suche verwendet nur Heuristiken.";
+"scan_updated_at" = "Aktualisiert %@";
+"scan_updated_just_now" = "gerade eben";
+"cleanup_restart_recommended_title" = "Neustart empfohlen";
+"cleanup_restart_recommended_body" = "macOS-Hintergrunddienste halten möglicherweise noch offene Verweise auf gelöschte Caches. Ein Neustart gibt APFS-Blöcke frei und aktualisiert Systemindizes.";
+"cleanup_restart_required_title" = "Neustart erforderlich";
+"cleanup_restart_font_cache_body" = "Der System-Schriftcache wurde geleert. Starten Sie Ihren Mac neu, um Darstellungsfehler in geöffneten Apps zu vermeiden.";
+"uninstaller_restart_recommended_title" = "Neustart empfohlen";
+"uninstaller_restart_recommended_body" = "Systemkomponenten (Daemons, Erweiterungen oder Plug-ins) wurden entfernt. Starten Sie Ihren Mac neu, um sie vollständig aus dem Speicher zu entladen.";
+"restart_mac_button" = "Mac neu starten…";
+"uninstaller_orphan_scanning_dirs" = "Zielverzeichnisse werden gescannt...";
+"uninstaller_orphan_analyzing_count" = "%lld mögliche Überreste werden analysiert...";
+"uninstaller_orphan_analyzing_progress" = "Analyse %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "Caches";
+"uninstaller_orphan_cat_preferences" = "Einstellungen";
+"uninstaller_orphan_cat_app_support" = "Programmunterstützung";
+"uninstaller_orphan_cat_logs" = "Protokolle";
+"uninstaller_orphan_cat_containers" = "Container";
+"uninstaller_orphan_cat_developer" = "Entwickler";
+"uninstaller_orphan_cat_launch_agents" = "Launch Agents";
+"uninstaller_orphan_cat_other" = "Andere";
+"uninstaller_evidence_score" = "Punkte: %lld";
diff --git a/MacOSCleaner/Resources/en.lproj/Localizable.strings b/MacOSCleaner/Resources/en.lproj/Localizable.strings
index b6d32b2..4e03ae1 100644
--- a/MacOSCleaner/Resources/en.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/en.lproj/Localizable.strings
@@ -1198,3 +1198,28 @@
"privacy_uninstaller_show_less" = "Show less";
"privacy_ext_open_in_browser_help" = "Opens this extension's page in the browser via Automation script (macOS may ask permission once).";
"privacy_ext_automation_denied_hint" = "Automation access to %1$@ was denied, so the script couldn't open the tab. Extension link for “%2$@” was copied — paste it into the address bar.";
+"uninstaller_browser_data_warning" = "Browser profiles, extensions, and site logins are unselected by default. Selecting them will sign you out of websites and remove installed extensions.";
+"uninstaller_browser_data_badge" = "Browser Data";
+"uninstaller_browser_data_confirm_warning" = "Warning: Selected browser profile data will sign you out of websites and permanently remove extensions and local web app data.";
+"uninstaller_spotlight_disabled" = "Spotlight indexing is turned off. Last-used dates fall back to file access metadata and search uses heuristic paths only.";
+"scan_updated_at" = "Updated %@";
+"scan_updated_just_now" = "just now";
+"cleanup_restart_recommended_title" = "Restart Recommended";
+"cleanup_restart_recommended_body" = "macOS background daemons may hold open handles to deleted caches in memory. Restarting frees remaining APFS blocks and refreshes system indexes.";
+"cleanup_restart_required_title" = "Restart Required";
+"cleanup_restart_font_cache_body" = "The system font cache was cleared. Restart your Mac so open apps rebuild font tables and avoid text rendering glitches.";
+"uninstaller_restart_recommended_title" = "Restart Recommended";
+"uninstaller_restart_recommended_body" = "System components (daemons, extensions, or plug-ins) were removed. Restart your Mac to unload them completely from memory.";
+"restart_mac_button" = "Restart Mac…";
+"uninstaller_orphan_scanning_dirs" = "Scanning target directories...";
+"uninstaller_orphan_analyzing_count" = "Analyzing %lld potential leftovers...";
+"uninstaller_orphan_analyzing_progress" = "Analyzing %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "Caches";
+"uninstaller_orphan_cat_preferences" = "Preferences";
+"uninstaller_orphan_cat_app_support" = "Application Support";
+"uninstaller_orphan_cat_logs" = "Logs";
+"uninstaller_orphan_cat_containers" = "Containers";
+"uninstaller_orphan_cat_developer" = "Developer";
+"uninstaller_orphan_cat_launch_agents" = "Launch Agents";
+"uninstaller_orphan_cat_other" = "Other";
+"uninstaller_evidence_score" = "Score: %lld";
diff --git a/MacOSCleaner/Resources/es.lproj/Localizable.strings b/MacOSCleaner/Resources/es.lproj/Localizable.strings
index 9144d26..4460688 100644
--- a/MacOSCleaner/Resources/es.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/es.lproj/Localizable.strings
@@ -1196,3 +1196,28 @@
"privacy_uninstaller_show_less" = "Mostrar menos";
"privacy_ext_open_in_browser_help" = "Abre la página de esta extensión en el navegador mediante un script (macOS puede pedir permiso de Automatización).";
"privacy_ext_automation_denied_hint" = "Se denegó el acceso de Automatización a %1$@. Se copió el enlace de «%2$@» — pégalo en la barra de direcciones.";
+"uninstaller_browser_data_warning" = "Los perfiles del navegador, extensiones y sesiones web están desmarcados por defecto. Eliminarlos cerrará tus sesiones y borrará tus extensiones.";
+"uninstaller_browser_data_badge" = "Datos del navegador";
+"uninstaller_browser_data_confirm_warning" = "Advertencia: Los datos de perfil seleccionados cerrarán tus sesiones web y eliminarán extensiones y datos de apps web.";
+"uninstaller_spotlight_disabled" = "La indexación de Spotlight está desactivada. Las fechas de último uso usan metadatos de acceso y la búsqueda solo usa heurística.";
+"scan_updated_at" = "Actualizado %@";
+"scan_updated_just_now" = "ahora mismo";
+"cleanup_restart_recommended_title" = "Reinicio recomendado";
+"cleanup_restart_recommended_body" = "Los servicios de macOS pueden mantener referencias en memoria a las cachés eliminadas. Reiniciar libera bloques APFS pendientes y actualiza los índices.";
+"cleanup_restart_required_title" = "Reinicio necesario";
+"cleanup_restart_font_cache_body" = "Se borró la caché de fuentes del sistema. Reinicia tu Mac para que las apps reconstruyan las tablas de fuentes y evitar fallos de texto.";
+"uninstaller_restart_recommended_title" = "Reinicio recomendado";
+"uninstaller_restart_recommended_body" = "Se eliminaron componentes del sistema (daemons, extensiones o complementos). Reinicia tu Mac para descargarlos por completo de la memoria.";
+"restart_mac_button" = "Reiniciar Mac…";
+"uninstaller_orphan_scanning_dirs" = "Escaneando directorios objetivo...";
+"uninstaller_orphan_analyzing_count" = "Analizando %lld posibles restos...";
+"uninstaller_orphan_analyzing_progress" = "Analizando %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "Cachés";
+"uninstaller_orphan_cat_preferences" = "Preferencias";
+"uninstaller_orphan_cat_app_support" = "Soporte de aplicaciones";
+"uninstaller_orphan_cat_logs" = "Registros";
+"uninstaller_orphan_cat_containers" = "Contenedores";
+"uninstaller_orphan_cat_developer" = "Desarrollador";
+"uninstaller_orphan_cat_launch_agents" = "Agentes de inicio";
+"uninstaller_orphan_cat_other" = "Otros";
+"uninstaller_evidence_score" = "Puntuación: %lld";
diff --git a/MacOSCleaner/Resources/fr.lproj/Localizable.strings b/MacOSCleaner/Resources/fr.lproj/Localizable.strings
index ab03e5b..7671a6b 100644
--- a/MacOSCleaner/Resources/fr.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/fr.lproj/Localizable.strings
@@ -1160,3 +1160,28 @@
"privacy_uninstaller_show_less" = "Réduire";
"privacy_ext_open_in_browser_help" = "Ouvre la page de cette extension dans le navigateur via un script (macOS peut demander l'autorisation Automatisation).";
"privacy_ext_automation_denied_hint" = "L'accès Automatisation à %1$@ a été refusé. Le lien pour « %2$@ » a été copié — collez-le dans la barre d'adresse.";
+"uninstaller_browser_data_warning" = "Les profils, extensions et sessions web sont décochés par défaut. Les supprimer vous déconnectera des sites et supprimera vos extensions.";
+"uninstaller_browser_data_badge" = "Données du navigateur";
+"uninstaller_browser_data_confirm_warning" = "Attention : les données de profil sélectionnées vous déconnecteront des sites web et supprimeront vos extensions et données d'applications web.";
+"uninstaller_spotlight_disabled" = "L'indexation Spotlight est désactivée. Les dates de dernière utilisation reposent sur l'accès fichier et la recherche utilise uniquement l'heuristique.";
+"scan_updated_at" = "Mis à jour %@";
+"scan_updated_just_now" = "à l'instant";
+"cleanup_restart_recommended_title" = "Redémarrage recommandé";
+"cleanup_restart_recommended_body" = "Les services macOS peuvent conserver des références aux caches supprimés en mémoire. Un redémarrage libère les blocs APFS et actualise les index système.";
+"cleanup_restart_required_title" = "Redémarrage requis";
+"cleanup_restart_font_cache_body" = "Le cache des polices système a été vidé. Redémarrez votre Mac pour éviter des anomalies d'affichage du texte dans les apps ouvertes.";
+"uninstaller_restart_recommended_title" = "Redémarrage recommandé";
+"uninstaller_restart_recommended_body" = "Des composants système (daemons, extensions ou modules) ont été supprimés. Redémarrez votre Mac pour les décharger complètement de la mémoire.";
+"restart_mac_button" = "Redémarrer le Mac…";
+"uninstaller_orphan_scanning_dirs" = "Analyse des dossiers cibles...";
+"uninstaller_orphan_analyzing_count" = "Analyse de %lld résidus potentiels...";
+"uninstaller_orphan_analyzing_progress" = "Analyse %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "Caches";
+"uninstaller_orphan_cat_preferences" = "Préférences";
+"uninstaller_orphan_cat_app_support" = "Support d’applications";
+"uninstaller_orphan_cat_logs" = "Journaux";
+"uninstaller_orphan_cat_containers" = "Conteneurs";
+"uninstaller_orphan_cat_developer" = "Développeur";
+"uninstaller_orphan_cat_launch_agents" = "Agents de lancement";
+"uninstaller_orphan_cat_other" = "Autre";
+"uninstaller_evidence_score" = "Score : %lld";
diff --git a/MacOSCleaner/Resources/it.lproj/Localizable.strings b/MacOSCleaner/Resources/it.lproj/Localizable.strings
index 0598e56..a13acd3 100644
--- a/MacOSCleaner/Resources/it.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/it.lproj/Localizable.strings
@@ -1161,3 +1161,28 @@
"privacy_uninstaller_show_less" = "Mostra meno";
"privacy_ext_open_in_browser_help" = "Apre la pagina di questa estensione nel browser tramite script (macOS può richiedere il permesso Automazione).";
"privacy_ext_automation_denied_hint" = "Accesso Automazione a %1$@ negato. Il link per «%2$@» è stato copiato — incollalo nella barra degli indirizzi.";
+"uninstaller_browser_data_warning" = "Profili del browser, estensioni e sessioni dei siti sono deselezionati per impostazione predefinita. Eliminarli disconnetterà dai siti e rimuoverà le estensioni.";
+"uninstaller_browser_data_badge" = "Dati del browser";
+"uninstaller_browser_data_confirm_warning" = "Attenzione: i dati del profilo selezionati disconnetteranno dai siti web e rimuoveranno estensioni e dati delle web app.";
+"uninstaller_spotlight_disabled" = "L'indicizzazione Spotlight è disattivata. Le date di ultimo utilizzo usano i metadati di accesso ai file e la ricerca usa solo l'euristica.";
+"scan_updated_at" = "Aggiornato %@";
+"scan_updated_just_now" = "proprio ora";
+"cleanup_restart_recommended_title" = "Riavvio consigliato";
+"cleanup_restart_recommended_body" = "I servizi di macOS potrebbero mantenere in memoria riferimenti alle cache eliminate. Il riavvio libera i blocchi APFS residui e aggiorna gli indici.";
+"cleanup_restart_required_title" = "Riavvio necessario";
+"cleanup_restart_font_cache_body" = "La cache dei font di sistema è stata svuotata. Riavvia il Mac per evitare problemi di rendering del testo nelle app aperte.";
+"uninstaller_restart_recommended_title" = "Riavvio consigliato";
+"uninstaller_restart_recommended_body" = "Sono stati rimossi componenti di sistema (daemon, estensioni o plug-in). Riavvia il Mac per scaricarli completamente dalla memoria.";
+"restart_mac_button" = "Riavvia il Mac…";
+"uninstaller_orphan_scanning_dirs" = "Scansione delle cartelle di destinazione...";
+"uninstaller_orphan_analyzing_count" = "Analisi di %lld possibili residui...";
+"uninstaller_orphan_analyzing_progress" = "Analisi %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "Cache";
+"uninstaller_orphan_cat_preferences" = "Preferenze";
+"uninstaller_orphan_cat_app_support" = "Supporto applicazioni";
+"uninstaller_orphan_cat_logs" = "Log";
+"uninstaller_orphan_cat_containers" = "Contenitori";
+"uninstaller_orphan_cat_developer" = "Sviluppatore";
+"uninstaller_orphan_cat_launch_agents" = "Agenti di avvio";
+"uninstaller_orphan_cat_other" = "Altro";
+"uninstaller_evidence_score" = "Punteggio: %lld";
diff --git a/MacOSCleaner/Resources/ja.lproj/Localizable.strings b/MacOSCleaner/Resources/ja.lproj/Localizable.strings
index 28858e1..4aa28f9 100644
--- a/MacOSCleaner/Resources/ja.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/ja.lproj/Localizable.strings
@@ -1161,3 +1161,28 @@
"privacy_uninstaller_show_less" = "折りたたむ";
"privacy_ext_open_in_browser_help" = "スクリプトを使ってブラウザで拡張機能ページを開きます(macOS がオートメーション許可を求める場合があります)。";
"privacy_ext_automation_denied_hint" = "%1$@ へのオートメーション許可が拒否されました。「%2$@」のURLをコピーしましたのでアドレスバーに貼り付けてください。";
+"uninstaller_browser_data_warning" = "ブラウザのプロファイル、拡張機能、ログインセッションは既定で選択解除されています。削除するとサイトからログアウトされ拡張機能が失われます。";
+"uninstaller_browser_data_badge" = "ブラウザデータ";
+"uninstaller_browser_data_confirm_warning" = "警告:選択したブラウザプロファイルデータを削除すると、ウェブサイトからログアウトされ、拡張機能やWebアプリデータが削除されます。";
+"uninstaller_spotlight_disabled" = "Spotlight のインデックス作成が無効です。最終使用日はファイルアクセス情報を使用し、検索はヒューリスティックのみで行われます。";
+"scan_updated_at" = "更新: %@";
+"scan_updated_just_now" = "たった今";
+"cleanup_restart_recommended_title" = "再起動をおすすめします";
+"cleanup_restart_recommended_body" = "macOS のバックグラウンドサービスが削除済みキャッシュをメモリ上に保持している場合があります。再起動すると残りの APFS ブロックが解放され、システムインデックスが更新されます。";
+"cleanup_restart_required_title" = "再起動が必要です";
+"cleanup_restart_font_cache_body" = "システムフォントキャッシュを消去しました。開いているアプリでの文字表示の崩れを防ぐため、Mac を再起動してください。";
+"uninstaller_restart_recommended_title" = "再起動をおすすめします";
+"uninstaller_restart_recommended_body" = "システムコンポーネント(デーモン、機能拡張、またはプラグイン)を削除しました。メモリから完全にアンロードするため、Mac を再起動してください。";
+"restart_mac_button" = "Mac を再起動…";
+"uninstaller_orphan_scanning_dirs" = "対象ディレクトリをスキャンしています...";
+"uninstaller_orphan_analyzing_count" = "%lld 件の不要ファイル候補を分析中...";
+"uninstaller_orphan_analyzing_progress" = "分析中 %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "キャッシュ";
+"uninstaller_orphan_cat_preferences" = "環境設定";
+"uninstaller_orphan_cat_app_support" = "アプリケーションサポート";
+"uninstaller_orphan_cat_logs" = "ログ";
+"uninstaller_orphan_cat_containers" = "コンテナ";
+"uninstaller_orphan_cat_developer" = "開発者";
+"uninstaller_orphan_cat_launch_agents" = "起動エージェント";
+"uninstaller_orphan_cat_other" = "その他";
+"uninstaller_evidence_score" = "スコア: %lld";
diff --git a/MacOSCleaner/Resources/ko.lproj/Localizable.strings b/MacOSCleaner/Resources/ko.lproj/Localizable.strings
index 56ffa76..642d99d 100644
--- a/MacOSCleaner/Resources/ko.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/ko.lproj/Localizable.strings
@@ -1198,3 +1198,28 @@
"privacy_uninstaller_show_less" = "접기";
"privacy_ext_open_in_browser_help" = "스크립트를 통해 브라우저에서 이 확장 프로그램 페이지를 엽니다(macOS가 자동화 권한을 요청할 수 있음).";
"privacy_ext_automation_denied_hint" = "%1$@ 자동화 권한이 거부되어 탭을 열 수 없습니다. “%2$@” 링크를 복사했으니 주소창에 붙여넣으세요.";
+"uninstaller_browser_data_warning" = "브라우저 프로필, 확장 프로그램 및 사이트 로그인 세션은 기본적으로 선택 해제되어 있습니다. 삭제하면 웹사이트에서 로그아웃되고 확장 프로그램이 제거됩니다.";
+"uninstaller_browser_data_badge" = "브라우저 데이터";
+"uninstaller_browser_data_confirm_warning" = "경고: 선택한 브라우저 프로필 데이터를 삭제하면 웹사이트에서 로그아웃되며 확장 프로그램과 웹 앱 데이터가 영구 삭제됩니다.";
+"uninstaller_spotlight_disabled" = "Spotlight 색인이 꺼져 있습니다. 마지막 사용 날짜는 파일 접근 메타데이터를 사용하며 잔여 파일 검색은 휴리스틱만 사용합니다.";
+"scan_updated_at" = "업데이트: %@";
+"scan_updated_just_now" = "방금 전";
+"cleanup_restart_recommended_title" = "재시동 권장";
+"cleanup_restart_recommended_body" = "macOS 백그라운드 서비스가 삭제된 캐시에 대한 핸들을 메모리에 유지할 수 있습니다. 재시동하면 남은 APFS 블록이 해제되고 시스템 인덱스가 새로고침됩니다.";
+"cleanup_restart_required_title" = "재시동 필요";
+"cleanup_restart_font_cache_body" = "시스템 서체 캐시를 비웠습니다. 열려 있는 앱에서 텍스트 렌더링 오류가 발생하지 않도록 Mac을 재시동하세요.";
+"uninstaller_restart_recommended_title" = "재시동 권장";
+"uninstaller_restart_recommended_body" = "시스템 구성 요소(데몬, 확장 프로그램 또는 플러그인)가 제거되었습니다. 메모리에서 완전히 언로드하려면 Mac을 재시동하세요.";
+"restart_mac_button" = "Mac 재시동…";
+"uninstaller_orphan_scanning_dirs" = "대상 디렉터리 스캔 중...";
+"uninstaller_orphan_analyzing_count" = "잠재적 잔여 파일 %lld개 분석 중...";
+"uninstaller_orphan_analyzing_progress" = "분석 중 %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "캐시";
+"uninstaller_orphan_cat_preferences" = "환경설정";
+"uninstaller_orphan_cat_app_support" = "응용 프로그램 지원";
+"uninstaller_orphan_cat_logs" = "로그";
+"uninstaller_orphan_cat_containers" = "컨테이너";
+"uninstaller_orphan_cat_developer" = "개발자";
+"uninstaller_orphan_cat_launch_agents" = "실행 에이전트";
+"uninstaller_orphan_cat_other" = "기타";
+"uninstaller_evidence_score" = "점수: %lld";
diff --git a/MacOSCleaner/Resources/pl.lproj/Localizable.strings b/MacOSCleaner/Resources/pl.lproj/Localizable.strings
index 29194bd..a6aa00e 100644
--- a/MacOSCleaner/Resources/pl.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/pl.lproj/Localizable.strings
@@ -1198,3 +1198,28 @@
"privacy_uninstaller_show_less" = "Pokaż mniej";
"privacy_ext_open_in_browser_help" = "Otwiera stronę tego rozszerzenia w przeglądarce za pomocą skryptu (macOS może jednorazowo poprosić o zgodę Automatyzacji).";
"privacy_ext_automation_denied_hint" = "Odmówiono dostępu Automatyzacji do %1$@. Link do „%2$@” został skopiowany — wklej go na pasku adresu.";
+"uninstaller_browser_data_warning" = "Profile przeglądarki, rozszerzenia i sesje logowania są domyślnie odznaczone. Ich usunięcie wyloguje Cię ze stron i usunie rozszerzenia.";
+"uninstaller_browser_data_badge" = "Dane przeglądarki";
+"uninstaller_browser_data_confirm_warning" = "Uwaga: wybrane dane profilu przeglądarki wylogują Cię ze stron internetowych i trwale usuną rozszerzenia oraz dane aplikacji webowych.";
+"uninstaller_spotlight_disabled" = "Indeksowanie Spotlight jest wyłączone. Daty ostatniego użycia korzystają z metadanych dostępu do pliku, a wyszukiwanie używa tylko heurystyki.";
+"scan_updated_at" = "Zaktualizowano %@";
+"scan_updated_just_now" = "przed chwilą";
+"cleanup_restart_recommended_title" = "Zalecane ponowne uruchomienie";
+"cleanup_restart_recommended_body" = "Usługi systemowe macOS mogą utrzymywać w pamięci odwołania do usuniętych pamięci podręcznych. Ponowne uruchomienie zwalnia bloki APFS i odświeża indeksy.";
+"cleanup_restart_required_title" = "Wymagane ponowne uruchomienie";
+"cleanup_restart_font_cache_body" = "Wyczyszczono systemową pamięć podręczną czcionek. Uruchom ponownie Maca, aby uniknąć błędów renderowania tekstu w otwartych aplikacjach.";
+"uninstaller_restart_recommended_title" = "Zalecane ponowne uruchomienie";
+"uninstaller_restart_recommended_body" = "Usunięto komponenty systemowe (demony, rozszerzenia lub wtyczki). Uruchom ponownie Maca, aby całkowicie usunąć je z pamięci.";
+"restart_mac_button" = "Uruchom ponownie Maca…";
+"uninstaller_orphan_scanning_dirs" = "Skanowanie katalogów docelowych...";
+"uninstaller_orphan_analyzing_count" = "Analizowanie %lld potencjalnych pozostałości...";
+"uninstaller_orphan_analyzing_progress" = "Analizowanie %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "Pamięć podręczna";
+"uninstaller_orphan_cat_preferences" = "Preferencje";
+"uninstaller_orphan_cat_app_support" = "Wsparcie aplikacji";
+"uninstaller_orphan_cat_logs" = "Dzienniki";
+"uninstaller_orphan_cat_containers" = "Kontenery";
+"uninstaller_orphan_cat_developer" = "Deweloper";
+"uninstaller_orphan_cat_launch_agents" = "Agenci uruchamiania";
+"uninstaller_orphan_cat_other" = "Inne";
+"uninstaller_evidence_score" = "Wynik: %lld";
diff --git a/MacOSCleaner/Resources/pt-BR.lproj/Localizable.strings b/MacOSCleaner/Resources/pt-BR.lproj/Localizable.strings
index 67a80fd..7b22c94 100644
--- a/MacOSCleaner/Resources/pt-BR.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/pt-BR.lproj/Localizable.strings
@@ -1161,3 +1161,28 @@
"privacy_uninstaller_show_less" = "Mostrar menos";
"privacy_ext_open_in_browser_help" = "Abre a página desta extensão no navegador via script (o macOS pode solicitar permissão de Automação).";
"privacy_ext_automation_denied_hint" = "O acesso de Automação ao %1$@ foi negado. O link de “%2$@” foi copiado — cole na barra de endereços.";
+"uninstaller_browser_data_warning" = "Perfis do navegador, extensões e sessões de login vêm desmarcados por padrão. Apagá-los desconectará sua conta dos sites e removerá extensões.";
+"uninstaller_browser_data_badge" = "Dados do navegador";
+"uninstaller_browser_data_confirm_warning" = "Aviso: os dados de perfil selecionados desconectarão suas contas de sites e removerão extensões e dados de web apps.";
+"uninstaller_spotlight_disabled" = "A indexação do Spotlight está desativada. As datas de último uso recorrem ao acesso de arquivos e a busca usa apenas heurística.";
+"scan_updated_at" = "Atualizado %@";
+"scan_updated_just_now" = "agora mesmo";
+"cleanup_restart_recommended_title" = "Reinicialização recomendada";
+"cleanup_restart_recommended_body" = "Serviços do macOS podem manter referências em memória aos caches apagados. Reiniciar libera os blocos APFS restantes e atualiza os índices do sistema.";
+"cleanup_restart_required_title" = "Reinicialização necessária";
+"cleanup_restart_font_cache_body" = "O cache de fontes do sistema foi limpo. Reinicie o Mac para evitar falhas de exibição de texto nos apps abertos.";
+"uninstaller_restart_recommended_title" = "Reinicialização recomendada";
+"uninstaller_restart_recommended_body" = "Componentes do sistema (daemons, extensões ou plug-ins) foram removidos. Reinicie o Mac para descarregá-los completamente da memória.";
+"restart_mac_button" = "Reiniciar Mac…";
+"uninstaller_orphan_scanning_dirs" = "Verificando diretórios de destino...";
+"uninstaller_orphan_analyzing_count" = "Analisando %lld possíveis resíduos...";
+"uninstaller_orphan_analyzing_progress" = "Analisando %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "Caches";
+"uninstaller_orphan_cat_preferences" = "Preferências";
+"uninstaller_orphan_cat_app_support" = "Suporte a aplicativos";
+"uninstaller_orphan_cat_logs" = "Registros";
+"uninstaller_orphan_cat_containers" = "Contêineres";
+"uninstaller_orphan_cat_developer" = "Desenvolvedor";
+"uninstaller_orphan_cat_launch_agents" = "Agentes de inicialização";
+"uninstaller_orphan_cat_other" = "Outros";
+"uninstaller_evidence_score" = "Pontuação: %lld";
diff --git a/MacOSCleaner/Resources/ru.lproj/Localizable.strings b/MacOSCleaner/Resources/ru.lproj/Localizable.strings
index 66d5655..2d1d290 100644
--- a/MacOSCleaner/Resources/ru.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/ru.lproj/Localizable.strings
@@ -1197,3 +1197,28 @@
"privacy_uninstaller_show_less" = "Свернуть";
"privacy_ext_open_in_browser_help" = "Открывает страницу этого расширения в браузере с помощью скрипта (macOS может запросить разрешение Automation).";
"privacy_ext_automation_denied_hint" = "Доступ к управлению %1$@ (Automation) запрещён, поэтому скрипт не смог открыть вкладку. Ссылка на «%2$@» скопирована — вставьте её в адресную строку.";
+"uninstaller_browser_data_warning" = "Профили браузера, расширения и сессии сайтов сняты с выбора по умолчанию. Их удаление приведёт к выходу из аккаунтов и потере расширений.";
+"uninstaller_browser_data_badge" = "Данные браузера";
+"uninstaller_browser_data_confirm_warning" = "Внимание: удаление отмеченного профиля браузера выведет вас из всех сайтов и удалит расширения и данные веб-приложений.";
+"uninstaller_spotlight_disabled" = "Индексация Spotlight выключена. Даты запуска определяются по метаданным доступа, поиск остатков работает только по эвристике.";
+"scan_updated_at" = "Обновлено %@";
+"scan_updated_just_now" = "только что";
+"cleanup_restart_recommended_title" = "Рекомендуется перезагрузка";
+"cleanup_restart_recommended_body" = "Системные службы macOS могут удерживать удалённые кэши в памяти. Перезагрузка полностью освободит блоки APFS и обновит индексы.";
+"cleanup_restart_required_title" = "Требуется перезагрузка";
+"cleanup_restart_font_cache_body" = "Системный кэш шрифтов очищен. Перезагрузите Mac, чтобы избежать искажений текста в открытых приложениях.";
+"uninstaller_restart_recommended_title" = "Рекомендуется перезагрузка";
+"uninstaller_restart_recommended_body" = "Удалены системные компоненты (демоны, расширения или плагины). Перезагрузите Mac для их полной выгрузки из памяти.";
+"restart_mac_button" = "Перезагрузить Mac…";
+"uninstaller_orphan_scanning_dirs" = "Сканирование целевых каталогов...";
+"uninstaller_orphan_analyzing_count" = "Анализ %lld возможных остатков...";
+"uninstaller_orphan_analyzing_progress" = "Анализ %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "Кэши";
+"uninstaller_orphan_cat_preferences" = "Настройки";
+"uninstaller_orphan_cat_app_support" = "Поддержка программ";
+"uninstaller_orphan_cat_logs" = "Журналы";
+"uninstaller_orphan_cat_containers" = "Контейнеры";
+"uninstaller_orphan_cat_developer" = "Разработчик";
+"uninstaller_orphan_cat_launch_agents" = "Агенты запуска";
+"uninstaller_orphan_cat_other" = "Другое";
+"uninstaller_evidence_score" = "Оценка: %lld";
diff --git a/MacOSCleaner/Resources/uk.lproj/Localizable.strings b/MacOSCleaner/Resources/uk.lproj/Localizable.strings
index 7d527ce..fa2c827 100644
--- a/MacOSCleaner/Resources/uk.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/uk.lproj/Localizable.strings
@@ -1194,3 +1194,28 @@
"privacy_uninstaller_show_less" = "Згорнути";
"privacy_ext_open_in_browser_help" = "Відкриває сторінку цього розширення в браузері за допомогою скрипту (macOS може запросити дозвіл Automation).";
"privacy_ext_automation_denied_hint" = "Доступ до керування %1$@ (Automation) заборонено, тому скрипт не зміг відкрити вкладку. Посилання на «%2$@» скопійовано — вставте його в адресний рядок.";
+"uninstaller_browser_data_warning" = "Профілі браузера, розширення та сесії сайтів зняті з вибору за замовчуванням. Їх видалення призведе до виходу з акаунтів і втрати розширень.";
+"uninstaller_browser_data_badge" = "Дані браузера";
+"uninstaller_browser_data_confirm_warning" = "Увага: видалення вибраних даних профілю браузера виведе вас із сайтів та видалить розширення й дані вебдодатків.";
+"uninstaller_spotlight_disabled" = "Індексація Spotlight вимкнена. Дати запуску визначаються за метаданими доступу, пошук залишків працює лише за евристикою.";
+"scan_updated_at" = "Оновлено %@";
+"scan_updated_just_now" = "щойно";
+"cleanup_restart_recommended_title" = "Рекомендується перезавантаження";
+"cleanup_restart_recommended_body" = "Системні служби macOS можуть утримувати видалені кеші в пам’яті. Перезавантаження повністю звільнить блоки APFS та оновить індекси.";
+"cleanup_restart_required_title" = "Потрібне перезавантаження";
+"cleanup_restart_font_cache_body" = "Системний кеш шрифтів очищено. Перезавантажте Mac, щоб уникнути помилок відображення тексту у відкритих програмах.";
+"uninstaller_restart_recommended_title" = "Рекомендується перезавантаження";
+"uninstaller_restart_recommended_body" = "Видалено системні компоненти (демони, розширення або плагіни). Перезавантажте Mac, щоб повністю вивантажити їх із пам’яті.";
+"restart_mac_button" = "Перезавантажити Mac…";
+"uninstaller_orphan_scanning_dirs" = "Сканування цільових каталогів...";
+"uninstaller_orphan_analyzing_count" = "Аналіз %lld можливих залишків...";
+"uninstaller_orphan_analyzing_progress" = "Аналіз %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "Кеші";
+"uninstaller_orphan_cat_preferences" = "Налаштування";
+"uninstaller_orphan_cat_app_support" = "Підтримка програм";
+"uninstaller_orphan_cat_logs" = "Журнали";
+"uninstaller_orphan_cat_containers" = "Контейнери";
+"uninstaller_orphan_cat_developer" = "Розробник";
+"uninstaller_orphan_cat_launch_agents" = "Агенти запуску";
+"uninstaller_orphan_cat_other" = "Інше";
+"uninstaller_evidence_score" = "Оцінка: %lld";
diff --git a/MacOSCleaner/Resources/zh-Hans.lproj/Localizable.strings b/MacOSCleaner/Resources/zh-Hans.lproj/Localizable.strings
index a9f2d48..9313630 100644
--- a/MacOSCleaner/Resources/zh-Hans.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/zh-Hans.lproj/Localizable.strings
@@ -1161,3 +1161,28 @@
"privacy_uninstaller_show_less" = "收起";
"privacy_ext_open_in_browser_help" = "通过脚本在浏览器中打开此扩展页面(macOS 可能会请求一次自动化权限)。";
"privacy_ext_automation_denied_hint" = "未能获取 %1$@ 的自动化控制权限。已复制“%2$@”的链接,请粘贴到地址栏。";
+"uninstaller_browser_data_warning" = "浏览器配置文件、扩展程序和网站登录会话默认不勾选。删除它们将退出网站登录并移除已安装的扩展程序。";
+"uninstaller_browser_data_badge" = "浏览器数据";
+"uninstaller_browser_data_confirm_warning" = "警告:所选浏览器配置数据将退出您的网站登录状态,并永久移除扩展程序和 Web 应用数据。";
+"uninstaller_spotlight_disabled" = "Spotlight 索引已关闭。最后使用日期将回退至文件访问元数据,残留搜索仅使用启发式路径。";
+"scan_updated_at" = "更新于 %@";
+"scan_updated_just_now" = "刚刚";
+"cleanup_restart_recommended_title" = "建议重新启动";
+"cleanup_restart_recommended_body" = "macOS 后台服务可能仍在内存中持有已删除缓存的句柄。重新启动可彻底释放剩余的 APFS 块并刷新系统索引。";
+"cleanup_restart_required_title" = "需要重新启动";
+"cleanup_restart_font_cache_body" = "系统字体缓存已清除。请重新启动 Mac,以避免已打开的应用出现文字渲染异常。";
+"uninstaller_restart_recommended_title" = "建议重新启动";
+"uninstaller_restart_recommended_body" = "已移除系统组件(守护进程、扩展或插件)。请重新启动 Mac 以将其从内存中完全卸载。";
+"restart_mac_button" = "重新启动 Mac…";
+"uninstaller_orphan_scanning_dirs" = "正在扫描目标目录...";
+"uninstaller_orphan_analyzing_count" = "正在分析 %lld 个潜在残留项...";
+"uninstaller_orphan_analyzing_progress" = "正在分析 %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "缓存";
+"uninstaller_orphan_cat_preferences" = "偏好设置";
+"uninstaller_orphan_cat_app_support" = "应用程序支持";
+"uninstaller_orphan_cat_logs" = "日志";
+"uninstaller_orphan_cat_containers" = "容器";
+"uninstaller_orphan_cat_developer" = "开发者";
+"uninstaller_orphan_cat_launch_agents" = "启动代理";
+"uninstaller_orphan_cat_other" = "其他";
+"uninstaller_evidence_score" = "评分:%lld";
diff --git a/MacOSCleaner/Resources/zh-Hant.lproj/Localizable.strings b/MacOSCleaner/Resources/zh-Hant.lproj/Localizable.strings
index f34279f..2b508eb 100644
--- a/MacOSCleaner/Resources/zh-Hant.lproj/Localizable.strings
+++ b/MacOSCleaner/Resources/zh-Hant.lproj/Localizable.strings
@@ -1161,3 +1161,28 @@
"privacy_uninstaller_show_less" = "收起";
"privacy_ext_open_in_browser_help" = "透過腳本在瀏覽器中開啟此擴充功能頁面(macOS 可能會請求一次自動化權限)。";
"privacy_ext_automation_denied_hint" = "未取得 %1$@ 的自動化控制權限。已複製「%2$@」的連結,請貼上至網址列。";
+"uninstaller_browser_data_warning" = "瀏覽器設定檔、擴充功能與網站登入工作階段預設不勾選。刪除它們將登出網站並移除已安裝的擴充功能。";
+"uninstaller_browser_data_badge" = "瀏覽器資料";
+"uninstaller_browser_data_confirm_warning" = "警告:所選瀏覽器設定檔資料將會登出您的網站帳號,並永久移除擴充功能與網頁應用資料。";
+"uninstaller_spotlight_disabled" = "Spotlight 索引已關閉。最後使用日期將改用檔案存取中繼資料,殘留搜尋僅使用啟發式路徑。";
+"scan_updated_at" = "更新於 %@";
+"scan_updated_just_now" = "剛剛";
+"cleanup_restart_recommended_title" = "建議重新啟動";
+"cleanup_restart_recommended_body" = "macOS 背景服務可能仍在記憶體中保留已刪除快取的參照。重新啟動可徹底釋放剩餘的 APFS 區塊並更新系統索引。";
+"cleanup_restart_required_title" = "需要重新啟動";
+"cleanup_restart_font_cache_body" = "系統字體快取已清除。請重新啟動 Mac,以避免已開啟的 App 出現文字顯示異常。";
+"uninstaller_restart_recommended_title" = "建議重新啟動";
+"uninstaller_restart_recommended_body" = "已移除系統元件(守護程式、延伸功能或外掛程式)。請重新啟動 Mac 以將其從記憶體完全卸載。";
+"restart_mac_button" = "重新啟動 Mac…";
+"uninstaller_orphan_scanning_dirs" = "正在掃描目標目錄...";
+"uninstaller_orphan_analyzing_count" = "正在分析 %lld 個潛在殘留項目...";
+"uninstaller_orphan_analyzing_progress" = "正在分析 %lld/%lld...";
+"uninstaller_orphan_cat_caches" = "快取";
+"uninstaller_orphan_cat_preferences" = "偏好設定";
+"uninstaller_orphan_cat_app_support" = "應用程式支援";
+"uninstaller_orphan_cat_logs" = "日誌";
+"uninstaller_orphan_cat_containers" = "容器";
+"uninstaller_orphan_cat_developer" = "開發者";
+"uninstaller_orphan_cat_launch_agents" = "啟動代理程式";
+"uninstaller_orphan_cat_other" = "其他";
+"uninstaller_evidence_score" = "評分:%lld";
diff --git a/MacOSCleaner/SharedViews/CachedFileIconView.swift b/MacOSCleaner/SharedViews/CachedFileIconView.swift
new file mode 100644
index 0000000..918ce66
--- /dev/null
+++ b/MacOSCleaner/SharedViews/CachedFileIconView.swift
@@ -0,0 +1,64 @@
+import AppKit
+import SwiftUI
+
+struct CachedFileIconView: View {
+ let path: String?
+ let size: CGFloat
+ let cornerRadius: CGFloat
+ @ViewBuilder let placeholder: () -> Placeholder
+
+ @State private var image: NSImage?
+
+ init(
+ path: String?,
+ size: CGFloat,
+ cornerRadius: CGFloat = 0,
+ @ViewBuilder placeholder: @escaping () -> Placeholder
+ ) {
+ self.path = path
+ self.size = size
+ self.cornerRadius = cornerRadius
+ self.placeholder = placeholder
+ let pixelSize = Self.targetPixelSize(for: size)
+ if let path {
+ _image = State(initialValue: AppIconCache.shared.cachedIcon(forPath: path, pixelSize: pixelSize))
+ } else {
+ _image = State(initialValue: nil)
+ }
+ }
+
+ var body: some View {
+ let pixelSize = Self.targetPixelSize(for: size)
+ Group {
+ if let image {
+ Image(nsImage: image)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .frame(width: size, height: size)
+ .clipShape(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous))
+ } else {
+ placeholder()
+ .frame(width: size, height: size)
+ }
+ }
+ .task(id: "\(path ?? "")#\(pixelSize)") {
+ guard let path else {
+ image = nil
+ return
+ }
+ if let cached = AppIconCache.shared.cachedIcon(forPath: path, pixelSize: pixelSize) {
+ image = cached
+ return
+ }
+ image = nil
+ let loaded = await AppIconCache.shared.icon(forPath: path, pixelSize: pixelSize)
+ if !Task.isCancelled {
+ image = loaded
+ }
+ }
+ }
+
+ private static func targetPixelSize(for pointSize: CGFloat) -> Int {
+ pointSize <= 36 ? 64 : 128
+ }
+}
diff --git a/MacOSCleaner/SharedViews/GlassPillPicker.swift b/MacOSCleaner/SharedViews/GlassPillPicker.swift
index 3c95e54..0cd474b 100644
--- a/MacOSCleaner/SharedViews/GlassPillPicker.swift
+++ b/MacOSCleaner/SharedViews/GlassPillPicker.swift
@@ -29,6 +29,9 @@ struct GlassPillPicker: View {
pillRow(horizontalPadding: 8)
pillRow(horizontalPadding: 6)
}
+ .padding(3)
+ // Apply glassEffect outside ViewThatFits so probing candidate widths doesn't update multiple glass surfaces per frame.
+ .glassEffect(Glass.regular, in: Capsule())
// glassEffect can retain a previous text snapshot — force rebuild on locale change.
.id(locale.identifier)
}
@@ -90,7 +93,5 @@ struct GlassPillPicker: View {
.buttonStyle(.plain)
}
}
- .padding(3)
- .glassEffect(Glass.regular, in: Capsule())
}
}
diff --git a/MacOSCleaner/SharedViews/ScanStatusPill.swift b/MacOSCleaner/SharedViews/ScanStatusPill.swift
new file mode 100644
index 0000000..957b0d8
--- /dev/null
+++ b/MacOSCleaner/SharedViews/ScanStatusPill.swift
@@ -0,0 +1,31 @@
+import SwiftUI
+
+/// Compact freshness indicator shown in workspace headers when cached scan data exists.
+struct ScanStatusPill: View {
+ let lastUpdatedAt: Date?
+
+ var body: some View {
+ if let lastUpdatedAt {
+ TimelineView(.periodic(from: .now, by: 30)) { context in
+ let relative = Self.formatRelative(from: lastUpdatedAt, to: context.date)
+ Label(String(format: "scan_updated_at".localized, relative), systemImage: "clock")
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 3)
+ .background(Capsule().fill(Color.secondary.opacity(0.10)))
+ .lineLimit(1)
+ }
+ }
+ }
+
+ private static func formatRelative(from date: Date, to now: Date) -> String {
+ if now.timeIntervalSince(date) < 10 {
+ return "scan_updated_just_now".localized
+ }
+ let formatter = RelativeDateTimeFormatter()
+ formatter.unitsStyle = .abbreviated
+ formatter.locale = LanguageManager.shared.currentLocale
+ return formatter.localizedString(for: date, relativeTo: now)
+ }
+}
diff --git a/MacOSCleaner/project.yml b/MacOSCleaner/project.yml
index bbcfd98..657f523 100644
--- a/MacOSCleaner/project.yml
+++ b/MacOSCleaner/project.yml
@@ -2,6 +2,8 @@ name: MacOSCleaner
options:
bundleIdPrefix: input
developmentLanguage: en
+attributes:
+ LastUpgradeCheck: "1600"
targets:
MacOSCleaner:
@@ -87,8 +89,8 @@ targets:
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: input.MacOSCleaner
- MARKETING_VERSION: 3.0.0
- CURRENT_PROJECT_VERSION: 3
+ MARKETING_VERSION: 3.0.1
+ CURRENT_PROJECT_VERSION: 4
ENABLE_HARDENED_RUNTIME: YES
ENABLE_DEBUG_DYLIB: NO
ENABLE_XOJIT_PREVIEWS: NO
@@ -99,7 +101,7 @@ targets:
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
GENERATE_INFOPLIST_FILE: YES
INFOPLIST_KEY_LSApplicationCategoryType: "public.app-category.utilities"
- INFOPLIST_KEY_NSAppleEventsUsageDescription: "MacOSCleaner needs to send Apple Events to close applications before cleaning their caches and to open specific extension pages in your browser."
+ INFOPLIST_KEY_NSAppleEventsUsageDescription: "MacOSCleaner needs to send Apple Events to close applications before cleaning their caches, open specific extension pages in your browser, and request a standard macOS restart when you choose to restart."
INFOPLIST_KEY_NSHumanReadableCopyright: "Copyright © 2026 AlexTkDev (ORCID 0009-0002-8907-5406). All rights reserved."
SWIFT_COMPILATION_MODE: wholemodule
DEAD_CODE_STRIPPING: YES
@@ -107,6 +109,7 @@ targets:
CLANG_ANALYZER_NONNULL: YES
GCC_WARN_ABOUT_RETURN_TYPE: YES_ERROR
COPY_PHASE_STRIP: NO
+ ARCHS: arm64
EXCLUDED_ARCHS: "x86_64"
configs:
Debug:
diff --git a/README.md b/README.md
index ed9076e..ef31a21 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@
- Requirements: macOS 26.0 or later. Apple Silicon only (Intel Macs are not supported).
+ Requirements: macOS 26.0 or later. Apple Silicon only (Intel Macs are not supported).
@@ -19,7 +19,7 @@
-
+
@@ -43,13 +43,13 @@
| Principle | Technical Implementation |
| :--- | :--- |
-| **No Telemetry** | No background daemons, analytics SDKs, or remote loggers. All scanning runs locally without network access. |
-| **Safe Deletion** | Cleanup, App Uninstaller, Disk Space Analyzer, Duplicate Finder, and Startup Services move files to macOS Trash via `trashItem(at:)` by default for recoverable deletion. Permanent removal (`removeItem(at:)`) is strictly opt-in. |
-| **Protected Paths** | Hardcoded blocklists protect SIP paths, `/System`, `/Library`, `/usr`, `~/.ssh`, user documents, credential files (`.env`, `.npmrc`, `.yarnrc`, `.pypirc`), IDE settings (`.vscode`, `.idea`, `.zed`), and Finder sidebar favorites (`FavoriteItems.sfl3` / `.sfl4`). |
-| **Non-Destructive Scanning** | Scanning never terminates running applications or modifies files. Cleanup and uninstallation enforce a 3-second soft quit timeout before forced termination. |
-| **Open Core** | Swift 6 codebase with strict concurrency, actors, and structured task groups. Core engine and heuristics are inspectable. |
-| **On-Device AI** | Checksums, hashes, and `FoundationModels` file explanations execute strictly on-device without cloud relays (no Private Cloud Compute or third-party APIs). |
-| **Native Runtime** | Built in Swift 6 and SwiftUI with Liquid Glass materials. No Electron or WebKit container overhead. |
+| **No Telemetry** | No background daemons, analytics, or remote logging. Only optional GitHub Releases update checks use the network (configurable in Settings). |
+| **Safe Deletion** | Cleanup, Uninstaller, Disk Analyzer, Duplicates, and Startup Services move files to Trash (`trashItem(at:)`) by default. Permanent deletion is opt-in. |
+| **Protected Paths** | Blocklists guard SIP paths, `/System`, `/Library`, `/usr`, `~/.ssh`, user documents, `.env` / `.npmrc` / `.yarnrc` / `.pypirc`, IDE folders (`.vscode`, `.idea`, `.zed`), and Finder favorites (`FavoriteItems.sfl3` / `.sfl4`). |
+| **Non-Destructive Scan** | Scanning never quits apps or changes files. Cleaning waits up to 3 seconds on soft quit before force-quitting. |
+| **Open Core** | Native Swift 6 with actors and structured concurrency. Core cleanup and scan rules live in readable source. |
+| **On-Device AI** | File hashes and `FoundationModels` explanations run locally on your Mac with no cloud calls. |
+| **Native UI** | Built with SwiftUI and macOS 26 Liquid Glass materials. No Electron or web wrappers. |
---
@@ -84,7 +84,7 @@
1. **Direct Download:** Grab the latest `.dmg` from [GitHub Releases](https://github.com/AlexTkDev/MacOSCleaner/releases/latest).
2. **Mount & Drag:** Open the `.dmg` and drag `MacOSCleaner.app` into `/Applications`.
-3. **If macOS says it can't verify MacOSCleaner:** On macOS 26, Gatekeeper can block the first open (“Apple could not verify “MacOSCleaner” is free of malware”, or a dialog that it cannot verify the app is free of malware) because the app is ad-hoc signed. Only do this with the DMG from the official [GitHub Releases](https://github.com/AlexTkDev/MacOSCleaner/releases/latest) page.
+3. **If macOS says it can't verify MacOSCleaner:** On macOS 26, Gatekeeper can block the first launch (“Apple could not verify “MacOSCleaner” is free of malware”) because the app is ad-hoc signed. Only do this with the DMG from the official [GitHub Releases](https://github.com/AlexTkDev/MacOSCleaner/releases/latest) page.
1. Move `MacOSCleaner.app` to `/Applications` (step 2).
2. Try to open it once. Then go to **System Settings → Privacy & Security**, scroll down, click **Open Anyway**, and confirm.
3. Or, in Terminal:
@@ -100,15 +100,46 @@
## ✨ Features
-- **Smart Cleanup:** scans 55+ categories across system caches, user logs, browser data, 305 applications, and 105 developer toolchains (Xcode, Docker, `uv`, `mise`, Rust, Go `modcache`, Python, Node, CocoaPods), aged project-local build artifacts (verified by sibling project markers), forgotten installer images (`.dmg`, `.pkg`, `.iso`, and `.zip` central-directory inspection without mounting), local AI models (Claude Code, Ollama, MLX, Hugging Face, WhisperKit), and safe Time Machine snapshot thinning (`thinlocalsnapshots`). Includes review-only categories deselected by default, guarded Font Cache reset with confirmation, APFS reclaimable space delta, adaptive debug log panel, and a dedicated History window (`⌘Y`).
-- **Forensic Uninstaller:** inspects 30 evidence types (Bundle ID, Team ID, Spotlight metadata, Launch Services) across 2,427 cataloged remnant paths. Features a 3-stage uninstallation pipeline (soft quit → `launchd` helper bootout → file trashing), automatic Dock icon cleanup (`com.apple.dock`) with multi-version protection, inline TCC privacy permission chips on app cards, word-boundary matching to prevent false positives, Intel-only app badges (`executableArchitectures`), and standalone orphaned residuals cleanup with privilege escalation fallback.
-- **Duplicate Finder:** Master-Detail split interface (`HSplitView`) with side-by-side group and file inspection. 3-stage detection pipeline (file size matching, 4 KB header checksum, full SHA-256 verification), native Quick Look previews (`Space`), high-resolution photo previews, middle-truncation path formatting, and Smart Selection actions (`Select All Duplicates`, `Deselect All`).
-- **Disk Space Analyzer:** hierarchical folder drill-down with breadcrumb navigation, honest APFS allocated block sizing (`totalFileAllocatedSizeKey`), symlink skipping and hardlink inode deduplication, Quick Look previews (`Space`), recursive category filters (Videos, Audio, Photos, Apps, Documents, Archives — excluding `.framework`/`.dSYM`/document bundles from Apps), and dataless iCloud item skip protection.
-- **Process and Service Manager:** monitors live CPU and RAM usage with termination safeguards for critical system processes (`kernel_task`, `launchd`), chunked lazy loading (`LazyVStack`), and configurable refresh/sort settings. Startup Services manager categorizes LaunchAgents, LaunchDaemons, and BTM Login Items (`sfltool dumpbtm`), verifies `SecStaticCode` signatures and notarization (`Needs Attention` filter), supports disabling/enabling user agents and background monitors (`launchctl disable`/`bootout` + process termination), and offers direct "Show in Finder" and safe service removal.
-- **Privacy Inspector:** inspects user and system TCC permissions (read-only SQLite URI `?mode=ro&immutable=1`) with verified user-permission reset via `tccutil reset`, captures on-demand active socket snapshots via `libproc` (`proc_pidfdinfo`) for current-UID processes alongside static `Info.plist` network indicators, and lists Safari, Chrome, Edge, Brave, Arc, and Firefox extensions with localized name resolution, permission risk classification, and direct extension-page navigation (via Automation script for Chromium browsers, with clipboard fallback).
-- **Native System Integrations & Apple Intelligence:** on-device `FoundationModels` structured classification (`@Generable` verdicts: safe, caution, danger) with streaming explanations, Apple Intelligence storage overview in Settings, Siri and App Intents automation (`CleanCategoryIntent`, `CleanDeveloperCachesIntent`, `EmptyTrashIntent`, `RunScheduledCleanupIntent`) with `.requiresAuthentication`, compact `48pt` Liquid Glass navigation rail (`GlassEffectContainer`, `glassEffectUnion`), full keyboard shortcuts (`⌘1`–`⌘9`, `⌘Y`, `⌘,`, `⌘C`, `⌘F`, `⌘R`, `⌘⌫`), and 14 language localizations (English, Russian, Ukrainian, German, French, Spanish, Italian, Japanese, Simplified & Traditional Chinese, Korean, Polish, Brazilian Portuguese, and Arabic with native RTL layout).
+### 🧹 Smart Cleanup
+- Scans **42 cleanup categories** across system caches, user logs, browser caches, **305** applications, and **105** developer toolchains (Xcode, Docker, `uv`, `mise`, Rust, Go `modcache`, Python, Node, CocoaPods).
+- Detects old project build folders (checked by project markers), forgotten installers (`.dmg`, `.pkg`, `.iso`, `.zip` inspected without mounting), local AI models (Claude Code, Ollama, MLX, Hugging Face, WhisperKit), and safe Time Machine snapshot thinning (`thinlocalsnapshots`).
+- Browser cleanup targets exact cache templates per bundle ID — profiles and extensions stay untouched. Review-only items are unchecked by default.
+- Shows live APFS reclaimable space delta, adaptive debug logs, History (`⌘Y`), guarded Font Cache reset with confirmation, and post-cleanup restart prompts (`loginwindow` dialog).
-Complete feature breakdowns and path specifications are documented in the [MacOSCleaner Wiki](https://github.com/AlexTkDev/MacOSCleaner/wiki).
+### 🗑️ App Uninstaller & Leftovers
+- Finds apps in `/Applications`, `~/Applications`, and writable `/Volumes/.../Applications` (including symlinked `.app` targets), even when Spotlight indexing is off.
+- Runs a fast indexed deep scan across **30** evidence signals and **2,427** known remnant paths using bounded concurrency and low memory.
+- Uses a 3-stage removal pipeline (soft quit → `launchd` bootout → Trash) with automatic Dock cleanup, inline TCC chips, Intel-only badges, and word-boundary matching to avoid false positives.
+- Standalone Leftovers scanner supports admin escalation, groups `LaunchAgents`/`LaunchDaemons` under `Launch Agents`, preserves versioned plist names (such as `python3.8.plist`), and checks active Homebrew (`homebrew.mxcl.*`, `homebrew.cask.*`), MacPorts, and Nix services so CLI tools are not flagged.
+- Shows a restart banner when removing system daemons, `.kext`/`.systemextension` bundles, privileged helpers, or hardware plug-ins.
+
+### 🗂️ Duplicate Finder & Disk Space Analyzer
+- **Duplicate Finder:** Master-Detail split view with a 3-stage check (size → 4 KB header SHA-256 → full SHA-256), Quick Look (`Space`), high-res photo previews, middle-truncated paths, and `Select All Duplicates` / `Deselect All`.
+- **Disk Space Analyzer:** On-demand folder drill-down with breadcrumbs, APFS allocated block sizing (`totalFileAllocatedSizeKey`), hardlink deduplication, Quick Look (`Space`), and category filters (Videos, Audio, Photos, Apps, Documents, Archives).
+- Both tools skip offloaded iCloud files without downloading them and only scan external volumes you pick.
+
+### ⚙️ Processes, Startup Services & Privacy
+- **Processes & Startup Services:** Live CPU/RAM monitor (safeguarding `kernel_task` and `launchd`) plus Startup Services grouping LaunchAgents, LaunchDaemons, and Login Items (`sfltool dumpbtm`) with code-signature checks (`Needs Attention` filter), disable/bootout, and removal.
+- **Privacy Inspector:** Read-only TCC permission audit (`tccutil reset` for user grants), on-demand active socket snapshot for current-UID processes, and read-only browser extension audit with risk ratings across Safari, Chrome, Edge, Brave, Arc, and Firefox.
+- **Live Dashboard:** Progressive disk-usage rings animate category progress and live byte counts while scanning.
+
+### Native macOS & Apple Intelligence
+- On-device `FoundationModels` classifies items as safe, caution, or danger with streaming explanations and an Apple Intelligence storage overview in Settings.
+- Siri and Shortcuts automation via **5 App Intents**, with authentication required for destructive actions.
+- Native Swift 6 / SwiftUI Liquid Glass interface with a `48pt` navigation rail, keyboard shortcuts (`⌘1`–`⌘9`, `⌘Y`, `⌘,`, `⌘F`), and **14 languages** (including RTL Arabic).
+
+
+Technical details
+
+- **Uninstaller & Sizing:** single-pass `ResidualScanIndex` (`URLResourceValues` bulk snapshot), in-process `SecStaticCode` signature verification, iterative POSIX directory sizing (`fstatat` with `SF_DATALESS` and inode cycle guards).
+- **System & Privacy APIs:** read-only SQLite URI (`?mode=ro&immutable=1`) for `TCC.db`, `libproc` (`proc_pidfdinfo`) socket snapshots, Chromium extension tab navigation via Apple Events (with clipboard fallback).
+- **App Intents:** `GetStorageStatusIntent` (read-only), plus `.requiresAuthentication`-guarded `CleanCategoryIntent`, `CleanDeveloperCachesIntent`, `EmptyTrashIntent`, and `RunScheduledCleanupIntent`.
+- **UI Containers:** `GlassEffectContainer`, `HSplitView`, `LazyVStack`.
+- **Localizations (14):** English, Russian, Ukrainian, German, French, Spanish, Italian, Japanese, Simplified & Traditional Chinese, Korean, Polish, Brazilian Portuguese, Arabic.
+
+
+
+Complete feature breakdowns live in the [MacOSCleaner Wiki](https://github.com/AlexTkDev/MacOSCleaner/wiki).
---
@@ -137,11 +168,13 @@ codesign -dv --verbose=4 /Applications/MacOSCleaner.app
## ⚠️ Known Limitations
-- **Not an Antivirus:** Startup Services checks inspect code signatures, binary presence, and launch paths — they do not use malware signatures and cannot guarantee software is safe.
-- **TCC Permissions:** Without Full Disk Access, user `TCC.db` shows "no data"; system `TCC.db` is protected by SIP and read-only. Resetting a permission via `tccutil reset` clears the decision so the app prompts again on next use (it does not permanently block future prompts).
-- **Network Snapshot (`EPERM`):** Non-root inspection via `proc_pidfdinfo` only sees sockets of processes owned by the current user (`UID`). System/root daemons are explicitly marked as restricted (`EPERM`).
-- **Browser Extensions:** Read-only inspection only. Clicking an extension opens the corresponding browser's management page (Chromium browsers use an Automation script to open the specific extension tab and fall back to copying the URL if Automation permission is denied) so you can disable or remove it using the browser's built-in controls.
-- **On-Demand Only:** No background daemon, continuous network monitor, or packet capture runs in the background.
+- **Not an antivirus:** Startup checks inspect signatures, binaries, and launch paths — not malware databases.
+- **TCC access:** User `TCC.db` reads require Full Disk Access; system `TCC.db` is SIP-protected. `tccutil reset` resets prior decisions rather than blocking future prompts.
+- **Spotlight disabled:** App listing still works when `mdutil -a -i off` is set; `mdfind` lookups are skipped and Spotlight fields are thinner.
+- **External volumes:** Auto-cleanup never targets `/Volumes` roots. Time Machine backups and OS folders (`.Spotlight-V100`, `.Trashes`) stay blocked, and read-only/ejected volume errors are reported directly.
+- **Socket audit (`EPERM`):** Non-root `proc_pidfdinfo` reads only sockets owned by the current user; root daemons show `EPERM`.
+- **Browser extensions:** Inspection is read-only; clicking opens the browser's management page (or copies its URL if Automation is denied).
+- **On-demand only:** Nothing runs in the background between launches.
---