diff --git a/MacCleaner/CLI.swift b/MacCleaner/CLI.swift index 50bb9bc..baafc01 100644 --- a/MacCleaner/CLI.swift +++ b/MacCleaner/CLI.swift @@ -100,7 +100,12 @@ enum CLI { // MARK: Run - static func run(_ argv: [String]) -> Int32 { + /// The subcommand as `run` sees it: the first argument once `--json`, `--yes` and `-y` are set aside. + static func subcommand(_ argv: [String]) -> String? { + argv.first { !["--json", "--yes", "-y"].contains($0) } + } + + @MainActor static func run(_ argv: [String]) -> Int32 { var args = argv let json = args.contains("--json"); args.removeAll { $0 == "--json" } let yes = args.contains("--yes") || args.contains("-y"); args.removeAll { $0 == "--yes" || $0 == "-y" } @@ -108,7 +113,7 @@ enum CLI { switch name { case "mcp": MCPServer.run(); return 0 - case "bench": return MainActor.assumeIsolated { Bench.run(Array(args.dropFirst())) } + case "bench": return Bench.run(Array(args.dropFirst())) case "install": switch CLIInstaller.install() { case .success(let u): @@ -180,7 +185,7 @@ enum CLI { } /// A confirm reaching here came with --yes (`tool` refuses confirm without it): a non-interactive override. - private static func call(_ tool: String, _ a: [String: Any], json: Bool) -> Int32 { + @MainActor private static func call(_ tool: String, _ a: [String: Any], json: Bool) -> Int32 { let approval: ToolApproval? = (a["confirm"] as? Bool) == true ? .yesFlag : nil do { return output(try MCPServer.call(tool, a, approval: approval), json: json) } catch { err("\(error)"); return 1 } } diff --git a/MacCleaner/MCPApproval.swift b/MacCleaner/MCPApproval.swift index 5aba945..7f4c4c6 100644 --- a/MacCleaner/MCPApproval.swift +++ b/MacCleaner/MCPApproval.swift @@ -23,7 +23,7 @@ struct ApprovalRequest: Sendable { /// itself. So before any MCP tool changes anything, Mac Cleaner asks the person in its own window. enum HumanApproval { /// How Mac Cleaner asks. Replaced only by the self-test. - nonisolated(unsafe) static var ask: (ApprovalRequest) -> Bool = askWithDialog + @MainActor static var ask: @MainActor (ApprovalRequest) -> Bool = askWithDialog /// The dialog cancels itself after this long, so an unattended request never goes ahead. /// MACCLEANER_APPROVAL_TIMEOUT can only shorten it (1–120 s), for testing the cancel path. static var timeout: TimeInterval { diff --git a/MacCleaner/MCPServer.swift b/MacCleaner/MCPServer.swift index cc05e99..6602516 100644 --- a/MacCleaner/MCPServer.swift +++ b/MacCleaner/MCPServer.swift @@ -1,17 +1,18 @@ import AppKit import Foundation import MacCleanerCore +import os /// Model Context Protocol server over stdio. Start with: "Mac Cleaner" --mcp /// Every tool that deletes or moves something returns a preview unless called with confirm: true. enum MCPServer { struct ToolError: Error, CustomStringConvertible { let description: String } - private static var cacheScan: [CleanTarget] = [] - private static var appCache: [AppInfo] = [] - private static var projectScan: [DevProject] = [] - private static var sdkScan = SDKScan() - private static var sysReport = SysReport() + @MainActor private static var cacheScan: [CleanTarget] = [] + @MainActor private static var appCache: [AppInfo] = [] + @MainActor private static var projectScan: [DevProject] = [] + @MainActor private static var sdkScan = SDKScan() + @MainActor private static var sysReport = SysReport() static let instructions = """ Mac Cleaner frees disk space on this Mac. Rules for using it: @@ -33,7 +34,7 @@ enum MCPServer { // MARK: - Loop - static func run() { + @MainActor static func run() { while let line = readLine() { guard !line.isEmpty, let data = line.data(using: .utf8), let msg = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { continue } @@ -41,6 +42,20 @@ enum MCPServer { } } + /// Measures every scan location in parallel, one slot per location (nonisolated: no main-actor state involved). + /// The array is pre-sized (all nil) before any iteration starts. Each iteration measures outside the lock, then + /// writes only its own index under the lock. `concurrentPerform` is synchronous and returns only after every + /// iteration finished, so the final read sees all writes (the lock also gives happens-before). Same result as + /// the old unsafe-buffer version: slot i holds `Scanner.measure(plan[i])`. + private nonisolated static func measureAll(_ plan: [CleanTarget]) -> [CleanTarget?] { + let slots = OSAllocatedUnfairLock<[CleanTarget?]>(initialState: Array(repeating: nil, count: plan.count)) + DispatchQueue.concurrentPerform(iterations: plan.count) { i in + let m = Scanner.measure(plan[i]) + slots.withLock { $0[i] = m } + } + return slots.withLock { $0 } + } + private static func send(_ obj: [String: Any]) { guard let d = try? JSONSerialization.data(withJSONObject: obj, options: [.withoutEscapingSlashes]) else { return } FileHandle.standardOutput.write(d + Data("\n".utf8)) @@ -50,7 +65,7 @@ enum MCPServer { send(["jsonrpc": "2.0", "id": id, "result": result]) } - private static func handle(_ msg: [String: Any]) { + @MainActor private static func handle(_ msg: [String: Any]) { guard let id = msg["id"] else { return } // notifications need no answer let method = msg["method"] as? String ?? "" let params = msg["params"] as? [String: Any] ?? [:] @@ -207,7 +222,7 @@ enum MCPServer { /// `approval` is set only by the CLI: `.terminal` when a person typed "yes" at its prompt, `.yesFlag` for the /// `--yes` override (no prompt, not a person's confirmation). Calls from the MCP connection pass nil, so every /// confirm from an AI client also needs the person's yes in Mac Cleaner's own window. - static func call(_ name: String, _ a: [String: Any], approval: ToolApproval? = nil) throws -> Any { + @MainActor static func call(_ name: String, _ a: [String: Any], approval: ToolApproval? = nil) throws -> Any { let confirm = a["confirm"] as? Bool ?? false switch name { case "disk_status": @@ -218,10 +233,7 @@ enum MCPServer { case "scan_caches": let minBytes = Int64((a["min_size_mb"] as? Double ?? 1) * 1_000_000) let plan = Scanner.plan() - var measured = [CleanTarget?](repeating: nil, count: plan.count) - measured.withUnsafeMutableBufferPointer { buf in - DispatchQueue.concurrentPerform(iterations: plan.count) { i in buf[i] = Scanner.measure(plan[i]) } - } + let measured = Self.measureAll(plan) cacheScan = Scanner.finalize(measured.compactMap { $0 }) let shown = cacheScan.filter { $0.sizeBytes >= minBytes }.sorted { $0.sizeBytes > $1.sizeBytes } return [ @@ -648,13 +660,13 @@ enum MCPServer { /// A confirm only runs a plan the user was shown: each preview gets a single-use id, valid for /// 10 minutes, tied to the tool and to a digest of the exact items. The confirm recomputes the /// digest from the same arguments, so a different app, path or selection is refused. - private static var previews: [String: (tool: String, digest: String, expires: Date, request: ApprovalRequest, + @MainActor private static var previews: [String: (tool: String, digest: String, expires: Date, request: ApprovalRequest, cleanupPlan: CleanupPlan?)] = [:] static let previewLifetime: TimeInterval = 600 static func plan(_ parts: [String]) -> String { parts.sorted().joined(separator: "\n") } - static func issuePreview(_ tool: String, _ digest: String, now: Date = Date(), request: ApprovalRequest? = nil, + @MainActor static func issuePreview(_ tool: String, _ digest: String, now: Date = Date(), request: ApprovalRequest? = nil, cleanupPlan: CleanupPlan? = nil) -> String { previews = previews.filter { $0.value.expires > now } let id = UUID().uuidString.lowercased() @@ -683,7 +695,7 @@ enum MCPServer { /// "yes", or the --yes override), Mac Cleaner asks the person in its own window, showing the preview's list. The preview is used up /// either way, so a refused confirm can't be retried without a new preview. @discardableResult - static func approve(_ tool: String, _ digest: String, _ a: [String: Any], _ approval: ToolApproval? = nil, + @MainActor static func approve(_ tool: String, _ digest: String, _ a: [String: Any], _ approval: ToolApproval? = nil, now: Date = Date()) throws -> ConfirmedPreview { guard let id = a["preview_id"] as? String, !id.isEmpty else { throw ToolError(description: "confirm: true needs the preview_id from this tool's preview. Call it without confirm, show the user the list, and confirm only after they say yes.") @@ -766,7 +778,7 @@ enum MCPServer { /// `lines` replaces the window's list when the JSON result shows only part of it (e.g. a huge Trash): /// the person always sees every item. - private static func withPreview(_ tool: String, _ digest: String, _ result: [String: Any], + @MainActor private static func withPreview(_ tool: String, _ digest: String, _ result: [String: Any], lines: [String]? = nil, cleanupPlan: CleanupPlan? = nil) -> [String: Any] { var r = result let request = ApprovalRequest(tool: tool, verb: verb(for: tool), lines: lines ?? approvalLines(result)) @@ -777,7 +789,7 @@ enum MCPServer { // MARK: - Helpers - private static func findApp(_ a: [String: Any]) throws -> AppInfo { + @MainActor private static func findApp(_ a: [String: Any]) throws -> AppInfo { guard let q = a["app"] as? String, !q.isEmpty else { throw ToolError(description: "Pass app (name, bundle id or path).") } if appCache.isEmpty { appCache = AppEngine.scanAll() } if let hit = AppEngine.find(q, in: appCache) { return hit } @@ -786,7 +798,7 @@ enum MCPServer { throw ToolError(description: "No installed app matches \"\(q)\". Use list_apps to see names.") } - private static func replace(_ app: AppInfo) { + @MainActor private static func replace(_ app: AppInfo) { if let i = appCache.firstIndex(where: { $0.id == app.id }) { appCache[i] = app } } diff --git a/MacCleaner/MacCleanerApp.swift b/MacCleaner/MacCleanerApp.swift index 13c50be..8d30a31 100644 --- a/MacCleaner/MacCleanerApp.swift +++ b/MacCleaner/MacCleanerApp.swift @@ -23,18 +23,38 @@ enum Entry { #endif SettingsMigration.migrate() if args.count > 1 && args[1] == "--cli" { - exit(CLI.run(Array(args.dropFirst(2)))) + let cliArgs = Array(args.dropFirst(2)) + if CLI.subcommand(cliArgs) == "bench" { + // Bench spins the main run loop itself (Bench.time); it would hang inside runOnMain's loop. + exit(MainActor.assumeIsolated { CLI.run(cliArgs) }) + } + runOnMain { CLI.run(cliArgs) } } if CommandLine.arguments.contains("--selftest") { SelfTest.installTestApprover() // never show a real confirmation window during the self-test exit(SelfTest.run() ? 0 : 1) } if CommandLine.arguments.contains("--mcp") { - MCPServer.run() - exit(0) + runOnMain { MCPServer.run(); return 0 } } MacCleanerApp.main() } + + /// Runs `body` on the main actor inside a running main run loop, then exits with its code. Used by `--mcp` and + /// `--cli` only. The body starts from a main-queue task, so everything it does (including the approval dialog's + /// run-loop mode and any `@MainActor` hop) sees a live main run loop. + /// + /// Never `dispatchMain()`: it parks the main thread in the dispatch main-queue drain, so the main CFRunLoop is not + /// run in its default/common modes (the probe reports mode=nil) and `RunLoop.main` timers and sources outside a + /// modal are not serviced. (`NSAlert.runModal` would still spin the loop itself.) + /// `CFRunLoopRun()` returns when no sources remain, hence the loop. Exit codes go through `exit(...)` unchanged. + /// + /// Bench (`--cli bench`) and the self-test stay outside: both spin `RunLoop.main` themselves and wait for work + /// from the main thread, which would hang or re-enter if they ran inside a main-queue callout. + static func runOnMain(_ body: @escaping @MainActor () -> Int32) -> Never { + Task { @MainActor in exit(body()) } + while true { CFRunLoopRun() } + } } struct MacCleanerApp: App { diff --git a/MacCleaner/SelfTest.swift b/MacCleaner/SelfTest.swift index fc49191..5f04c9a 100644 --- a/MacCleaner/SelfTest.swift +++ b/MacCleaner/SelfTest.swift @@ -128,8 +128,8 @@ enum SelfTest { ProtectedPaths.set(ProtectedPaths.all + ["/Library/LaunchDaemons/com.example.keep.plist"]) return !AdminGuard.isAllowed(URL(fileURLWithPath: "/Library/LaunchDaemons/com.example.keep.plist")) }()) - let keepPreview = (try? MCPServer.call("move_to_trash", ["paths": [keep.path]])) as? [String: Any] - let mcp = (try? MCPServer.call("move_to_trash", ["paths": [keep.path], "confirm": true, + let keepPreview = (try? mcpCall("move_to_trash", ["paths": [keep.path]])) as? [String: Any] + let mcp = (try? mcpCall("move_to_trash", ["paths": [keep.path], "confirm": true, "preview_id": keepPreview?["preview_id"] as? String ?? ""])) as? [String: Any] check("MCP move_to_trash refuses protected even with an approved confirm", (mcp?["moved_to_trash"] as? [String])?.isEmpty == true && fm.fileExists(atPath: keep.path)) @@ -590,63 +590,65 @@ enum SelfTest { fm.createFile(atPath: mB.path, contents: Data("b".utf8)) let bothThere = { fm.fileExists(atPath: mA.path) && fm.fileExists(atPath: mB.path) } check("confirm without a preview_id is refused, nothing moved", - (try? MCPServer.call("move_to_trash", ["paths": [mA.path], "confirm": true])) == nil && bothThere()) - let pv = (try? MCPServer.call("move_to_trash", ["paths": [mA.path]])) as? [String: Any] + (try? mcpCall("move_to_trash", ["paths": [mA.path], "confirm": true])) == nil && bothThere()) + let pv = (try? mcpCall("move_to_trash", ["paths": [mA.path]])) as? [String: Any] let pid = pv?["preview_id"] as? String ?? "" check("a preview returns a preview_id", !pid.isEmpty) check("confirming a different list than the preview is refused", - (try? MCPServer.call("move_to_trash", ["paths": [mA.path, mB.path], "confirm": true, "preview_id": pid])) == nil && bothThere()) + (try? mcpCall("move_to_trash", ["paths": [mA.path, mB.path], "confirm": true, "preview_id": pid])) == nil && bothThere()) check("a preview_id works once", - (try? MCPServer.call("move_to_trash", ["paths": [mA.path], "confirm": true, "preview_id": pid])) == nil && bothThere()) - let okID = MCPServer.issuePreview("clean_caches", "plan") - check("matching tool and plan is approved", (try? MCPServer.approve("clean_caches", "plan", ["preview_id": okID])) != nil) - let otherTool = MCPServer.issuePreview("clean_caches", "plan") + (try? mcpCall("move_to_trash", ["paths": [mA.path], "confirm": true, "preview_id": pid])) == nil && bothThere()) + let okID = MainActor.assumeIsolated { MCPServer.issuePreview("clean_caches", "plan") } + check("matching tool and plan is approved", + MainActor.assumeIsolated { (try? MCPServer.approve("clean_caches", "plan", ["preview_id": okID])) != nil }) + let otherTool = MainActor.assumeIsolated { MCPServer.issuePreview("clean_caches", "plan") } check("a preview_id from another tool is refused", - (try? MCPServer.approve("empty_trash", "plan", ["preview_id": otherTool])) == nil) - let old = MCPServer.issuePreview("clean_caches", "plan", now: Date().addingTimeInterval(-MCPServer.previewLifetime - 1)) - check("an expired preview_id is refused", (try? MCPServer.approve("clean_caches", "plan", ["preview_id": old])) == nil) + MainActor.assumeIsolated { (try? MCPServer.approve("empty_trash", "plan", ["preview_id": otherTool])) == nil }) + let old = MainActor.assumeIsolated { MCPServer.issuePreview("clean_caches", "plan", now: Date().addingTimeInterval(-MCPServer.previewLifetime - 1)) } + check("an expired preview_id is refused", + MainActor.assumeIsolated { (try? MCPServer.approve("clean_caches", "plan", ["preview_id": old])) == nil }) print("MCP: the person approves in Mac Cleaner's own window, for the exact files (SAFE-03)") let hA = sandbox.appendingPathComponent("mcp-human.txt") fm.createFile(atPath: hA.path, contents: Data("h".utf8)) approvals.asked = []; approvals.answer = false - let hPreview = (try? MCPServer.call("move_to_trash", ["paths": [hA.path]])) as? [String: Any] + let hPreview = (try? mcpCall("move_to_trash", ["paths": [hA.path]])) as? [String: Any] let hID = hPreview?["preview_id"] as? String ?? "" - let declined = (try? MCPServer.call("move_to_trash", ["paths": [hA.path], "confirm": true, "preview_id": hID])) == nil + let declined = (try? mcpCall("move_to_trash", ["paths": [hA.path], "confirm": true, "preview_id": hID])) == nil check("an AI confirm the person declines in Mac Cleaner's window changes nothing", declined && fm.fileExists(atPath: hA.path) && approvals.asked.count == 1) check("the window lists exactly the previewed item, with Mac Cleaner's own wording", approvals.asked.first?.verb == "Move to Trash" && approvals.asked.first?.lines.contains { $0.contains("mcp-human.txt") } == true) check("a declined preview can't be confirmed again", - (try? MCPServer.call("move_to_trash", ["paths": [hA.path], "confirm": true, "preview_id": hID])) == nil + (try? mcpCall("move_to_trash", ["paths": [hA.path], "confirm": true, "preview_id": hID])) == nil && fm.fileExists(atPath: hA.path)) // A path that doesn't exist: the call goes through (and is skipped) without touching the real Trash. let ghost = sandbox.appendingPathComponent("mcp-ghost.txt").path approvals.asked = []; approvals.answer = true - let gID = ((try? MCPServer.call("move_to_trash", ["paths": [ghost]])) as? [String: Any])?["preview_id"] as? String ?? "" + let gID = ((try? mcpCall("move_to_trash", ["paths": [ghost]])) as? [String: Any])?["preview_id"] as? String ?? "" check("an AI confirm the person approves goes ahead", - (try? MCPServer.call("move_to_trash", ["paths": [ghost], "confirm": true, "preview_id": gID])) != nil + (try? mcpCall("move_to_trash", ["paths": [ghost], "confirm": true, "preview_id": gID])) != nil && approvals.asked.count == 1) approvals.asked = []; approvals.answer = false - let tID = ((try? MCPServer.call("move_to_trash", ["paths": [ghost]])) as? [String: Any])?["preview_id"] as? String ?? "" + let tID = ((try? mcpCall("move_to_trash", ["paths": [ghost]])) as? [String: Any])?["preview_id"] as? String ?? "" check("a CLI confirm (the person said yes at the terminal) needs no second window", - (try? MCPServer.call("move_to_trash", ["paths": [ghost], "confirm": true, "preview_id": tID], approval: .terminal)) != nil + (try? mcpCall("move_to_trash", ["paths": [ghost], "confirm": true, "preview_id": tID], approval: .terminal)) != nil && approvals.asked.isEmpty) // Same path, different file: replaced (new inode) or edited (size/time) between preview and confirm. approvals.asked = []; approvals.answer = true let hR = sandbox.appendingPathComponent("mcp-replaced.txt") fm.createFile(atPath: hR.path, contents: Data("v1".utf8)) - let rID = ((try? MCPServer.call("move_to_trash", ["paths": [hR.path]])) as? [String: Any])?["preview_id"] as? String ?? "" + let rID = ((try? mcpCall("move_to_trash", ["paths": [hR.path]])) as? [String: Any])?["preview_id"] as? String ?? "" try? fm.removeItem(at: hR) fm.createFile(atPath: hR.path, contents: Data("v2".utf8)) check("a file replaced at the same path after the preview is refused before anyone is asked", - (try? MCPServer.call("move_to_trash", ["paths": [hR.path], "confirm": true, "preview_id": rID])) == nil + (try? mcpCall("move_to_trash", ["paths": [hR.path], "confirm": true, "preview_id": rID])) == nil && (try? String(contentsOf: hR, encoding: .utf8)) == "v2" && approvals.asked.isEmpty) - let eID = ((try? MCPServer.call("move_to_trash", ["paths": [hR.path]])) as? [String: Any])?["preview_id"] as? String ?? "" + let eID = ((try? mcpCall("move_to_trash", ["paths": [hR.path]])) as? [String: Any])?["preview_id"] as? String ?? "" if let fh = try? FileHandle(forWritingTo: hR) { fh.seekToEndOfFile(); fh.write(Data("more".utf8)); try? fh.close() } check("a file edited after the preview is refused", - (try? MCPServer.call("move_to_trash", ["paths": [hR.path], "confirm": true, "preview_id": eID])) == nil + (try? mcpCall("move_to_trash", ["paths": [hR.path], "confirm": true, "preview_id": eID])) == nil && fm.fileExists(atPath: hR.path) && approvals.asked.isEmpty) let idDir = sandbox.appendingPathComponent("mcp-dir") try? fm.createDirectory(at: idDir, withIntermediateDirectories: true) @@ -748,8 +750,8 @@ enum SelfTest { let many = (0..<600).map { homeTrash.appendingPathComponent(String(format: "selftest-%03d.txt", $0)) } for f in many { fm.createFile(atPath: f.path, contents: Data("t".utf8)) } approvals.asked = []; approvals.answer = false - let tp = (try? MCPServer.call("empty_trash", [:])) as? [String: Any] - _ = try? MCPServer.call("empty_trash", ["confirm": true, "preview_id": tp?["preview_id"] as? String ?? ""]) + let tp = (try? mcpCall("empty_trash", [:])) as? [String: Any] + _ = try? mcpCall("empty_trash", ["confirm": true, "preview_id": tp?["preview_id"] as? String ?? ""]) let shownLines = approvals.asked.first?.lines ?? [] check("a large Trash: the JSON lists 500 and says how many more; the window lists every item", (tp?["listed"] as? [String])?.count == 500 && (tp?["listed_more"] as? Int).map { $0 >= 100 } == true @@ -1598,10 +1600,10 @@ extension SelfTest { func log(_ u: URL) -> [TrashedItem] { TrashLog.shared.present().filter { $0.original == AppCleanup.physicalPath(u) } } func putBack(_ u: URL) -> Bool { log(u).first.map { TrashOps.restore($0) == nil } ?? false } func previewID(_ paths: [URL]) -> String { - ((try? MCPServer.call("move_to_trash", ["paths": paths.map(\.path)])) as? [String: Any])?["preview_id"] as? String ?? "" + ((try? mcpCall("move_to_trash", ["paths": paths.map(\.path)])) as? [String: Any])?["preview_id"] as? String ?? "" } func confirm(_ paths: [URL], _ id: String, _ approval: ToolApproval? = nil) -> [String: Any]? { - (try? MCPServer.call("move_to_trash", ["paths": paths.map(\.path), "confirm": true, "preview_id": id], + (try? mcpCall("move_to_trash", ["paths": paths.map(\.path), "confirm": true, "preview_id": id], approval: approval)) as? [String: Any] } let outstanding = { wait { await AppCleanup.executor.outstandingApprovals } ?? -1 } @@ -1641,14 +1643,14 @@ extension SelfTest { // Changed or replaced while the person was looking at the window (after the digest check). let s = file("mcp-stale") - HumanApproval.ask = { _ in try? Data("written while asking".utf8).write(to: s); return true } + setApprover { _ in try? Data("written while asking".utf8).write(to: s); return true } let stale = confirm([s], previewID([s])) check("a file changed during the confirmation is left alone and reported", (stale?["moved_to_trash"] as? [String])?.isEmpty == true && (stale?["errors"] as? [String])?.first?.contains("changed after you reviewed") == true && (try? String(contentsOf: s, encoding: .utf8)) == "written while asking") let p = file("mcp-replaced", "v1") - HumanApproval.ask = { _ in try? fm.removeItem(at: p); try? Data("v2".utf8).write(to: p); return true } + setApprover { _ in try? fm.removeItem(at: p); try? Data("v2".utf8).write(to: p); return true } let replaced = confirm([p], previewID([p])) installTestApprover(); approvals.answer = true check("a file replaced during the confirmation is left alone and reported", @@ -2348,15 +2350,15 @@ extension SelfTest { approvals.asked = []; approvals.answer = true /// The id the tool itself reports for the item (as an AI client would use it). func toolID(_ tool: String, _ args: [String: Any], endingWith tail: String) -> String { - let items = ((try? MCPServer.call(tool, args)) as? [String: Any])?["items"] as? [[String: Any]] ?? [] + let items = ((try? mcpCall(tool, args)) as? [String: Any])?["items"] as? [[String: Any]] ?? [] return items.compactMap { $0["id"] as? String }.first { $0.hasSuffix(tail) } ?? "missing" } let archTail = "/Archives/2026-01-01/SelfTest-\(runID).xcarchive" func sdkConfirm(_ approval: ToolApproval?) -> [String: Any]? { let sdkID = toolID("list_sdks", ["group": "Xcode"], endingWith: archTail) - let pv = (try? MCPServer.call("remove_sdks", ["ids": [sdkID]])) as? [String: Any] + let pv = (try? mcpCall("remove_sdks", ["ids": [sdkID]])) as? [String: Any] let id = pv?["preview_id"] as? String ?? "" - return (try? MCPServer.call("remove_sdks", ["ids": [sdkID], "confirm": true, "preview_id": id], approval: approval)) as? [String: Any] + return (try? mcpCall("remove_sdks", ["ids": [sdkID], "confirm": true, "preview_id": id], approval: approval)) as? [String: Any] } let m1 = sdkConfirm(nil) check("MCP remove_sdks moves the archive through the executor after the window, logged as the AI assistant", @@ -2368,7 +2370,7 @@ extension SelfTest { (m2?["errors"] as? [String])?.isEmpty == true && log(mcpArch).first?.source == "Developer SDKs · Command line (--yes, not confirmed by a person)") _ = putBack(mcpArch) - HumanApproval.ask = { _ in try? fm.removeItem(at: mcpArch); _ = folder(mcpArch, "replaced while asking"); return true } + setApprover { _ in try? fm.removeItem(at: mcpArch); _ = folder(mcpArch, "replaced while asking"); return true } let m3 = sdkConfirm(nil) installTestApprover(); approvals.answer = true check("an archive replaced during the confirmation window is left alone and reported", @@ -2378,9 +2380,9 @@ extension SelfTest { _ = toolID("list_sdks", ["group": "Xcode"], endingWith: archTail) let scanID = toolID("list_sdks", ["group": "Xcode"], endingWith: archTail) try? fm.removeItem(at: mcpArch); _ = folder(mcpArch, "replaced after list_sdks") - let rpv = (try? MCPServer.call("remove_sdks", ["ids": [scanID]])) as? [String: Any] + let rpv = (try? mcpCall("remove_sdks", ["ids": [scanID]])) as? [String: Any] let rRow = (rpv?["items"] as? [[String: Any]])?.first - let rc = (try? MCPServer.call("remove_sdks", ["ids": [scanID], "confirm": true, + let rc = (try? mcpCall("remove_sdks", ["ids": [scanID], "confirm": true, "preview_id": rpv?["preview_id"] as? String ?? ""])) as? [String: Any] check("an archive replaced between list_sdks and the preview is refused and isn't moved", rRow?["allowed"] as? Bool == false && (rRow?["reason"] as? String)?.contains("changed since the scan") == true @@ -2388,8 +2390,8 @@ extension SelfTest { let mcpBackup = folder(home.appendingPathComponent("Library/Application Support/MobileSync/Backup/selftest-\(runID)"), "mcp backup") let backupID = toolID("system_data", [:], endingWith: "/MobileSync/Backup/selftest-\(runID)") - let spv = (try? MCPServer.call("remove_system_data", ["ids": [backupID]])) as? [String: Any] - let sm = (try? MCPServer.call("remove_system_data", ["ids": [backupID], "confirm": true, + let spv = (try? mcpCall("remove_system_data", ["ids": [backupID]])) as? [String: Any] + let sm = (try? mcpCall("remove_system_data", ["ids": [backupID], "confirm": true, "preview_id": spv?["preview_id"] as? String ?? ""], approval: .terminal)) as? [String: Any] check("MCP remove_system_data moves the backup through the executor, logged with who confirmed", (sm?["errors"] as? [String])?.isEmpty == true && !fm.fileExists(atPath: mcpBackup.path) @@ -3148,8 +3150,8 @@ extension SelfTest { .write(to: mcpApp.appendingPathComponent("Contents/Info.plist"), atomically: true) approvals.asked = []; approvals.answer = true let mcpBundleID = "com.example.selftest.uninstall\(runID)" // unique: only this fake app can match it - let up = (try? MCPServer.call("uninstall_app", ["app": mcpBundleID])) as? [String: Any] - let uc = (try? MCPServer.call("uninstall_app", ["app": mcpBundleID, "confirm": true, + let up = (try? mcpCall("uninstall_app", ["app": mcpBundleID])) as? [String: Any] + let uc = (try? mcpCall("uninstall_app", ["app": mcpBundleID, "confirm": true, "preview_id": up?["preview_id"] as? String ?? ""])) as? [String: Any] check("MCP uninstall_app removes the previewed app through the executor after the window, logged with who confirmed", uc?["app_removed"] as? Bool == true && !fm.fileExists(atPath: mcpApp.path) && approvals.asked.count == 1 diff --git a/MacCleaner/SelfTestSubprocess.swift b/MacCleaner/SelfTestSubprocess.swift index 9b368cc..69da397 100644 --- a/MacCleaner/SelfTestSubprocess.swift +++ b/MacCleaner/SelfTestSubprocess.swift @@ -194,6 +194,8 @@ extension SelfTest { mcpFraming(home: home) mcpBurst(home: home) cliUnknownScan(home: home, scratch: dir) + cliBenchRoutes(home: home, scratch: dir) + cliMcpPing(home: home, scratch: dir) #if MACCLEANER_TEST_HOOKS // Every child that could move a file is gated on the isolated Trash AND on the sandbox home. if subprocessTrashIsIsolated() && childHomeIsSandbox(home: home, scratch: dir) { @@ -284,6 +286,23 @@ extension SelfTest { r.code == 64 && r.err.hasPrefix("Unknown scan “nosuchscan”. Scans: junk, storage,") && r.out.isEmpty) } + // MARK: 8. CLI bench stays on the sync path (PR 1a) + + /// `--cli bench` spins the main run loop itself, so it must not run inside Entry.runOnMain. A hang fails by the deadline. + private static func cliBenchRoutes(home: String, scratch: URL) { + let r = runCLI(["bench", "sdks"], home: home, timeout: 60, scratch: scratch) + check("--cli bench sdks on the sandbox home exits 0 within 60 s and prints the bench header and its result row (bench stays outside runOnMain)", + r.code == 0 && r.out.contains("scan") && r.out.contains("median s") && r.out.contains("sdks") && r.err.isEmpty) + } + + /// `--cli mcp` is the same one stdin reader as `--mcp`: a ping, then end of input, gives one reply and exit 0. + private static func cliMcpPing(home: String, scratch: URL) { + let r = runCLI(["mcp"], home: home, input: .text(rpc(1, "ping") + "\n"), scratch: scratch) + let lines = r.out.split(separator: "\n").map(String.init) + check("--cli mcp with a ping then end of input: one reply (id 1) and exit 0", + r.code == 0 && lines.count == 1 && replyID(jsonObject(lines.first)) == 1) + } + // MARK: In-process pins private static func inProcessPins(dir: URL, runID: String) { @@ -302,8 +321,8 @@ extension SelfTest { approvals.asked = []; approvals.answer = true chflags(locked.path, UInt32(UF_IMMUTABLE)) let paths = [free.path, locked.path] - let preview = (try? MCPServer.call("move_to_trash", ["paths": paths])) as? [String: Any] - let reply = (try? MCPServer.call("move_to_trash", ["paths": paths, "confirm": true, + let preview = (try? mcpCall("move_to_trash", ["paths": paths])) as? [String: Any] + let reply = (try? mcpCall("move_to_trash", ["paths": paths, "confirm": true, "preview_id": preview?["preview_id"] as? String ?? ""])) as? [String: Any] chflags(locked.path, 0) let errors = reply?["errors"] as? [String] ?? [] @@ -336,10 +355,10 @@ extension SelfTest { approvals.asked = []; approvals.answer = true let outstanding = { wait { await AppCleanup.executor.outstandingApprovals } ?? -1 } let before = outstanding() - let appPreview = (try? MCPServer.call("uninstall_app", ["app": bundleID])) as? [String: Any] + let appPreview = (try? mcpCall("uninstall_app", ["app": bundleID])) as? [String: Any] var failure = "" do { - _ = try MCPServer.call("uninstall_app", ["app": bundleID, "confirm": true, + _ = try mcpCall("uninstall_app", ["app": bundleID, "confirm": true, "preview_id": appPreview?["preview_id"] as? String ?? ""]) } catch { failure = "\(error)" } check("MCP uninstall_app preview of a running app reports running: true", @@ -427,6 +446,8 @@ extension SelfTest { check("--mcp behind a slow confirm: the confirm's reply is the declined error, the pings' results are empty objects", toolText(replies3.first)?.isError == true && toolText(replies3.first)?.text.contains("did not approve") == true && replies3.dropFirst().allSatisfy { ($0["result"] as? [String: Any])?.isEmpty == true }) + check("--mcp behind a slow confirm: the simulated dialog's modal-mode timer fired inside the main run loop (modalTimerFired=true)", + probeLines(probe3.path).count == 1 && probeLines(probe3.path).first?["modalTimerFired"] == "true") check("--mcp behind a slow confirm: the file is untouched and the isolated Trash unchanged", fm.fileExists(atPath: f3.path) && isolatedTrashCount() == trashBefore) @@ -444,6 +465,8 @@ extension SelfTest { } check("--mcp reply-after-dialog ordering: after a 400 ms dialog the confirm's reply (id 2) is the first line and the ping's (id 3) the second", ok5 && replyID(first) == 2 && toolText(first)?.text.contains("did not approve") == true && replyID(second) == 3 && status5 == 0) + check("--mcp reply-after-dialog ordering: the simulated dialog's modal-mode timer fired (modalTimerFired=true)", + probeLines(probe5.path).count == 1 && probeLines(probe5.path).first?["modalTimerFired"] == "true") check("--mcp reply-after-dialog ordering: the file is untouched", fm.fileExists(atPath: f5.path) && isolatedTrashCount() == trashBefore) } @@ -472,7 +495,7 @@ extension SelfTest { check("--mcp approval probe: the file is unmoved and unchanged, and the isolated Trash is unchanged", (try? String(contentsOf: f4, encoding: .utf8)) == "keep me" && isolatedTrashCount() == trashBefore) - // 6. Baseline before PR 1a: the sync read loop never spins the main run loop. + // 6. Fingerprint (PR 1a): the approval runs inside the running main run loop (Entry.runOnMain). let f6 = sandboxFile(dir, "baseline", runID) let probe6 = dir.appendingPathComponent("approval-probe-baseline-\(runID).txt") var ping6: [String: Any]? @@ -486,9 +509,9 @@ extension SelfTest { _ = c.finish() } let lines6 = probeLines(probe6.path) - check("baseline (sync loop, before PR 1a): the main run loop isn't running while MCP handles a request (probe: ticks=0, mode=nil)", - ok6 && replyID(ping6) == 1 && lines6.count == 1 && lines6.first?["ticks"] == "0" && lines6.first?["mode"] == "nil" - && fm.fileExists(atPath: f6.path)) + check("PR 1a: the MCP approval runs inside the running main run loop (mode=kCFRunLoopDefaultMode, main=1); ticks stay 0 until stdin moves off main in PR 1b", + ok6 && replyID(ping6) == 1 && lines6.count == 1 && lines6.first?["main"] == "1" + && lines6.first?["mode"] == "kCFRunLoopDefaultMode" && lines6.first?["ticks"] == "0" && fm.fileExists(atPath: f6.path)) if let l = lines6.first { print(" (run-loop fingerprint today: \(l))") } } @@ -518,6 +541,8 @@ extension SelfTest { check("--mcp reply only after the move: an approved confirm (400 ms dialog, answer yes) asks once on the main thread (main=1)", ok && probeLines(probe.path).count == 1 && probeLines(probe.path).first?["main"] == "1" && probeLines(probe.path).first?["isMainThread"] == "true") + check("--mcp reply only after the move: the simulated dialog's modal-mode timer fired (modalTimerFired=true)", + probeLines(probe.path).first?["modalTimerFired"] == "true") check("--mcp reply only after the move: the confirm's reply is the first line and reports the file moved", replyID(first) == 2 && toolText(first)?.isError == false && moved == [Scanner.tilde(f)]) check("--mcp reply only after the move: when that reply is read the file is already gone from its place and in the isolated Trash", diff --git a/MacCleaner/SelfTestSupport.swift b/MacCleaner/SelfTestSupport.swift index 5f803a8..cef6ec6 100644 --- a/MacCleaner/SelfTestSupport.swift +++ b/MacCleaner/SelfTestSupport.swift @@ -11,6 +11,16 @@ extension SelfTest { /// Called before `run()` (see `Entry.main`): MCP confirms in the self-test are answered by `approvals`. static func installTestApprover() { - HumanApproval.ask = { r in approvals.asked.append(r); return approvals.answer } + setApprover { r in approvals.asked.append(r); return approvals.answer } + } + + // MCPServer and HumanApproval.ask are main-actor state. The self-test runs synchronously on the main thread + // (never inside a main-queue callout), so these assume that isolation instead of hopping. + static func setApprover(_ ask: @escaping @MainActor (ApprovalRequest) -> Bool) { + MainActor.assumeIsolated { HumanApproval.ask = ask } + } + + static func mcpCall(_ name: String, _ a: [String: Any], approval: ToolApproval? = nil) throws -> Any { + try MainActor.assumeIsolated { try MCPServer.call(name, a, approval: approval) } } } diff --git a/MacCleaner/TestHooks.swift b/MacCleaner/TestHooks.swift index 6e32242..119cdd6 100644 --- a/MacCleaner/TestHooks.swift +++ b/MacCleaner/TestHooks.swift @@ -33,13 +33,22 @@ enum TestHooks { ticks += 1 } CFRunLoopAddTimer(CFRunLoopGetMain(), timer, .commonModes) - HumanApproval.ask = { _ in - if delayMS > 0 { usleep(UInt32(delayMS) * 1000) } // stands in for an open dialog + MainActor.assumeIsolated { HumanApproval.ask = { _ in let mode = CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent()).map { ($0.rawValue as String) } ?? "nil" + // Stands in for an open dialog: spin the main run loop in modal-panel mode (as NSAlert.runModal does) + // until a one-shot modal-mode timer fires, with a hard upper bound. + var fired = false + if delayMS > 0 { + let t = Timer(timeInterval: Double(delayMS) / 1000, repeats: false) { _ in fired = true } + RunLoop.main.add(t, forMode: .modalPanel) + let limit = Date().addingTimeInterval(Double(delayMS) / 1000 + 5) + while !fired && Date() < limit { RunLoop.main.run(mode: .modalPanel, before: Date().addingTimeInterval(0.01)) } + t.invalidate() + } append("main=\(pthread_main_np()) isMainThread=\(Thread.isMainThread) " - + "mainRunLoop=\(CFRunLoopGetCurrent() == CFRunLoopGetMain()) mode=\(mode) ticks=\(ticks)", to: path) + + "mainRunLoop=\(CFRunLoopGetCurrent() == CFRunLoopGetMain()) mode=\(mode) ticks=\(ticks) modalTimerFired=\(delayMS > 0 ? "\(fired)" : "n/a")", to: path) return answer - } + } } } } }