From 460099593f1f5411765dea27d2987f6043cd618c Mon Sep 17 00:00:00 2001 From: Karim Masmoudi <125830216+Kernel-Hunter@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:39:42 +0100 Subject: [PATCH] Fix Large Files edge cases found in review Music and TV library folders are never listed or trashed. Each folder gets a share of the scan budget so one huge tree cannot starve the rest, and the notice names any folder that ran out. Emptying a truncated list rescans. A personal folder that links outside home is refused. The report heading says what it leaves out. The snapshot tool restores the preferences it borrows. --- Sources/BoostKit/LargeFileEngine.swift | 6 +++ Sources/BoostKit/LargeFileScan.swift | 41 ++++++++++++++--- Sources/BoostKit/LargeFileView.swift | 4 +- Sources/BoostKit/MemoryReport.swift | 2 +- Sources/BoostKit/Snapshot.swift | 12 +++++ Tests/BoostKitTests/LargeFileScanTests.swift | 48 ++++++++++++++++++++ Tests/BoostKitTests/MemoryReportTests.swift | 2 +- 7 files changed, 106 insertions(+), 9 deletions(-) diff --git a/Sources/BoostKit/LargeFileEngine.swift b/Sources/BoostKit/LargeFileEngine.swift index 4baf344..0c53c84 100644 --- a/Sources/BoostKit/LargeFileEngine.swift +++ b/Sources/BoostKit/LargeFileEngine.swift @@ -27,6 +27,7 @@ public final class LargeFileEngine: ObservableObject { @Published public var selection: Set = [] @Published public private(set) var lastScan: Date? @Published public private(set) var capped = false + @Published public private(set) var cappedFolders: [String] = [] @Published public private(set) var matches = 0 @Published public private(set) var skippedRecent = 0 @Published public var report: String? @@ -85,6 +86,7 @@ public final class LargeFileEngine: ObservableObject { self.items = result.items self.capped = result.capped + self.cappedFolders = result.cappedFolders self.matches = result.matches self.skippedRecent = result.skippedRecent // Nothing is ticked for you. These are your own files; opting in @@ -140,6 +142,10 @@ public final class LargeFileEngine: ObservableObject { self.selection.subtract(gone) self.matches = max(self.items.count, self.matches - r.moved) self.trashing = false + // The list held only the largest files. When it is now empty but + // more matched, the next ones are still there: look again instead + // of saying there is nothing. + if self.items.isEmpty && self.matches > 0 { self.scan() } } } diff --git a/Sources/BoostKit/LargeFileScan.swift b/Sources/BoostKit/LargeFileScan.swift index 578e97e..f5fbf11 100644 --- a/Sources/BoostKit/LargeFileScan.swift +++ b/Sources/BoostKit/LargeFileScan.swift @@ -50,6 +50,9 @@ public struct LargeFileScanResult: Sendable { /// True when the walk hit its entry cap before finishing. The list is then /// incomplete and the UI must say so. public var capped = false + /// The folders whose share of the walk ran out, so the notice can name + /// exactly what was not fully read. + public var cappedFolders: [String] = [] public var visited = 0 /// Over the size threshold but changed in the last minute, so probably /// still being written. @@ -117,6 +120,16 @@ public enum LargeFileScan { bundleExtensions.contains((name as NSString).pathExtension.lowercased()) } + /// Where Music and TV keep their media when the library is a plain folder + /// rather than a package. Removing a track from here leaves the app + /// showing it as missing, so these are never listed. + static let appLibraryFolders: Set = ["Media.localized", "iTunes Media"] + + /// A folder the scan treats as one opaque item. + static func isOpaqueFolder(_ name: String) -> Bool { + isBundleName(name) || appLibraryFolders.contains(name) + } + private static var fm: FileManager { .default } // MARK: - Roots @@ -151,9 +164,14 @@ public enum LargeFileScan { /// external disk is not scanned. public static func isAcceptableRoot(_ url: URL, home: URL? = nil) -> Bool { guard ProjectScan.isAcceptableRoot(url, home: home) else { return false } - let parts = ProjectScan.canonical(url).pathComponents + let canonical = ProjectScan.canonical(url) + let parts = canonical.pathComponents if parts.count > 1, parts[1] == "Volumes" { return false } - return true + // A personal folder that is really a link somewhere else, such as + // another user's folder or /private/tmp, is not scanned. It has to + // resolve to somewhere inside your home folder. + let h = ProjectScan.canonical(home ?? fm.homeDirectoryForCurrentUser) + return ProjectScan.isInside(canonical, of: h) } private static func isAcceptableHome(_ url: URL) -> Bool { @@ -200,8 +218,14 @@ public enum LargeFileScan { roots.deep.map { (ProjectScan.canonical($0), false) } + roots.shallow.map { (ProjectScan.canonical($0), true) } - walk: for (root, shallow) in walks { + for (index, walkRoot) in walks.enumerated() { + let (root, shallow) = walkRoot if isCancelled() { result.cancelled = true; return result } + // Each folder gets an equal share of what is left, and a folder + // that uses less hands the rest on. One huge Documents tree cannot + // starve Movies, Music and Pictures. + let budget = max(1, (maxEntries - visited) / (walks.count - index)) + var rootVisited = 0 guard let e = fm.enumerator( at: root, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles, .skipsPackageDescendants] @@ -209,8 +233,13 @@ public enum LargeFileScan { for case let url as URL in e { visited += 1 + rootVisited += 1 if visited % 256 == 0, isCancelled() { result.cancelled = true; return result } - if visited > maxEntries { result.capped = true; break walk } + if rootVisited > budget { + result.capped = true + result.cappedFolders.append(root.lastPathComponent) + break + } guard let v = try? url.resourceValues(forKeys: keySet) else { continue } if v.isSymbolicLink == true { e.skipDescendants(); continue } @@ -223,7 +252,7 @@ public enum LargeFileScan { if v.isDirectory == true { // A bundle is one opaque item, and a shallow root never // goes below its top level. - if shallow || v.isPackage == true || isBundleName(name) { e.skipDescendants() } + if shallow || v.isPackage == true || isOpaqueFolder(name) { e.skipDescendants() } continue } guard v.isRegularFile == true else { continue } @@ -342,7 +371,7 @@ public enum LargeFileScan { } let below = Array(resolved.pathComponents.dropFirst(root.pathComponents.count)) if below.contains(where: { $0.hasPrefix(".") }) { return .refused("hidden") } - if below.dropLast().contains(where: isBundleName) { return .refused("inside a bundle") } + if below.dropLast().contains(where: isOpaqueFolder) { return .refused("inside a bundle or media library") } guard let modified = v.contentModificationDate else { return .refused("no date") } if now.timeIntervalSince(modified) < recentWindow { return .tooRecent } diff --git a/Sources/BoostKit/LargeFileView.swift b/Sources/BoostKit/LargeFileView.swift index 560048a..444f584 100644 --- a/Sources/BoostKit/LargeFileView.swift +++ b/Sources/BoostKit/LargeFileView.swift @@ -149,7 +149,9 @@ struct LargeFileView: View { @ViewBuilder private var notices: some View { if engine.capped { - notice("Stopped early because these folders hold a very large number of items. " + let named = engine.cappedFolders.isEmpty ? "these folders" + : engine.cappedFolders.joined(separator: ", ") + notice("Stopped early in \(named) because they hold a very large number of items. " + "The list may be incomplete.") } if engine.matches > engine.items.count { diff --git a/Sources/BoostKit/MemoryReport.swift b/Sources/BoostKit/MemoryReport.swift index 6bc0cdd..fdce32f 100644 --- a/Sources/BoostKit/MemoryReport.swift +++ b/Sources/BoostKit/MemoryReport.swift @@ -34,7 +34,7 @@ enum MemoryReport { if !apps.isEmpty { lines.append("") - lines.append("Biggest apps") + lines.append("Biggest apps (system and command line processes left out)") for app in apps { lines.append(" \(app.name) \(fmtBytes(app.bytes))") } } diff --git a/Sources/BoostKit/Snapshot.swift b/Sources/BoostKit/Snapshot.swift index 9714ddf..66b5d7d 100644 --- a/Sources/BoostKit/Snapshot.swift +++ b/Sources/BoostKit/Snapshot.swift @@ -20,6 +20,17 @@ public enum Snapshot { try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) _ = NSApplication.shared NSApp.setActivationPolicy(.accessory) + // The render borrows a few settings. They are put back before exit so + // running it on your own Mac does not change your preferences. + let borrowed = ["firstRunDismissed", "projectCutoffDays", "historyRange", "selectedTab"] + let original = borrowed.map { ($0, UserDefaults.standard.object(forKey: $0)) } + func restoreSettings() { + for (key, value) in original { + if let value { UserDefaults.standard.set(value, forKey: key) } + else { UserDefaults.standard.removeObject(forKey: key) } + } + UserDefaults.standard.synchronize() + } // Screenshots show the app as it looks once the welcome card is gone. UserDefaults.standard.set(true, forKey: "firstRunDismissed") UserDefaults.standard.set(30, forKey: "projectCutoffDays") @@ -47,6 +58,7 @@ public enum Snapshot { settle: tab == .memory ? 3.0 : 12.0, to: directory) } } + restoreSettings() exit(0) } diff --git a/Tests/BoostKitTests/LargeFileScanTests.swift b/Tests/BoostKitTests/LargeFileScanTests.swift index df58b84..2394bef 100644 --- a/Tests/BoostKitTests/LargeFileScanTests.swift +++ b/Tests/BoostKitTests/LargeFileScanTests.swift @@ -545,3 +545,51 @@ struct LargeFileRootTests { #expect(!LargeFileScan.isAcceptableRoot(home, home: home)) } } + +@Suite("Large files: review fixes") +struct LargeFileReviewFixTests { + + @Test("Music and TV library folders are never listed", arguments: ["Media.localized", "iTunes Media"]) + func appLibrariesSkipped(folder: String) throws { + let root = try makeRoot(); defer { try? fm.removeItem(at: root) } + try makeFile(root.appending(path: "Music/\(folder)/Album/track.m4a")) + let loose = try makeFile(root.appending(path: "Music/loose-recording.wav")) + + #expect(paths(scan(root)) == [loose.path]) + } + + @Test("A file inside a media library is refused at trash time too", arguments: ["Media.localized", "iTunes Media"]) + func appLibraryRefusedAtVerify(folder: String) throws { + let root = try makeRoot(); defer { try? fm.removeItem(at: root) } + let track = try makeFile(root.appending(path: "Music/\(folder)/track.m4a")) + let item = LargeFileItem(url: track, bytes: 300 * 1024, lastAccessed: nil, + lastModified: try fm.attributesOfItem(atPath: track.path)[.modificationDate] as? Date) + let verdict = LargeFileScan.verify(item, roots: LargeFileRoots(deep: [root])) + #expect(verdict != .ok) + } + + @Test("One huge folder cannot use up the whole budget") + func budgetIsShared() throws { + let first = try makeRoot(); defer { try? fm.removeItem(at: first) } + let second = try makeRoot(); defer { try? fm.removeItem(at: second) } + for i in 0..<60 { try makeFile(first.appending(path: "f\(i).bin"), kbSize: 1) } + let late = try makeFile(second.appending(path: "late.mov")) + + let r = LargeFileScan.scan(roots: LargeFileRoots(deep: [first, second]), minBytes: threshold, + maxEntries: 40) + #expect(paths(r) == [late.path]) + #expect(r.capped) + #expect(r.cappedFolders == [first.lastPathComponent]) + } + + @Test("A personal folder that links outside home is not accepted") + func linkOutsideHomeRefused() throws { + let home = try makeRoot(); defer { try? fm.removeItem(at: home) } + let elsewhere = try makeRoot(); defer { try? fm.removeItem(at: elsewhere) } + try fm.createDirectory(at: home.appending(path: "Documents"), withIntermediateDirectories: true) + try fm.createSymbolicLink(at: home.appending(path: "Downloads"), withDestinationURL: elsewhere) + + #expect(LargeFileScan.isAcceptableRoot(home.appending(path: "Documents"), home: home)) + #expect(!LargeFileScan.isAcceptableRoot(home.appending(path: "Downloads"), home: home)) + } +} diff --git a/Tests/BoostKitTests/MemoryReportTests.swift b/Tests/BoostKitTests/MemoryReportTests.swift index f2f39c7..bf53355 100644 --- a/Tests/BoostKitTests/MemoryReportTests.swift +++ b/Tests/BoostKitTests/MemoryReportTests.swift @@ -39,7 +39,7 @@ struct MemoryReportTests { MemoryReport.App(name: "Claude", bytes: 4 * gb)] let text = MemoryReport.text(version: "1.3.0", machine: machine, mem: mem(), apps: apps, pausedCount: 2, history: nil, now: now) - #expect(text.contains("Biggest apps\n Safari 700 MB\n Claude 4.00 GB")) + #expect(text.contains("Biggest apps (system and command line processes left out)\n Safari 700 MB\n Claude 4.00 GB")) #expect(text.contains("Paused apps: 2")) #expect(!text.contains("/Users")) #expect(!text.contains(NSUserName()))