Free, open-source macOS cleaner. CleanMyMac alternative with zero telemetry. Native SwiftUI, scheduled auto-cleaning, Xcode/Homebrew/system cache cleanup. MIT licensed.
Swift cache-cleanercleanmymaccleanupdisk-cleanerdisk-spacehomebrewmac-utilitymacosmacos-appmacos-cleanermacosxnativeossosxprivacyswiftswiftuisystem-cleanerxcode-cleaner
fix: register PureMac with TCC so Full Disk Access works (#75)
livitfb563c5f9002
diff --git a/PureMac/Info.plist b/PureMac/Info.plistindex 37c8bfe..e9c7374 100644--- a/PureMac/Info.plist+++ b/PureMac/Info.plist@@ -24,5 +24,17 @@<string>public.app-category.utilities</string><key>NSHumanReadableCopyright</key><string>Copyright 2026. MIT License.</string>+ <key>NSDesktopFolderUsageDescription</key>+ <string>PureMac needs access to your Desktop to find junk and orphaned files.</string>+ <key>NSDocumentsFolderUsageDescription</key>+ <string>PureMac needs access to your Documents to find junk and orphaned files.</string>+ <key>NSDownloadsFolderUsageDescription</key>+ <string>PureMac needs access to your Downloads to find junk and orphaned files.</string>+ <key>NSRemovableVolumesUsageDescription</key>+ <string>PureMac needs access to removable volumes to scan for junk files.</string>+ <key>NSSystemAdministrationUsageDescription</key>+ <string>PureMac needs system administration access to clean caches and uninstall apps completely.</string>+ <key>NSAppleEventsUsageDescription</key>+ <string>PureMac uses Apple Events to interact with Finder when revealing files.</string></dict></plist>diff --git a/PureMac/PureMacApp.swift b/PureMac/PureMacApp.swiftindex fde9bff..a175ed8 100644--- a/PureMac/PureMacApp.swift+++ b/PureMac/PureMacApp.swift@@ -6,6 +6,9 @@ class AppDelegate: NSObject, NSApplicationDelegate {func applicationDidFinishLaunching(_ notification: Notification) {NSWindow.allowsAutomaticWindowTabbing = false+ // Touch TCC-protected paths so macOS registers PureMac in the+ // Full Disk Access pane on first launch (fixes issue #75).+ FullDiskAccessManager.shared.triggerRegistration()}}@@ -13,6 +16,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {struct PureMacApp: App {@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate@StateObject private var appState = AppState()+ @StateObject private var theme = ThemeManager.shared@AppStorage("PureMac.OnboardingComplete") private var onboardingComplete = falseinit() {@@ -27,13 +31,17 @@ struct PureMacApp: App {var body: some Scene {WindowGroup {- if onboardingComplete {- MainWindow()- .environmentObject(appState)- .frame(minWidth: 900, minHeight: 600)- } else {- OnboardingView(isComplete: $onboardingComplete)+ Group {+ if onboardingComplete {+ MainWindow()+ .environmentObject(appState)+ .frame(minWidth: 900, minHeight: 600)+ } else {+ OnboardingView(isComplete: $onboardingComplete)+ }}+ .environmentObject(theme)+ .preferredColorScheme(theme.appearance.colorScheme)}.windowStyle(.automatic).windowToolbarStyle(.unified)diff --git a/PureMac/Services/CleaningEngine.swift b/PureMac/Services/CleaningEngine.swiftindex c50a450..8ce28eb 100644--- a/PureMac/Services/CleaningEngine.swift+++ b/PureMac/Services/CleaningEngine.swift@@ -7,6 +7,11 @@ actor CleaningEngine {var freedSpace: Int64 = 0var itemsCleaned: Int = 0var errors: [String] = []+ var cleanedPaths: Set<String> = []+ // Items that user-level FileManager.removeItem refused with EACCES /+ // EPERM. These are root-owned and need an admin-privileged second+ // pass via cleanWithAdminPrivileges(items:).+ var requiresAdmin: [CleanableItem] = []}// MARK: - Public API@@ -67,8 +72,25 @@ actor CleaningEngine {try fileManager.removeItem(at: resolvedURL)result.freedSpace += item.sizeresult.itemsCleaned += 1+ result.cleanedPaths.insert(item.path)} catch {- result.errors.append("\(item.name): \(error.localizedDescription)")+ let nsError = error as NSError+ let isPermissionDenied =+ (nsError.domain == NSCocoaErrorDomain &&+ (nsError.code == NSFileWriteNoPermissionError ||+ nsError.code == NSFileReadNoPermissionError)) ||+ (nsError.domain == NSPOSIXErrorDomain &&+ (nsError.code == Int(EACCES) || nsError.code == Int(EPERM)))+ if isPermissionDenied {+ // Defer to the admin pass — these are typically root-owned+ // system caches that the user-level process can't unlink.+ result.requiresAdmin.append(item)+ Logger.shared.log("Deferring to admin pass: \(item.path)", level: .info)+ } else {+ let detail = "\(item.name) at \(item.path): \(error.localizedDescription)"+ result.errors.append(detail)+ Logger.shared.log("Clean failed: \(detail)", level: .error)+ }}}@@ -80,6 +102,99 @@ actor CleaningEngine {return await cleanItems(selectedItems, progressHandler: progressHandler)}+ /// Re-runs the deletion of the supplied items as root via NSAppleScript's+ /// "with administrator privileges" clause. Triggers exactly one auth+ /// prompt for the whole batch (macOS caches the credential for ~5 min).+ ///+ /// Every path is re-validated against the same allow-list as the user-+ /// level pass (isSafeToDelete / isExplicitSingleFileDeletable) before it+ /// gets handed off to /bin/rm. Paths are passed via a NUL-separated+ /// temp file consumed by xargs -0, so no shell-quoting pitfalls.+ func cleanWithAdminPrivileges(items: [CleanableItem]) async -> CleaningResult {+ var result = CleaningResult()++ Logger.shared.log("Admin pass starting with \(items.count) item(s)", level: .info)++ // Re-validate. Don't trust the caller — anything not on the allow-list+ // refuses to escalate.+ let validated: [(item: CleanableItem, resolved: String)] = items.compactMap { item in+ let resolved = URL(fileURLWithPath: item.path).resolvingSymlinksInPath().path+ let accepted: Bool = {+ if item.category == .largeFiles {+ return isExplicitSingleFileDeletable(resolvedPath: resolved)+ }+ return isSafeToDelete(resolvedPath: resolved)+ }()+ if !accepted {+ Logger.shared.log("Refusing admin escalation for unsafe path: \(item.path)", level: .warning)+ }+ return accepted ? (item, resolved) : nil+ }+ guard !validated.isEmpty else {+ Logger.shared.log("Admin pass: no items survived validation", level: .warning)+ return result+ }++ // Stage paths NUL-separated so newlines/spaces in paths don't matter.+ let staged = validated.map(\.resolved).joined(separator: "\u{0}")+ guard let payload = staged.data(using: .utf8) else { return result }++ let tempFile = FileManager.default.temporaryDirectory+ .appendingPathComponent("puremac-rm-\(UUID().uuidString)")+ do {+ try payload.write(to: tempFile, options: [.atomic])+ } catch {+ Logger.shared.log("Couldn't stage admin path list: \(error.localizedDescription)", level: .error)+ return result+ }+ defer { try? FileManager.default.removeItem(at: tempFile) }++ // UUIDs are alphanumeric + hyphens, NSTemporaryDirectory is a known+ // path with no shell metacharacters, so direct embedding is safe.+ let script = """+ do shell script "/usr/bin/xargs -0 /bin/rm -rf -- < \(tempFile.path)" with administrator privileges+ """++ let runResult: (success: Bool, error: String?) = await withCheckedContinuation { continuation in+ DispatchQueue.global(qos: .userInitiated).async {+ let appleScript = NSAppleScript(source: script)+ var errorInfo: NSDictionary?+ appleScript?.executeAndReturnError(&errorInfo)+ if let errorInfo {+ continuation.resume(returning: (false, "\(errorInfo)"))+ } else {+ continuation.resume(returning: (true, nil))+ }+ }+ }++ guard runResult.success else {+ // -128 is "user cancelled" — log quietly, no need for an error row.+ if let err = runResult.error, !err.contains("-128") {+ Logger.shared.log("Admin clean failed: \(err)", level: .error)+ result.errors.append("Administrator authorization failed")+ }+ return result+ }++ // Verify which items actually disappeared. xargs may have reported a+ // partial failure even when the AppleScript exited cleanly, so we+ // re-stat every path rather than trust the script's exit status.+ for (item, resolved) in validated {+ if !FileManager.default.fileExists(atPath: resolved) {+ result.cleanedPaths.insert(item.path)+ result.itemsCleaned += 1+ result.freedSpace += item.size+ } else {+ let detail = "\(item.name) at \(item.path) survived admin removal"+ result.errors.append(detail)+ Logger.shared.log("Admin pass survivor: \(detail)", level: .error)+ }+ }+ Logger.shared.log("Admin pass complete: \(result.itemsCleaned) deleted, \(result.errors.count) survived", level: .info)+ return result+ }+// MARK: - Purgeable Spacefunc purgePurgeableSpace() async -> Int64 {@@ -150,17 +265,31 @@ actor CleaningEngine {"\(home)/Library/Preferences","\(home)/Library/LaunchAgents","\(home)/Library/Mail Downloads",+ "\(home)/Library/Developer/Xcode/DerivedData",+ "\(home)/Library/Developer/Xcode/Archives",+ "\(home)/Library/Developer/CoreSimulator/Caches","\(home)/.Trash",+ "\(home)/.npm",+ "\(home)/.cache",+ "\(home)/Library/Containers/com.docker.docker","/Library/Caches","/Library/Logs","/private/var/log","/private/var/tmp",+ // /var is a symlink to /private/var, and resolvingSymlinksInPath+ // gives the /var form. Both spellings must be allow-listed or+ // every system log/tmp deletion silently fails the safety check.+ "/var/log",+ "/var/tmp","/tmp",]- // Allow whole-subtree deletion only; require a trailing "/" on the- // root match so siblings like "/tmpfoo" cannot pass the prefix check.+ // Either the path equals an allow-listed root (whole-subtree wipe by+ // the scanner that emits the root itself, e.g. DerivedData) or it+ // sits strictly inside one. The trailing "/" on the prefix match+ // prevents siblings like "/tmpfoo" from sneaking past "/tmp".let normalized = (resolvedPath as NSString).standardizingPathreturn allowedRoots.contains { root in+ if normalized == root { return true }let rootWithSeparator = root.hasSuffix("/") ? root : root + "/"return normalized.hasPrefix(rootWithSeparator)}diff --git a/PureMac/Services/FullDiskAccessManager.swift b/PureMac/Services/FullDiskAccessManager.swiftindex 82f4ac4..f9b1107 100644--- a/PureMac/Services/FullDiskAccessManager.swift+++ b/PureMac/Services/FullDiskAccessManager.swift@@ -2,62 +2,72 @@ import AppKitimport Foundation/// Detects whether Full Disk Access (FDA) has been granted to PureMac.-/// Without FDA, macOS TCC blocks access to ~/Desktop, ~/Documents, ~/Mail,-/// ~/.Trash, and other app containers even for non-sandboxed apps.+/// Without FDA, macOS TCC blocks access to ~/Library/Mail, ~/Library/Safari,+/// /Library/Application Support/com.apple.TCC, and other protected locations.final class FullDiskAccessManager {static let shared = FullDiskAccessManager()private init() {}- /// Check if Full Disk Access is granted by probing TCC-protected paths.- /// Returns true if at least one protected path is readable.+ /// Check if Full Disk Access is granted by attempting a real read of a+ /// TCC-protected file. We use FileHandle/Data — not isReadableFile or+ /// fileExists — because the metadata APIs short-circuit before TCC fires+ /// and so don't register the calling app in the FDA list.var hasFullDiskAccess: Bool {- // These paths are protected by TCC and require FDA to read.- // We try multiple because some may not exist on every system.- let protectedPaths = [+ let probes = [+ "/Library/Application Support/com.apple.TCC/TCC.db",FileManager.default.homeDirectoryForCurrentUser- .appendingPathComponent("Library/Mail").path,+ .appendingPathComponent("Library/Safari/CloudTabs.db").path,FileManager.default.homeDirectoryForCurrentUser- .appendingPathComponent("Library/Safari/Bookmarks.plist").path,- "/Library/Application Support/com.apple.TCC/TCC.db",+ .appendingPathComponent("Library/Mail").path,]- for path in protectedPaths {- if FileManager.default.isReadableFile(atPath: path) {- return true- }- }-- // If none of the protected paths exist, assume FDA is not granted- // but don't block the user - some paths may legitimately not exist- // on a fresh system. Check if we can at least list a protected directory.- let home = FileManager.default.homeDirectoryForCurrentUser.path- let trashPath = "\(home)/.Trash"- if let contents = try? FileManager.default.contentsOfDirectory(atPath: trashPath),- !contents.isEmpty {- return true+ for path in probes {+ if canActuallyRead(path: path) { return true }}+ return false+ }- // Try listing Desktop - if TCC blocks it, we get an empty array or error- let desktopPath = "\(home)/Desktop"- do {- let contents = try FileManager.default.contentsOfDirectory(atPath: desktopPath)- // If Desktop exists and has files, FDA is likely granted- // (An empty Desktop is ambiguous, so we check more paths)- if !contents.isEmpty { return true }- } catch {- // Permission denied = no FDA+ /// Real-read probe. Performs the syscall TCC actually evaluates, so+ /// the OS records PureMac as the requester and adds it to the FDA pane.+ /// Directories use contentsOfDirectory; files use FileHandle.+ @discardableResult+ private func canActuallyRead(path: String) -> Bool {+ var isDir: ObjCBool = false+ guard FileManager.default.fileExists(atPath: path, isDirectory: &isDir) else {return false}-- // Ambiguous - Desktop is empty, try one more path- let mailDir = "\(home)/Library/Mail"- if FileManager.default.fileExists(atPath: mailDir) {- return FileManager.default.isReadableFile(atPath: mailDir)+ if isDir.boolValue {+ do {+ _ = try FileManager.default.contentsOfDirectory(atPath: path)+ return true+ } catch {+ return false+ }+ } else {+ guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else {+ return false+ }+ defer { try? handle.close() }+ return (try? handle.read(upToCount: 1)) != nil}+ }- // Can't determine definitively - default to warning the user- return false+ /// Force PureMac to appear in the Full Disk Access list.+ ///+ /// The OS only registers an app in the FDA pane after that app itself+ /// makes a TCC-gated syscall. Metadata lookups (fileExists, isReadableFile)+ /// don't qualify, and delegating to Finder via AppleScript registers+ /// *Finder* — not PureMac. So at launch we touch a few protected paths+ /// directly. The reads will fail until the user grants access; that's+ /// fine — the failed attempts are what register us.+ func triggerRegistration() {+ DispatchQueue.global(qos: .utility).async {+ _ = self.canActuallyRead(path: "/Library/Application Support/com.apple.TCC/TCC.db")+ let home = FileManager.default.homeDirectoryForCurrentUser.path+ _ = self.canActuallyRead(path: "\(home)/Library/Mail")+ _ = self.canActuallyRead(path: "\(home)/Library/Safari/CloudTabs.db")+ }}/// Opens System Settings to the Full Disk Access pane.@@ -65,4 +75,31 @@ final class FullDiskAccessManager {let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles")!NSWorkspace.shared.open(url)}++ /// Reveal the running PureMac.app bundle in Finder so the user can drag+ /// it into the Full Disk Access list when the OS hasn't auto-registered+ /// it (common with Homebrew installs that strip the quarantine attribute).+ func revealAppInFinder() {+ let bundleURL = Bundle.main.bundleURL+ NSWorkspace.shared.activateFileViewerSelecting([bundleURL])+ }++ /// Reset PureMac's TCC entries so the OS can re-register the bundle.+ /// Useful when the bundle was replaced (Homebrew upgrade, manual move)+ /// and the existing TCC row points at a stale code-signing identity.+ /// Returns true if the reset command exited cleanly.+ @discardableResult+ func resetFullDiskAccess() -> Bool {+ let bundleID = Bundle.main.bundleIdentifier ?? "com.puremac.app"+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/usr/bin/tccutil")+ process.arguments = ["reset", "SystemPolicyAllFiles", bundleID]+ do {+ try process.run()+ process.waitUntilExit()+ return process.terminationStatus == 0+ } catch {+ return false+ }+ }}diff --git a/PureMac/Services/ScanEngine.swift b/PureMac/Services/ScanEngine.swiftindex 1537594..c7279a6 100644--- a/PureMac/Services/ScanEngine.swift+++ b/PureMac/Services/ScanEngine.swift@@ -248,11 +248,11 @@ actor ScanEngine {options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { continue }- var depth = 0+ // No entry cap. A 5k cap was here previously and meant any user+ // with hundreds of thousands of small files (e.g. node_modules+ // checkouts) would never see anything past entry 5k — the+ // scattered 100+ MB files were always past that bound.for case let fileURL as URL in enumerator {- depth += 1- if depth > 5000 { break } // Safety limit-guard let resourceValues = try? fileURL.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey, .isRegularFileKey]),let isFile = resourceValues.isRegularFile, isFile,let fileSize = resourceValues.fileSizediff --git a/PureMac/ViewModels/AppState.swift b/PureMac/ViewModels/AppState.swiftindex a53e90e..8fdc233 100644--- a/PureMac/ViewModels/AppState.swift+++ b/PureMac/ViewModels/AppState.swift@@ -31,6 +31,7 @@ final class AppState: ObservableObject {@Published var deselectedItems: Set<UUID> = []@Published var hasFullDiskAccess: Bool = true@Published var fdaBannerDismissed: Bool = false+ @Published var cleanError: String?// MARK: - App Uninstaller State@@ -123,9 +124,9 @@ final class AppState: ObservableObject {func removeSelectedFiles() {// Safety guard: never allow a high-risk home dotpath (listed in- // Conditions.swift) to be sent to trashViaFinder no matter how it- // ended up in the selection. Catches selection-time additions that- // slipped past the scanner-side filters.+ // Conditions.swift) to be trashed no matter how it ended up in the+ // selection. Catches selection-time additions that slipped past the+ // scanner-side filters.let allURLs = Array(selectedFiles)let (urls, blocked): ([URL], [URL]) = allURLs.reduce(into: ([], [])) { acc, url inlet resolved = url.resolvingSymlinksInPath().path@@ -150,47 +151,42 @@ final class AppState: ObservableObject {}return}- trashViaFinder(urls: urls) { [weak self] success in+ trashDirectly(urls: urls) { [weak self] removed, failed inDispatchQueue.main.async {guard let self else { return }- // Check which files were actually removed from disk- let removed = urls.filter { !FileManager.default.fileExists(atPath: $0.path) }if !removed.isEmpty {self.discoveredFiles.removeAll { removed.contains($0) }self.selectedFiles.subtract(removed)Logger.shared.log("Removed \(removed.count) files", level: .info)}- let failed = urls.count - removed.count- if failed > 0 {- self.removalError = "\(failed) file\(failed == 1 ? "" : "s") could not be removed. Grant Full Disk Access in System Settings → Privacy & Security to allow PureMac to manage all files."- Logger.shared.log("Failed to remove \(failed) files — likely missing FDA", level: .error)+ if !failed.isEmpty {+ self.removalError = "\(failed.count) file\(failed.count == 1 ? "" : "s") could not be removed. Grant Full Disk Access in System Settings → Privacy & Security to allow PureMac to manage all files."+ Logger.shared.log("Failed to remove \(failed.count) files — likely missing FDA", level: .error)}}}}- /// Uses Finder via AppleScript to move files to Trash.- /// This triggers the standard macOS authorization prompt for protected files.- private func trashViaFinder(urls: [URL], completion: @escaping (Bool) -> Void) {- let posixPaths = urls.map { "\"\($0.path)\"" }.joined(separator: ", ")- let script = """- tell application "Finder"- set theFiles to {}- repeat with p in {\(posixPaths)}- set end of theFiles to (POSIX file p as alias)- end repeat- delete theFiles- end tell- """+ /// Move files to the Trash via FileManager.trashItem so the syscall+ /// originates from PureMac itself — TCC then registers PureMac in the+ /// Full Disk Access list. The previous AppleScript-via-Finder bridge+ /// caused the syscall to originate from Finder, which is why granting+ /// FDA to PureMac made no difference (issue #75).+ private func trashDirectly(urls: [URL], completion: @escaping ([URL], [URL]) -> Void) {DispatchQueue.global(qos: .userInitiated).async {- let appleScript = NSAppleScript(source: script)- var errorInfo: NSDictionary?- appleScript?.executeAndReturnError(&errorInfo)- let success = errorInfo == nil- if let errorInfo {- Logger.shared.log("Finder trash error: \(errorInfo)", level: .error)+ var removed: [URL] = []+ var failed: [URL] = []+ for url in urls {+ var resulting: NSURL?+ do {+ try FileManager.default.trashItem(at: url, resultingItemURL: &resulting)+ removed.append(url)+ } catch {+ Logger.shared.log("Trash failed for \(url.path): \(error.localizedDescription)", level: .error)+ failed.append(url)+ }}- completion(success)+ completion(removed, failed)}}@@ -426,19 +422,49 @@ final class AppState: ObservableObject {cleanProgress = 0Task {- let result = await cleaningEngine.cleanItems(itemsToClean) { [weak self] progress in+ var result = await cleaningEngine.cleanItems(itemsToClean) { [weak self] progress inTask { @MainActor [weak self] inself?.cleanProgress = progressself?.scanState = .cleaning(progress: progress)}}+ // Escalate root-owned items via "with administrator privileges".+ // One auth prompt covers the entire batch.+ if !result.requiresAdmin.isEmpty {+ let admin = await cleaningEngine.cleanWithAdminPrivileges(items: result.requiresAdmin)+ result.cleanedPaths.formUnion(admin.cleanedPaths)+ result.itemsCleaned += admin.itemsCleaned+ result.freedSpace += admin.freedSpace+ result.errors.append(contentsOf: admin.errors)+ }+totalFreedSpace = result.freedSpacelastCleanedDate = Date()- categoryResults = [:]- totalJunkSize = 0- clearSelectionState()+ for (cat, catResult) in categoryResults {+ let remaining = catResult.items.filter { !result.cleanedPaths.contains($0.path) }+ let cleared = catResult.items.filter { result.cleanedPaths.contains($0.path) }+ for item in cleared {+ selectedCleanupItems.remove(item.id)+ deselectedItems.remove(item.id)+ }+ if remaining.isEmpty {+ categoryResults.removeValue(forKey: cat)+ } else {+ categoryResults[cat] = CategoryResult(+ category: cat,+ items: remaining,+ totalSize: remaining.reduce(0) { $0 + $1.size }+ )+ }+ }+ totalJunkSize = categoryResults.values.reduce(0) { $0 + $1.totalSize }++ if !result.errors.isEmpty {+ cleanError = "\(result.errors.count) item\(result.errors.count == 1 ? "" : "s") couldn't be removed. Check the log for details."+ }+scanState = .cleanedloadDiskInfo()@@ -458,19 +484,47 @@ final class AppState: ObservableObject {cleanProgress = 0Task {- let cleanResult = await cleaningEngine.cleanItems(selectedItems) { [weak self] progress in+ var cleanResult = await cleaningEngine.cleanItems(selectedItems) { [weak self] progress inTask { @MainActor [weak self] inself?.cleanProgress = progressself?.scanState = .cleaning(progress: progress)}}+ if !cleanResult.requiresAdmin.isEmpty {+ let admin = await cleaningEngine.cleanWithAdminPrivileges(items: cleanResult.requiresAdmin)+ cleanResult.cleanedPaths.formUnion(admin.cleanedPaths)+ cleanResult.itemsCleaned += admin.itemsCleaned+ cleanResult.freedSpace += admin.freedSpace+ cleanResult.errors.append(contentsOf: admin.errors)+ }+totalFreedSpace = cleanResult.freedSpacelastCleanedDate = Date()- clearSelectionState(for: category)- categoryResults.removeValue(forKey: category)+ if let existing = categoryResults[category] {+ let remaining = existing.items.filter { !cleanResult.cleanedPaths.contains($0.path) }+ let cleared = existing.items.filter { cleanResult.cleanedPaths.contains($0.path) }+ for item in cleared {+ selectedCleanupItems.remove(item.id)+ deselectedItems.remove(item.id)+ }+ if remaining.isEmpty {+ categoryResults.removeValue(forKey: category)+ } else {+ categoryResults[category] = CategoryResult(+ category: category,+ items: remaining,+ totalSize: remaining.reduce(0) { $0 + $1.size }+ )+ }+ }totalJunkSize = categoryResults.values.reduce(0) { $0 + $1.totalSize }++ if !cleanResult.errors.isEmpty {+ cleanError = "\(cleanResult.errors.count) item\(cleanResult.errors.count == 1 ? "" : "s") couldn't be removed. Check the log for details."+ }+scanState = .cleanedloadDiskInfo()diff --git a/PureMac/Views/Apps/AppFilesView.swift b/PureMac/Views/Apps/AppFilesView.swiftindex b0baf9f..9fbaeb8 100644--- a/PureMac/Views/Apps/AppFilesView.swift+++ b/PureMac/Views/Apps/AppFilesView.swift@@ -121,6 +121,17 @@ struct AppFilesView: View {}private func fileSize(_ url: URL) -> Int64? {+ // totalFileAllocatedSize recurses into directories; attributesOfItem+ // returns the directory's own metadata size (≈0), which is why+ // bundles and support folders previously displayed as 0 B.+ if let values = try? url.resourceValues(forKeys: [.totalFileAllocatedSizeKey]),+ let size = values.totalFileAllocatedSize, size > 0 {+ return Int64(size)+ }+ if let values = try? url.resourceValues(forKeys: [.fileAllocatedSizeKey]),+ let size = values.fileAllocatedSize {+ return Int64(size)+ }guard let attrs = try? FileManager.default.attributesOfItem(atPath: url.path),let size = attrs[.size] as? Int64 else { return nil }return sizediff --git a/PureMac/Views/OnboardingView.swift b/PureMac/Views/OnboardingView.swiftindex 897c38a..68ef48f 100644--- a/PureMac/Views/OnboardingView.swift+++ b/PureMac/Views/OnboardingView.swift@@ -5,11 +5,13 @@ struct OnboardingView: View {@State private var currentPage = 0@State private var hasFullDiskAccess = false@State private var appeared = false+ @State private var hasOpenedSettings = false+ @State private var showDiagnostics = false// Per-path access checks@State private var accessResults: [ProtectedPath] = ProtectedPath.allPaths- private let timer = Timer.publish(every: 1.5, on: .main, in: .common).autoconnect()+ private let timer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()var body: some View {VStack(spacing: 0) {@@ -158,84 +160,180 @@ struct OnboardingView: View {// MARK: - Full Disk Accessprivate var fdaPage: some View {- VStack(spacing: 16) {- Spacer()-+ VStack(spacing: 14) {Image(systemName: hasFullDiskAccess ? "checkmark.shield.fill" : "lock.shield")- .font(.system(size: 44))+ .font(.system(size: 40)).foregroundStyle(hasFullDiskAccess ? .green : .orange).animation(.easeInOut(duration: 0.3), value: hasFullDiskAccess)+ .padding(.top, 8)Text("Full Disk Access").font(.title2.bold())if hasFullDiskAccess {- Text("All permissions granted. You're all set!")- .foregroundStyle(.green)- .transition(.opacity.combined(with: .scale))+ grantedView+ } else if hasOpenedSettings {+ instructionsView} else {- Text("PureMac needs Full Disk Access to scan protected locations.")- .foregroundStyle(.secondary)- .multilineTextAlignment(.center)- .frame(maxWidth: 400)+ introView+ }++ Spacer(minLength: 0)+ }+ .padding(.horizontal)+ .padding(.bottom, 8)+ .onAppear {+ FullDiskAccessManager.shared.triggerRegistration()+ refreshAccessChecks()+ }+ .onChange(of: hasFullDiskAccess) { granted in+ if granted, currentPage == 1 {+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {+ withAnimation(.spring(response: 0.4, dampingFraction: 0.85)) {+ currentPage = 2+ }+ }}+ }+ .transition(.asymmetric(+ insertion: .move(edge: .trailing).combined(with: .opacity),+ removal: .move(edge: .leading).combined(with: .opacity)+ ))+ }- // Permission checklist- VStack(alignment: .leading, spacing: 6) {- ForEach(Array(accessResults.enumerated()), id: \.element.id) { index, path in- HStack(spacing: 10) {- Image(systemName: path.accessible ? "checkmark.circle.fill" : "xmark.circle.fill")- .foregroundStyle(path.accessible ? .green : .red.opacity(0.7))- .font(.system(size: 14))+ private var introView: some View {+ VStack(spacing: 12) {+ Text("PureMac needs Full Disk Access to uninstall apps, find leftover files, and clean protected caches.")+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ .frame(maxWidth: 420)- Image(systemName: path.icon)- .foregroundStyle(.secondary)- .frame(width: 16)+ Button {+ openSettingsAndAdvance()+ } label: {+ Label("Open System Settings", systemImage: "gear")+ .frame(minWidth: 200)+ }+ .buttonStyle(.borderedProminent)+ .controlSize(.large)+ .keyboardShortcut(.defaultAction)+ .padding(.top, 4)- Text(path.label)- .font(.callout)+ Text("We'll guide you through the next steps.")+ .font(.caption)+ .foregroundStyle(.tertiary)+ }+ }- Spacer()+ private var instructionsView: some View {+ VStack(spacing: 10) {+ Text("In System Settings, do this:")+ .font(.callout)+ .foregroundStyle(.secondary)- Text(path.accessible ? "Accessible" : "Blocked")- .font(.caption)- .foregroundStyle(path.accessible ? .green : .orange)- }- .padding(.vertical, 4)- .padding(.horizontal, 12)- .background(- RoundedRectangle(cornerRadius: 6)- .fill(path.accessible ? Color.green.opacity(0.06) : Color.orange.opacity(0.06))- )- .opacity(appeared ? 1 : 0)- .offset(x: appeared ? 0 : -20)- .animation(.easeOut(duration: 0.4).delay(Double(index) * 0.05), value: appeared)- }+ VStack(alignment: .leading, spacing: 8) {+ stepRow(number: 1, text: "Privacy & Security → Full Disk Access")+ stepRow(number: 2, text: "Find **PureMac** and turn the toggle on")+ stepRow(number: 3, text: "Authenticate with Touch ID or your password")}- .frame(maxWidth: 400)- .padding(.vertical, 4)+ .frame(maxWidth: 420, alignment: .leading)- if !hasFullDiskAccess {+ HStack(spacing: 8) {Button {FullDiskAccessManager.shared.openFullDiskAccessSettings()} label: {- Label("Open System Settings", systemImage: "gear")+ Label("Reopen Settings", systemImage: "gear")+ }++ Menu {+ Button("PureMac isn't in the list — reveal it") {+ FullDiskAccessManager.shared.revealAppInFinder()+ }+ Button("Reset permissions and re-prompt") {+ _ = FullDiskAccessManager.shared.resetFullDiskAccess()+ FullDiskAccessManager.shared.triggerRegistration()+ refreshAccessChecks()+ }+ Divider()+ Button(showDiagnostics ? "Hide diagnostics" : "Show diagnostics") {+ showDiagnostics.toggle()+ }+ } label: {+ Label("Trouble?", systemImage: "questionmark.circle")}- .buttonStyle(.borderedProminent)- .padding(.top, 4)+ .menuStyle(.borderlessButton)+ .fixedSize()+ }+ .padding(.top, 4)- Text("Enable PureMac in Privacy & Security → Full Disk Access")+ HStack(spacing: 6) {+ ProgressView().controlSize(.small)+ Text("Waiting for permission…").font(.caption).foregroundStyle(.secondary)}+ .padding(.top, 2)++ if showDiagnostics {+ diagnosticsList+ }+ }+ }+ private var grantedView: some View {+ VStack(spacing: 8) {+ Text("Permission granted.")+ .foregroundStyle(.green)+ .font(.callout.weight(.semibold))+ Text("PureMac can now manage protected files.")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ .transition(.opacity.combined(with: .scale))+ }++ private func stepRow(number: Int, text: String) -> some View {+ HStack(alignment: .firstTextBaseline, spacing: 10) {+ Text("\(number)")+ .font(.callout.bold())+ .foregroundStyle(.white)+ .frame(width: 22, height: 22)+ .background(Circle().fill(Color.accentColor))+ Text(.init(text))+ .font(.callout)Spacer()}- .padding()- .transition(.asymmetric(- insertion: .move(edge: .trailing).combined(with: .opacity),- removal: .move(edge: .leading).combined(with: .opacity)- ))+ }++ private var diagnosticsList: some View {+ VStack(alignment: .leading, spacing: 4) {+ ForEach(accessResults) { path in+ HStack(spacing: 8) {+ Image(systemName: path.accessible ? "checkmark.circle.fill" : "xmark.circle")+ .foregroundStyle(path.accessible ? .green : .red.opacity(0.7))+ .font(.system(size: 11))+ Image(systemName: path.icon)+ .foregroundStyle(.secondary)+ .frame(width: 14)+ Text(path.label)+ .font(.caption)+ Spacer()+ Text(path.accessible ? "OK" : "Blocked")+ .font(.caption2)+ .foregroundStyle(path.accessible ? .green : .orange)+ }+ }+ }+ .frame(maxWidth: 360)+ .padding(8)+ .background(RoundedRectangle(cornerRadius: 6).fill(Color.secondary.opacity(0.08)))+ }++ private func openSettingsAndAdvance() {+ FullDiskAccessManager.shared.openFullDiskAccessSettings()+ withAnimation(.easeInOut(duration: 0.25)) {+ hasOpenedSettings = true+ }}// MARK: - Readydiff --git a/PureMac/Views/Orphans/OrphanListView.swift b/PureMac/Views/Orphans/OrphanListView.swiftindex cc47617..6305b26 100644--- a/PureMac/Views/Orphans/OrphanListView.swift+++ b/PureMac/Views/Orphans/OrphanListView.swift@@ -106,6 +106,14 @@ struct OrphanListView: View {}private func fileSize(_ url: URL) -> Int64? {+ if let values = try? url.resourceValues(forKeys: [.totalFileAllocatedSizeKey]),+ let size = values.totalFileAllocatedSize, size > 0 {+ return Int64(size)+ }+ if let values = try? url.resourceValues(forKeys: [.fileAllocatedSizeKey]),+ let size = values.fileAllocatedSize {+ return Int64(size)+ }guard let attrs = try? FileManager.default.attributesOfItem(atPath: url.path),let size = attrs[.size] as? Int64 else { return nil }return size