diff --git a/CHANGELOG.md b/CHANGELOG.md index 008d08e..7b4b105 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ MacMCP is in early development, so tools and policy keys may change before 1.0. ### Added +- A kill switch for the person at the Mac: ⌃⇧⌘\ (or the menu bar item's "Stop and pause agents", or `mac-mcp pause`) + stops the running action and pauses agents. Only `mac-mcp resume` in Terminal resumes. A menu bar item shows when + an agent is driving; `--hide-indicator` hides it. The pause state survives restarts. +- `mac-mcp setup`: a guided first run that opens the right System Settings panes and waits for the grants. +- `mac-mcp install --client` and `uninstall --client` for Claude Code, Claude Desktop, Codex, Cursor and VS Code. They + edit only MacMCP's entry, keep a backup in MacMCP's protected support folder, and refuse files they can't parse. +- A Claude Code plugin with a driving-macos skill: `/plugin marketplace add Playback-Software/mac-mcp`. +- `scripts/measure-actions.py` and `MAC_MCP_DEBUG_ACTIONS=1` for per-action walk counts and timings. - `CONTRIBUTING.md` and this changelog. - A `VERSION` file at the repo root. `scripts/build.sh` reads it, and a unit test fails if the CLI's version differs. - A GitHub Actions workflow that builds, runs the unit tests and runs `scripts/lint-blocking.sh` on a macOS 26 @@ -15,6 +23,16 @@ MacMCP is in early development, so tools and policy keys may change before 1.0. ### Changed +- `mac_snapshot` output over its budget keeps controls ahead of text, keeps the focused and selected rows and the + window's bottom controls, collapses runs of similar list rows, and marks each gap. +- Actions refuse a ref that was never shown (a guessed one); find it with `query=` or a new snapshot. +- Tool descriptions and server instructions are about 27% shorter, and say to trust an action's diff rather than + snapshot again. +- Actions reuse settle's final walk for the report: clicks and menu commands are about 16% faster. +- Protected-path checks resolve the protected locations once per check, so a 5,000-file Finder selection is checked + in about 1 s instead of 13–26 s. +- OCR hands frames to Vision directly and, within one `mac_wait`, skips frames that haven't changed. +- VS Code's, VS Code Insiders' and Cursor's user folders are protected like other AI clients' settings. - `scripts/build.sh` and `scripts/setup-signing.sh` stop with a fix when full Xcode or Swift 6.1+ is missing, and `build.sh` ends with a hint when `~/.local/bin` isn't on `PATH`. - `swift test` prints a notice when it skips the integration tests, pointing at `scripts/integration.sh`. @@ -22,6 +40,16 @@ MacMCP is in early development, so tools and policy keys may change before 1.0. skipped hang phase as a problem unless `--no-chaos` was passed. - `scripts/protocol-probe.py` has a shebang and is executable. +### Fixed + +- `mac_script` refused every allowed app that had a window on macOS 27: its open-documents check required the window + server and Accessibility to list the same number of windows, and macOS 27 adds offscreen helper windows to every + app. The check now matches each window to its Accessibility element by window ID, and skips only offscreen helper + windows whose title is present and empty (read with Screen Recording); a document window always has a title. +- `mac_script` refused every reference to an app's documents or Safari's tabs: the document gate's own inventory + query encoded "every" with the wrong descriptor type, so apps rejected it. The gate now works as documented. +- `mac_menu` accepts a path sent as a JSON array inside a string (`"[\"File\", \"Save As…\"]"`). + ### Documentation - The policy reference describes `shortcuts.timeout_seconds` and `alert_cooldown_minutes`. diff --git a/Sources/MacMCPCore/Act/ScriptHost.swift b/Sources/MacMCPCore/Act/ScriptHost.swift index 96c151b..33eee73 100644 --- a/Sources/MacMCPCore/Act/ScriptHost.swift +++ b/Sources/MacMCPCore/Act/ScriptHost.swift @@ -292,6 +292,12 @@ public enum ScriptHost { if let reply { let response: NSAppleEventDescriptor if ScriptHost.propertyCode(descriptor.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))) == "ppth", let ref { + // Model Cocoa's collection selector validation, not just its path reply. + let paths = descriptor.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)) + let documents = paths?.forKeyword(AEKeyword(keyAEContainer)) + guard let ordinal = documents?.forKeyword(AEKeyword(keyAEKeyData)), + ordinal.descriptorType == typeAbsoluteOrdinal, + ordinal.data == NSAppleEventDescriptor(enumCode: OSType(kAEAll)).data else { return OSErr(errAEWrongDataType) } let gate = Unmanaged.fromOpaque(ref).takeUnretainedValue() response = NSAppleEventDescriptor(eventClass: ScriptHost.codeValue("aevt"), eventID: ScriptHost.codeValue("ansr"), targetDescriptor: nil, returnID: AEReturnID(kAutoGenerateReturnID), transactionID: AETransactionID(kAnyTransactionID)) @@ -738,7 +744,9 @@ public enum ScriptHost { record.setDescriptor(container, forKeyword: AEKeyword(keyAEContainer)) return record.coerce(toDescriptorType: typeObjectSpecifier) } - let all = NSAppleEventDescriptor(enumCode: OSType(kAEAll)) + // Cocoa rejects enum/all as an absolute-position selector. AppleScript uses abso/all for `every`. + guard let all = NSAppleEventDescriptor(descriptorType: typeAbsoluteOrdinal, + data: NSAppleEventDescriptor(enumCode: OSType(kAEAll)).data) else { return nil } var container = NSAppleEventDescriptor.null() if tabs { guard let windows = object("cwin", form: OSType(formAbsolutePosition), key: all, container: container) else { return nil } diff --git a/Sources/MacMCPCore/Act/Scripts.swift b/Sources/MacMCPCore/Act/Scripts.swift index 6a8c32a..adc0cd7 100644 --- a/Sources/MacMCPCore/Act/Scripts.swift +++ b/Sources/MacMCPCore/Act/Scripts.swift @@ -3,6 +3,10 @@ import ApplicationServices import Foundation import MachO +// Accessibility has no public window-ID attribute. Never substitute a coincident frame when this lookup fails. +@_silgen_name("_AXUIElementGetWindow") +private func scriptAXWindowID(_ element: AXUIElement, _ id: UnsafeMutablePointer) -> AXError + /// App automation with a source preflight and an Apple-event gate in a disposable signed host. public enum Scripts { public enum Language: String, Sendable, CaseIterable { @@ -499,25 +503,75 @@ enum ScriptDocuments { static func snapshot(bundleID: String) -> Snapshot { snapshot(bundleID: bundleID, source: Source( applications: { Scripts.runningApplications(bundleID: $0) }, trusted: AXIsProcessTrusted, - windowCount: { pid in + serverWindows: { pid in guard let windows = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[String: Any]] else { return nil } - return windows.filter { ($0[kCGWindowOwnerPID as String] as? pid_t) == pid }.count + // Preflight can cache a denial: keep exemptions disabled in that case. A cached grant alone + // is insufficient; exemptions also require an empty CGWindowName in this fresh, live inventory. + return windowInventory(pid: pid, info: windows, displays: WindowServer.activeDisplays(), + screenRecording: CGPreflightScreenCaptureAccess()) }, windows: { pid in let read = AXElement.application(pid: pid, timeout: 0.2).attribute(reporting: kAXWindowsAttribute) guard read.error == nil, let windows = read.value as? [AXUIElement] else { return nil } return windows.map(AXElement.init) }, read: { element in AXUIElementSetMessagingTimeout(element.raw, 0.2) - return element.read(reporting: [kAXDocumentAttribute, kAXURLAttribute, kAXRoleAttribute, kAXChildrenAttribute, kAXTabsAttribute]) + return element.read(reporting: [kAXDocumentAttribute, kAXURLAttribute, kAXRoleAttribute, kAXPositionAttribute, + kAXSizeAttribute, kAXChildrenAttribute, kAXTabsAttribute]) + }, windowID: { element in + var id = kCGNullWindowID + guard scriptAXWindowID(element.raw, &id) == .success, id != kCGNullWindowID else { return nil } + return id }, elements: { ($0 as? [AXUIElement])?.map(AXElement.init) })) } + struct Window: Equatable { + let id: CGWindowID + let bounds: CGRect + let onscreen: Bool + } + + /// Unordered windows are not necessarily backing windows: minimized windows and windows on other Spaces + /// must remain in this inventory. A document window always has a title (its file's name), so only an offscreen + /// window whose name is present and empty, read with Screen Recording live, and with the backing traits measured + /// below is exempt. Its size isn't: apps' helper windows vary (64×64 and 500×500 icon windows, 100×132, menu-bar + /// strips). An absent name (including redaction without Screen Recording) is unknown, and onscreen windows are + /// always checked. + static func windowInventory(pid: pid_t, info: [[String: Any]], displays: [CGRect], screenRecording: Bool) -> [Window]? { + var windows: [Window] = [], ids: Set = [] + for entry in info { + guard let owner = entry[kCGWindowOwnerPID as String] as? pid_t else { return nil } + guard owner == pid else { continue } + guard let layer = entry[kCGWindowLayer as String] as? Int else { return nil } + guard layer == 0 else { continue } // Includes neither Finder's desktop nor elevated system chrome. + guard let id = entry[kCGWindowNumber as String] as? CGWindowID, ids.insert(id).inserted, + let dictionary = entry[kCGWindowBounds as String] as? [String: Any], + let bounds = CGRect(dictionaryRepresentation: dictionary as CFDictionary), + bounds.origin.x.isFinite, bounds.origin.y.isFinite, bounds.width.isFinite, bounds.height.isFinite, + bounds.width >= 0, bounds.height >= 0 else { return nil } + guard bounds.width > 0, bounds.height > 0 else { continue } + if let title = entry[kCGWindowName as String], !(title is String) { return nil } + if let onscreen = entry[kCGWindowIsOnscreen as String], !(onscreen is Bool) { return nil } + let onscreen = entry[kCGWindowIsOnscreen as String] as? Bool ?? false + // Finder/TextEdit backing windows measured on macOS 27.2: sharing=read-only, store=nonretained, alpha=1. + // All three must be present and exact; window movement/resizing cannot establish these traits. + if screenRecording, entry[kCGWindowName as String] as? String == "", !onscreen, + entry[kCGWindowSharingState as String] as? Int == Int(CGWindowSharingType.readOnly.rawValue), + entry[kCGWindowStoreType as String] as? Int == Int(CGWindowBackingType.backingStoreNonretained.rawValue), + entry[kCGWindowAlpha as String] as? Double == 1 { + continue + } + windows.append(Window(id: id, bounds: bounds, onscreen: onscreen)) + } + return windows.sorted { $0.id < $1.id } + } + struct Source { let applications: (String) -> [Scripts.RunningApplication] let trusted: () -> Bool - let windowCount: (pid_t) -> Int? + let serverWindows: (pid_t) -> [Window]? let windows: (pid_t) -> [Element]? let read: (Element) -> AXElement.Read? + let windowID: (Element) -> CGWindowID? let elements: (Any) -> [Element]? } @@ -531,8 +585,10 @@ enum ScriptDocuments { let deadline = ContinuousClock.now.advanced(by: .seconds(2)) var tabsPerWindow: [Int] = [] for app in apps { + guard let serverWindows = source.serverWindows(app.pid), serverWindows.count <= 512 else { return Snapshot(.unavailable) } guard let windows = source.windows(app.pid), windows.count <= 128, - source.windowCount(app.pid) == windows.count else { return Snapshot(.unavailable) } + Set(windows).count == windows.count else { return Snapshot(.unavailable) } + var checkedIDs: [Element: CGWindowID] = [:], checkedFrames: [CGWindowID: CGRect] = [:] for window in windows { var queue = [(window, false)], seen: Set = [], tabs: Set = [], visited = 0 while !queue.isEmpty { @@ -542,6 +598,20 @@ enum ScriptDocuments { // A tab may also occur in AXChildren. Recheck it in tab context rather than losing its URL requirement. if !seen.insert(element).inserted, !tab { continue } guard let read = source.read(element), read.errors.isEmpty else { return Snapshot(.unavailable) } + if let role = read.values[kAXRoleAttribute] as? String, + [kAXWindowRole, kAXSheetRole, kAXDrawerRole, "AXPopover"].contains(role) { + guard let bounds = frame(position: read.values[kAXPositionAttribute], size: read.values[kAXSizeAttribute]), + let id = source.windowID(element), id != kCGNullWindowID else { + return Snapshot(.unavailable) + } + if let previous = checkedIDs[element] { + guard previous == id, checkedFrames[id] == bounds else { return Snapshot(.unavailable) } + } else { + guard checkedFrames[id] == nil else { return Snapshot(.unavailable) } + checkedIDs[element] = id + checkedFrames[id] = bounds + } + } var values: [String] = [] for key in [kAXDocumentAttribute, kAXURLAttribute] { guard let value = read.values[key] else { continue } @@ -564,7 +634,16 @@ enum ScriptDocuments { if bundleID.lowercased() == "com.apple.safari", tabs.isEmpty { return Snapshot(.unavailable) } tabsPerWindow.append(tabs.count) } - guard ContinuousClock.now < deadline, source.windowCount(app.pid) == windows.count else { return Snapshot(.unavailable) } + // Sheets/popovers have CG windows of their own but occur under their parent in AX. Conversely Finder + // includes its desktop scroll area in AXWindows. Require coverage, not equality of those two counts. + // Bind coverage to window identity as well as frame: an AXWindow panel on layer 3 cannot cover a + // missing layer-0 document at the same frame. A failed private ID lookup never falls back to frames. + for window in serverWindows { + guard checkedFrames[window.id] == window.bounds else { return Snapshot(.unavailable) } + } + guard ContinuousClock.now < deadline, source.serverWindows(app.pid) == serverWindows, + let currentWindows = source.windows(app.pid), Set(currentWindows) == Set(windows), + currentWindows.count == windows.count else { return Snapshot(.unavailable) } } return Snapshot(.safe, inventory: Inventory(pid: apps[0].pid, tabsPerWindow: tabsPerWindow)) } diff --git a/Sources/MacMCPServer/Tools/ActionTools.swift b/Sources/MacMCPServer/Tools/ActionTools.swift index a343938..181cba5 100644 --- a/Sources/MacMCPServer/Tools/ActionTools.swift +++ b/Sources/MacMCPServer/Tools/ActionTools.swift @@ -107,15 +107,18 @@ enum ActionTools { """, properties: [ "app": Prop.string(), - "path": Prop.string("\"Format > Make Plain Text\" or [\"File\", \"Save As…\"]; ignores case and ellipses."), + "path": Prop.string("Steps separated by \" > \", e.g. \"File > Save As…\"; ignores case and ellipses."), ], required: ["path"], annotations: .action, deadline: { _ in lockedDeadline(actionDeadline) } ) { args, _ in let raw = args.raw["path"] - let path: [String] = raw?.arrayValue?.compactMap(\.stringValue) - ?? (args.string("path") ?? "").components(separatedBy: ">").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } + let text = (args.string("path") ?? "").trimmingCharacters(in: .whitespaces) + // Some clients send the array form as a JSON string: '["File", "Save As…"]'. + let encoded = text.hasPrefix("[") ? (try? JSONDecoder().decode([String].self, from: Data(text.utf8))) : nil + let path: [String] = raw?.arrayValue?.compactMap(\.stringValue) ?? encoded + ?? text.components(separatedBy: ">").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } guard !path.isEmpty else { return .error("path is required, e.g. \"File > Save As…\".") } if let refusal = SessionSafety.refusal(menuPath: path) { return .error(refusal) } if let refused = await RouteGuards.menu(path, app: args.string("app")) { return refused } diff --git a/Tests/IntegrationTests/ScriptEnforcementTests.swift b/Tests/IntegrationTests/ScriptEnforcementTests.swift index c43ffc4..fa40813 100644 --- a/Tests/IntegrationTests/ScriptEnforcementTests.swift +++ b/Tests/IntegrationTests/ScriptEnforcementTests.swift @@ -68,7 +68,8 @@ extension Integration { let scripts = [ ("Mail", "tell application \"Mail\"\nif (count of messages of inbox) > 0 then\nget read status of message 1 of inbox\nelse\nreturn true\nend if\nend tell"), ("TextEdit", "tell application \"TextEdit\" to get name of every document"), - ("Finder", "tell application \"Finder\" to get name of every file of desktop"), + // Finder's desktop container cannot be mapped to a file path, so file enumeration fails closed. + ("Finder", "tell application \"Finder\" to count of windows"), ] for (app, script) in scripts { try withPolicy(#"{"script":{"allowed_apps":["\#(app)"],"timeout_seconds":30}}"#) { @@ -81,13 +82,15 @@ extension Integration { } @Test func additionsAddressedToAnAllowedAppAreStillRefused() async throws { - for command in ["system info", "path to home folder", "list disks"] { + // Bypass parent AX preflight so this verifies the addition's event-code refusal even when the runner + // lacks Accessibility. An absent document-gate socket must not be the reason these commands are refused. + for (command, refusal) in [("system info", "system info"), ("path to home folder", "path to"), ("list disks", "list disks")] { // Use a variable to avoid app terminology: the addition is still addressed to TextEdit at runtime. let source = "use scripting additions\nset target to application \"TextEdit\"\ntell target to " + command #expect(Scripts.refusal(source: source, language: .applescript, policy: policy) == nil) let result = try await runEventHost(source, language: .applescript, policy: policy) #expect(result.status != 0 && result.stdout.isEmpty) - #expect(result.stderr.contains("Refused Apple event"), "\(command): \(result.stderr)") + #expect(result.stderr.contains("Refused Apple event: \(refusal)."), "\(command): \(result.stderr)") } } diff --git a/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift b/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift index a97050c..3d5251f 100644 --- a/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift +++ b/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift @@ -1,6 +1,7 @@ import AppKit import Carbon import Foundation +import OSAKit import Testing @testable import MacMCPCore @@ -811,7 +812,15 @@ import Testing #expect(paths.forKeyword(AEKeyword(keyAEKeyData))?.typeCodeValue == code(property)) let items = try #require(paths.forKeyword(AEKeyword(keyAEContainer))) #expect(items.forKeyword(AEKeyword(keyAEDesiredClass))?.typeCodeValue == code(tabs ? "bTab" : "docu")) - #expect(items.forKeyword(AEKeyword(keyAEKeyData))?.enumCodeValue == OSType(kAEAll)) + let ordinal = try #require(items.forKeyword(AEKeyword(keyAEKeyData))) + #expect(ordinal.descriptorType == typeAbsoluteOrdinal) + #expect(ordinal.data == NSAppleEventDescriptor(enumCode: OSType(kAEAll)).data) + if tabs { + let windows = try #require(items.forKeyword(AEKeyword(keyAEContainer))) + let windowOrdinal = try #require(windows.forKeyword(AEKeyword(keyAEKeyData))) + #expect(windowOrdinal.descriptorType == typeAbsoluteOrdinal) + #expect(windowOrdinal.data == ordinal.data) + } #expect(ScriptHost.fileRefusal(query, target: target, dictionary: dictionary) == nil) let ordinary = event("coregetd") ordinary.setParam(try self.property("pnam", of: indexedObject("cwin")), forKeyword: AEKeyword(keyDirectObject)) @@ -821,6 +830,64 @@ import Testing } } + @Test func textEditOffscreenUntitledDocumentUsesAppleScriptCollectionOrdinal() throws { + let editor = P.Target.application(bundleID: "com.apple.TextEdit", name: "TextEdit") + let dictionary = ScriptHost.Dictionary(target: editor) + #expect(dictionary.documentInventory(target: editor) == .init(property: "ppth", tabs: false)) + let windows = try #require(documentWindows([ + serverWindow(id: 718, onscreen: false, title: "Untitled"), + serverWindow(id: 717, bounds: CGRect(x: 0, y: 482, width: 500, height: 500), onscreen: false, title: ""), + ])) + #expect(windows.map(\.id) == [718]) + let snapshot = ScriptDocuments.snapshot(bundleID: "com.apple.TextEdit", source: documentSource( + serverWindows: windows, windows: [718], frames: [718: documentFrame], reads: [ + 718: .init(values: [kAXRoleAttribute: kAXWindowRole, kAXSubroleAttribute: "AXDialog", + kAXTitleAttribute: "Untitled", kAXChildrenAttribute: [1]]), + 1: .init(values: [kAXRoleAttribute: kAXScrollAreaRole, kAXChildrenAttribute: [2]]), + 2: .init(values: [kAXRoleAttribute: kAXTextAreaRole]), + ])) + #expect(snapshot.check == .safe) + let inventory = try #require(snapshot.inventory) + #expect(inventory == .init(pid: 42, tabsPerWindow: [0])) + #expect(inventory.documentCount == 1) + + // Build Apple's canonical reference locally. Veto every send, including terminology requests; + // neither compilation nor evaluation of this reference may contact TextEdit or any other app. + let language = try #require(OSALanguage(forName: "AppleScript")) + let instance = OSALanguageInstance(language: language) + let component = instance.componentInstance + let veto: OSASendUPP = { _, _, _, _, _, _, _, _ in OSErr(errAEEventNotPermitted) } + try #require(OSASetSendProc(component, veto, nil) == noErr) + var script: OSAID = 0, result: OSAID = 0 + defer { + if result != 0 { OSADispose(component, result) } + if script != 0 { OSADispose(component, script) } + withExtendedLifetime(instance) {} + } + let source = NSAppleEventDescriptor(string: "return a reference to «property ppth» of every «class docu»") + try #require(OSACompile(component, source.aeDesc, 0, &script) == noErr) + try #require(OSAExecute(component, script, OSAID(kOSANullScript), 0, &result) == noErr) + var raw = AEDesc() + try #require(OSACoerceToDesc(component, result, typeObjectSpecifier, 0, &raw) == noErr) + let reference = NSAppleEventDescriptor(aeDescNoCopy: &raw) + let documents = try #require(reference.forKeyword(AEKeyword(keyAEContainer))) + let ordinal = try #require(documents.forKeyword(AEKeyword(keyAEKeyData))) + #expect(ordinal.descriptorType == typeAbsoluteOrdinal) + for key in ["pnam", "ppth"] { + let read = event("coregetd") + read.setParam(try property(key, of: documents), forKeyword: AEKeyword(keyDirectObject)) + let refusal = ScriptHost.documentRefusal(read, target: editor, dictionary: dictionary, inventory: inventory) { plan in + let query = plan.event(address: NSAppleEventDescriptor(processIdentifier: inventory.pid)) + let paths = query?.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)) + let items = paths?.forKeyword(AEKeyword(keyAEContainer)) + let actual = items?.forKeyword(AEKeyword(keyAEKeyData)) + guard actual?.descriptorType == ordinal.descriptorType, actual?.data == ordinal.data else { return nil } + return inventoryReply([NSAppleEventDescriptor(typeCode: OSType(cMissingValue))]) + } + #expect(refusal == nil, "\(key): \(refusal ?? "")") + } + } + @Test func appInventoryCoversCollectionsSubclassesAndCurrentDocumentProperties() throws { let editor = P.Target.application(bundleID: "com.apple.TextEdit", name: "TextEdit") let dictionary = inventoryDictionary(property: "file") @@ -872,14 +939,232 @@ import Testing } @Test func documentGateRefusesWindowsMissingFromAXIncludingOtherSpaces() { - for count in [nil, 0, 2] as [Int?] { - #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(windowCount: count)) == .unavailable) + for displays in [[], [primaryDisplay]] { + for info in [nil, [serverWindow(id: 1), serverWindow(id: 2, onscreen: false)], + [serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 500, height: 500))]] as [[[String: Any]]?] { + let source = documentSource(serverWindows: info.flatMap { documentWindows($0, displays: displays) }) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .unavailable) + } } let protected = FileManager.default.homeDirectoryForCurrentUser.path + "/.ssh/config" let source = documentSource(reads: [1: AXElement.Read(values: [kAXDocumentAttribute: protected])]) #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .protected) } + @Test func documentGateMatchesFinderAndTextEditWithoutBackingChrome() throws { + let display = CGRect(x: 0, y: 0, width: 1512, height: 982) + let chrome = [serverWindow(id: 10, bounds: CGRect(x: 0, y: 482, width: 64, height: 64), onscreen: false, title: "")] + + (11...14).map { serverWindow(id: CGWindowID($0), bounds: CGRect(x: 0, y: 0, width: 1512, height: 33), onscreen: false, title: "") } + let textEdit = try #require(documentWindows(chrome + [serverWindow(id: 1)], displays: [display])) + #expect(textEdit.count == 1) + #expect(ScriptDocuments.snapshot(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: textEdit)).inventory == .init(pid: 42, tabsPerWindow: [0])) + let finderBounds = CGRect(x: 296, y: 141, width: 920, height: 436) + let finder = try #require(documentWindows(chrome + [ + serverWindow(id: 1, bounds: finderBounds), serverWindow(id: 2, bounds: display, layer: -2147483603, title: ""), + ], displays: [display])) + let source = documentSource(serverWindows: finder, windows: [1, 2], frames: [1: finderBounds], reads: [ + 1: .init(values: [:]), 2: .init(values: [kAXRoleAttribute: kAXScrollAreaRole]), + ]) + #expect(ScriptDocuments.snapshot(bundleID: "com.apple.finder", source: source).inventory == .init(pid: 42, tabsPerWindow: [0, 0])) + } + + @Test func documentGateMatchesMailSheetAndSkipsItsUntitledHelperWindows() throws { + let main = CGRect(x: 226, y: 76, width: 1059, height: 688) + let sheet = CGRect(x: 521, y: 212, width: 470, height: 416) + let display = CGRect(x: 0, y: 0, width: 1512, height: 982) + let info = [serverWindow(id: 1, bounds: main), serverWindow(id: 2, bounds: sheet, title: "")] + + (3...6).map { serverWindow(id: CGWindowID($0), bounds: CGRect(x: 0, y: 0, width: 1512, height: 33), onscreen: false, title: "") } + var reads = [1: AXElement.Read(values: [kAXChildrenAttribute: [2]]), 2: .init(values: [kAXRoleAttribute: kAXSheetRole])] + let frames = [1: main, 2: sheet] + let checked = try #require(documentWindows(info, displays: [display])) + #expect(checked.count == 2) + #expect(ScriptDocuments.snapshot(bundleID: "com.apple.mail", source: documentSource(serverWindows: checked, frames: frames, reads: reads)).inventory == .init(pid: 42, tabsPerWindow: [0])) + let home = FileManager.default.homeDirectoryForCurrentUser.path + reads[2]?.values[kAXDocumentAttribute] = home + "/.ssh/config" + #expect(ScriptDocuments.check(bundleID: "com.apple.mail", source: documentSource(serverWindows: checked, frames: frames, reads: reads)) == .protected) + reads[2]?.values.removeValue(forKey: kAXDocumentAttribute) + // The live eight-window Mail shape has two more offscreen windows. Untitled, they aren't documents (a + // document window takes its file's name), so they're skipped; titled, they'd have to match AX. + let all = try #require(documentWindows(info + [ + serverWindow(id: 7, bounds: CGRect(x: 0, y: 482, width: 500, height: 500), onscreen: false, title: ""), + serverWindow(id: 8, bounds: CGRect(x: 100, y: 750, width: 100, height: 132), onscreen: false, title: ""), + ], displays: [display])) + #expect(all.count == 2) + #expect(ScriptDocuments.check(bundleID: "com.apple.mail", source: documentSource(serverWindows: all, frames: frames, reads: reads)) == .safe) + let titled = try #require(documentWindows(info + [ + serverWindow(id: 7, bounds: CGRect(x: 0, y: 482, width: 500, height: 500), onscreen: false, title: "Draft"), + ], displays: [display])) + #expect(ScriptDocuments.check(bundleID: "com.apple.mail", source: documentSource(serverWindows: titled, frames: frames, reads: reads)) == .unavailable) + } + + @Test func documentGateKeepsMinimizedHiddenAndOtherSpaceWindows() throws { + let other = CGRect(x: 50, y: 50, width: 586, height: 488) + // isOnscreen=false must not discard a titled window, or one whose title couldn't be read. No Space switch + // is needed to test that omitting it from AX fails closed, while an AX-listed minimized/hidden window is + // checked. (An offscreen window with an empty title isn't a document; see the helper-window tests.) + for displays in [[], [primaryDisplay]] { + for title in ["Document", nil] as [String?] { + let checked = try #require(documentWindows([serverWindow(id: 1), + serverWindow(id: 2, bounds: other, onscreen: false, title: title)], displays: displays)) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .unavailable) + let source = documentSource(serverWindows: checked, windows: [1, 2], frames: [1: documentFrame, 2: other], + reads: [1: .init(values: [:]), 2: .init(values: [kAXMinimizedAttribute: true])]) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .safe) + } + } + } + + @Test func documentGateRefusesAXErrorsTruncatedWalksAndCoincidentMissingWindows() { + for reads in [[:], [1: .init(values: [:], errors: [kAXDocumentAttribute: .cannotComplete])], + [1: .init(values: [kAXChildrenAttribute: Array(2...514)])], + Dictionary(uniqueKeysWithValues: (1...513).map { ($0, AXElement.Read(values: [kAXChildrenAttribute: [$0 + 1]])) }), + [1: .init(values: [kAXChildrenAttribute: "not an element list"])]] as [[Int: AXElement.Read]] { + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(reads: reads)) == .unavailable) + } + let coincident = [ScriptDocuments.Window(id: 1, bounds: documentFrame, onscreen: true), .init(id: 2, bounds: documentFrame, onscreen: false)] + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: coincident)) == .unavailable) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(windows: nil)) == .unavailable) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(trusted: false)) == .unavailable) + } + + @Test func documentWindowInventoryRefusesMalformedMetadataAndKeepsTitledSmallWindows() { + for displays in [[], [primaryDisplay]] { + for key in [kCGWindowOwnerPID, kCGWindowLayer, kCGWindowNumber, kCGWindowBounds] { + var info = serverWindow(id: 1) + info.removeValue(forKey: key as String) + #expect(documentWindows([info], displays: displays) == nil) + } + for bounds in [CGRect(x: 0, y: 482, width: 64, height: 64), menuStrip] { + let titled = serverWindow(id: 1, bounds: bounds, onscreen: false) + #expect(documentWindows([titled], displays: displays)?.count == 1) + } + } + } + + @Test func documentBackingExemptionsRequireScreenRecordingAndAnExplicitlyEmptyName() throws { + for bounds in [CGRect(x: 0, y: 482, width: 64, height: 64), menuStrip] { + for recording in [false, true] { + for title in [nil, ""] as [String?] { + // CG omits isOnscreen for the live unordered backing windows, and omits names without TCC. + let info = serverWindow(id: 2, bounds: bounds, onscreen: nil, title: title) + let checked = try #require(documentWindows([serverWindow(id: 1), info], screenRecording: recording)) + let exempt = recording && title == "" + #expect(checked.count == (exempt ? 1 : 2)) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == (exempt ? .safe : .unavailable)) + } + } + } + } + + @Test func documentBackingExemptionsKeepOnscreenAndTitledWindowsOfAnySize() throws { + let secondary = CGRect(x: 1512, y: 0, width: 1512, height: 982) + let shapes = [CGRect(x: 0, y: 482, width: 64, height: 64), CGRect(x: 0, y: 482, width: 500, height: 500), + CGRect(x: 0, y: 0, width: 1512, height: 41), CGRect(x: 1512, y: 0, width: 1512, height: 33), + CGRect(x: 200, y: 200, width: 100, height: 132)] + for bounds in shapes { + for candidate in [serverWindow(id: 2, bounds: bounds, title: ""), // onscreen: AX must see it + serverWindow(id: 2, bounds: bounds, onscreen: false, title: "notes.txt")] { + let checked = try #require(documentWindows([serverWindow(id: 1), candidate], displays: [primaryDisplay, secondary])) + #expect(checked.count == 2) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .unavailable) + } + } + } + + /// Measured on macOS 27.2: TextEdit's offscreen helper window was 64×64 in one session and 500×500 in the next, + /// and Mail has 500×500 and 100×132 ones. Offscreen and untitled, they're exempt whatever their size. + @Test func offscreenUntitledHelperWindowsAreExemptWhateverTheirSize() throws { + for bounds in [CGRect(x: 0, y: 482, width: 500, height: 500), CGRect(x: 0, y: 482, width: 100, height: 132), + CGRect(x: 0, y: 0, width: 1511, height: 33)] { + let checked = try #require(documentWindows([serverWindow(id: 1), serverWindow(id: 2, bounds: bounds, onscreen: false, title: "")])) + #expect(checked.count == 1) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .safe) + } + } + + @Test func documentBackingExemptionsRequireMeasuredSharingStoreAndAlpha() throws { + for bounds in [CGRect(x: 0, y: 482, width: 64, height: 64), menuStrip] { + for key in [kCGWindowSharingState, kCGWindowStoreType, kCGWindowAlpha] { + for value in [nil, 0, 2, 0.5, "1"] as [Any?] { + var candidate = serverWindow(id: 2, bounds: bounds, onscreen: false, title: "") + candidate[key as String] = value + let checked = try #require(documentWindows([serverWindow(id: 1), candidate])) + #expect(checked.count == 2) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .unavailable) + } + } + } + } + + @Test func menuBarStripsAreSkippedWhateverTheirHeight() throws { + for height in [24, 33, 34] as [CGFloat] { + let strip = serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 1512, height: height), onscreen: false, title: "") + #expect(documentWindows([strip], menuBarHeight: height)?.isEmpty == true) + #expect(documentWindows([strip], menuBarHeight: nil)?.isEmpty == true) + #expect(documentWindows([strip], displays: [], menuBarHeight: height)?.isEmpty == true) + } + } + + @Test func documentGateCannotUseAFloatingPanelToCoverACoincidentDocument() throws { + let other = CGRect(x: 300, y: 200, width: 400, height: 300) + let checked = try #require(documentWindows([ + serverWindow(id: 1), serverWindow(id: 2, bounds: other, layer: 3), + serverWindow(id: 3, bounds: other, onscreen: false), + ])) + #expect(checked.map(\.id) == [1, 3]) + let frames = [1: documentFrame, 2: other, 3: other] + let missing = documentSource(serverWindows: checked, windows: [1, 2], frames: frames, + reads: [1: .init(values: [:]), 2: .init(values: [kAXRoleAttribute: kAXWindowRole])]) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: missing) == .unavailable) + let complete = documentSource(serverWindows: checked, windows: [1, 2, 3], frames: frames, + reads: [1: .init(values: [:]), 2: .init(values: [:]), 3: .init(values: [:])]) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: complete) == .safe) + } + + @Test func documentGateRefusesFailedNullDuplicateAndWrongAXWindowIDs() { + for ids in [[:], [1: 0], [1: 2]] as [[Int: CGWindowID]] { + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(windowIDs: ids)) == .unavailable) + } + let duplicate = documentSource(windows: [1, 2], frames: [1: documentFrame, 2: documentFrame], windowIDs: [1: 1, 2: 1], + reads: [1: .init(values: [:]), 2: .init(values: [:])]) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: duplicate) == .unavailable) + } + + @Test func documentGateMatchesLayerZeroPopoverIDsAndTreatsDialogAsASubrole() throws { + let popover = CGRect(x: 300, y: 200, width: 320, height: 240) + let checked = try #require(documentWindows([serverWindow(id: 1), serverWindow(id: 2, bounds: popover, title: "")])) + for role in ["AXPopover", kAXWindowRole, "AXDialog"] { + var reads = [1: AXElement.Read(values: [kAXChildrenAttribute: [2]]), + 2: .init(values: [kAXRoleAttribute: role, kAXSubroleAttribute: "AXDialog"])] + let source = documentSource(serverWindows: checked, frames: [1: documentFrame, 2: popover], reads: reads) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == (role == "AXDialog" ? .unavailable : .safe)) + reads[2]?.values[kAXDocumentAttribute] = FileManager.default.homeDirectoryForCurrentUser.path + "/.ssh/config" + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked, frames: [1: documentFrame, 2: popover], reads: reads)) == .protected) + } + } + + @Test func documentGateRefusesChangedWindowIDsFramesOnscreenStateAndAXMembership() { + let base = documentSource() + for replacement in [nil, [.init(id: 2, bounds: documentFrame, onscreen: true)], + [.init(id: 1, bounds: CGRect(x: 153, y: 73, width: 586, height: 488), onscreen: true)], + [.init(id: 1, bounds: documentFrame, onscreen: false)]] as [[ScriptDocuments.Window]?] { + var reads = 0 + let source = ScriptDocuments.Source(applications: base.applications, trusted: base.trusted, + serverWindows: { _ in + reads += 1 + return reads == 1 ? base.serverWindows(42) : replacement + }, windows: base.windows, read: base.read, windowID: base.windowID, elements: base.elements) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .unavailable) + } + var reads = 0 + let source = ScriptDocuments.Source(applications: base.applications, trusted: base.trusted, serverWindows: base.serverWindows, + windows: { _ in + reads += 1 + return reads == 1 ? [1] : [2] + }, read: base.read, windowID: base.windowID, elements: base.elements) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .unavailable) + } + @Test func documentGateChecksEverySafariAndNativeTab() { let home = FileManager.default.homeDirectoryForCurrentUser.path for id in ["com.apple.Safari", "com.apple.TextEdit"] { @@ -904,10 +1189,51 @@ import Testing #expect(ScriptDocuments.check(bundleID: "com.apple.Safari", source: documentSource()) == .unavailable) } + private var documentFrame: CGRect { CGRect(x: 152, y: 73, width: 586, height: 488) } + private var primaryDisplay: CGRect { CGRect(x: 0, y: 0, width: 1512, height: 982) } + private var menuStrip: CGRect { CGRect(x: 0, y: 0, width: 1512, height: 33) } + + private func documentWindows(_ info: [[String: Any]], displays: [CGRect]? = nil, screenRecording: Bool = true, + menuBarHeight: CGFloat? = 33) -> [ScriptDocuments.Window]? { + var info = info + if let height = menuBarHeight { + var bar = serverWindow(id: 9000, bounds: CGRect(x: 0, y: 0, width: 1512, height: height), + layer: Int(CGWindowLevelForKey(.mainMenuWindow))) + bar[kCGWindowOwnerPID as String] = pid_t(777) + bar[kCGWindowOwnerName as String] = "Window Server" + info.append(bar) + } + return ScriptDocuments.windowInventory(pid: 42, info: info, displays: displays ?? [primaryDisplay], screenRecording: screenRecording) + } + + private func serverWindow(id: CGWindowID, bounds: CGRect = CGRect(x: 152, y: 73, width: 586, height: 488), + layer: Int = 0, onscreen: Bool? = true, title: String? = "Document") -> [String: Any] { + var info: [String: Any] = [kCGWindowOwnerPID as String: pid_t(42), kCGWindowNumber as String: id, kCGWindowLayer as String: layer, + kCGWindowBounds as String: bounds.dictionaryRepresentation, kCGWindowSharingState as String: 1, + kCGWindowStoreType as String: 1, kCGWindowAlpha as String: 1.0] + if let onscreen { info[kCGWindowIsOnscreen as String] = onscreen } + if let title { info[kCGWindowName as String] = title } + return info + } + private func documentSource(apps: [Scripts.RunningApplication] = [.init(pid: 42, finishedLaunching: true)], - windowCount: Int? = 1, reads: [Int: AXElement.Read] = [1: .init(values: [:])]) -> ScriptDocuments.Source { - ScriptDocuments.Source(applications: { _ in apps }, trusted: { true }, windowCount: { _ in windowCount }, - windows: { _ in [1] }, read: { reads[$0] }, elements: { $0 as? [Int] }) + serverWindows: [ScriptDocuments.Window]? = [.init(id: 1, bounds: CGRect(x: 152, y: 73, width: 586, height: 488), onscreen: true)], + windows: [Int]? = [1], frames: [Int: CGRect] = [1: CGRect(x: 152, y: 73, width: 586, height: 488)], + trusted: Bool = true, windowIDs: [Int: CGWindowID]? = nil, + reads: [Int: AXElement.Read] = [1: .init(values: [:])]) -> ScriptDocuments.Source { + ScriptDocuments.Source(applications: { _ in apps }, trusted: { trusted }, serverWindows: { _ in serverWindows }, + windows: { _ in windows }, read: { element in + guard var read = reads[element] else { return nil } + if let bounds = frames[element] { + if read.values[kAXRoleAttribute] == nil { read.values[kAXRoleAttribute] = kAXWindowRole } + read.values[kAXPositionAttribute] = bounds.origin + read.values[kAXSizeAttribute] = bounds.size + } + return read + }, windowID: { element in + if let windowIDs { return windowIDs[element] } + return CGWindowID(element) + }, elements: { $0 as? [Int] }) } @Test func finderNavigationChecksProtectedTextWithoutRejectingHome() throws { diff --git a/Tests/MacMCPServerTests/AgentPauseToolTests.swift b/Tests/MacMCPServerTests/AgentPauseToolTests.swift index b606516..78215e6 100644 --- a/Tests/MacMCPServerTests/AgentPauseToolTests.swift +++ b/Tests/MacMCPServerTests/AgentPauseToolTests.swift @@ -160,3 +160,18 @@ import Testing private extension JSONDecoder { func withISO8601() -> JSONDecoder { dateDecodingStrategy = .iso8601; return self } } + +@Suite struct MenuPathArgumentTests { + /// Some clients send the array form of a menu path as a JSON string; it's read as the array, not as one item. + @Test func aJSONArrayStringIsReadAsThePath() async throws { + let directory = NSTemporaryDirectory() + "menu-path-\(UUID())" + defer { try? FileManager.default.removeItem(atPath: directory) } + let server = MacMCPServer.definition(audit: AuditLog(path: directory + "/audit"), tools: MacMCPServer.tools, + pause: AgentPause(paused: false)) + let context = RequestContext(client: "test", protocolVersion: nil, leaseToken: nil, origin: "unit test", + id: UUID().uuidString, leasePath: directory + "/lease") + let result = await server.call("mac_menu", ["path": .string(#"["Apple", "Lock Screen"]"#)], context) + let text = result.content.compactMap { if case let .text(t) = $0 { t } else { nil } }.joined() + #expect(result.isError && text == SessionSafety.refusal(menuPath: ["Apple", "Lock Screen"]), "\(text)") + } +} diff --git a/docs/policy-and-security.md b/docs/policy-and-security.md index 3b34164..7e16e67 100644 --- a/docs/policy-and-security.md +++ b/docs/policy-and-security.md @@ -662,9 +662,28 @@ relaunched by its bundle-ID address. Asynchronous app events are refused because before the script continues. Before execution, before each event to an app and after its send returns (including named System Events process -targets), the parent checks that app's window `AXDocument` and `AXURL` values through Accessibility. It compares the -AX window count with all windows reported by `CGWindowListCopyWindowInfo(.optionAll)`, including other -Spaces and full screen, and refuses mismatches. It checks document/URL values in window descendants and every tab +targets), the parent checks that app's window `AXDocument` and `AXURL` values through Accessibility. It reads +`CGWindowListCopyWindowInfo(.optionAll)`, including offscreen windows, and requires each positive-area, layer-zero +window to match both the window-server ID and frame of a checked AX window, sheet, drawer or popover. The private +`_AXUIElementGetWindow` lookup binds each AX element to its own window; a failed, null or duplicate ID refuses the +app rather than falling back to a frame match. A floating panel on another layer cannot cover a coincident document. +`AXDialog` is a subrole of `AXWindow`, not a separate role. This handles sheets reported as AX descendants and +Finder's desktop scroll area reported in `AXWindows`, without equating the two raw window counts. Other window +layers (including Finder's desktop), empty windows, and narrowly classified backing windows are excluded. +Helper-window exemptions require a non-prompting Screen +Recording preflight and an explicitly present, empty `kCGWindowName` in the fresh window inventory; a missing name +never counts as empty. Without that permission, no window is exempt. The synchronous preflight can cache +a denial, conservatively disabling exemptions until restart; a cached grant alone cannot exempt a window whose +live title key is redacted. The window must also be offscreen, with `kCGWindowSharingState == 1` (read-only), +`kCGWindowStoreType == 1` (nonretained) and `kCGWindowAlpha == 1`, as measured on Finder, TextEdit and Mail helper +windows. Size doesn't count: those helper windows vary (64×64 and 500×500 icon windows, Mail's 100×132 one, +menu-bar strips), and the same app's can change size between sessions. The rule rests on the title instead: a +document window takes its file's name, and a file can't have an empty name, so an offscreen window whose title is +present and empty isn't a document. Titled offscreen windows, windows whose title can't be read, and every onscreen +window must match an AX element by window ID. +Window IDs, frames, onscreen state and AX window membership must stay consistent through the walk. Windows on +another Space or minimized windows must be exposed by AX; a candidate missing from AX refuses the app rather than +assuming it is harmless. It checks document/URL values in window descendants and every tab exposed by AX tab groups or `AXTabs`. A tab without a readable URL/document refuses the app; Safari also requires a tab inventory for every window. If any checked value identifies a protected file, the whole app is refused until a person closes that document. This covers reading a document already open and editing @@ -675,8 +694,9 @@ The disposable host asks the parent afresh through a private local socket; it does not need its own Accessibility grant. These checks inspect the current windows and cannot make the check and an app's later handling of an event atomic with a person's concurrent actions. -AX cannot establish which scripted document or tab a window backs. Before each event using document/tab object -specifiers (including collections, nested properties, dictionary-defined document subclasses and current-document/tab +AX cannot establish which scripted document or tab a window backs. The file-inventory gate below applies to +document/tab selectors, not every app event, so it does not replace the window-coverage preflight. Before each event +using document/tab object specifiers (including collections, nested properties, dictionary-defined document subclasses and current-document/tab properties), the host therefore asks the app itself for its complete file inventory. This is one read-only `get` event for paths only, sent through the same policy, Automation, PID and before/after AX gates; its reply never reaches the script. The host reads the app's local scripting dictionary once per script run to select a readable document @@ -685,7 +705,7 @@ the URL of every tab of every window, covering background tabs as well as the ac Every returned file must resolve locally and pass ProtectedPaths; Safari file URLs receive the same check, while ordinary absolute web URLs are allowed. Explicit no-file values for untitled, never-saved documents are allowed. -The document count must equal the checked AX/CG window inventory, including native document tabs; Safari's nested +The document count must equal the checked AX window inventory, including native document tabs; Safari's nested tab counts must match the checked tab counts for all windows. Counts and the pinned PID must stay consistent across the inventory query. Missing or unreadable properties, unresolved values and mismatched counts keep the existing document/tab-reference refusal. Thus `text of document 1` and `close tab 1` work only with a complete, safe inventory. diff --git a/scripts/integration.sh b/scripts/integration.sh index bb6d107..4876c8a 100755 --- a/scripts/integration.sh +++ b/scripts/integration.sh @@ -15,4 +15,7 @@ if [[ "$agent_pause_status" != *"Agents are running (not paused)."* ]]; then fi export MAC_MCP_LEASE=$("$CLI" lease acquire --holder integration-tests --reason "swift test" --minutes 30 --pid $$) trap '"$CLI" lease release "$MAC_MCP_LEASE" >/dev/null' EXIT -MAC_MCP_INTEGRATION=1 swift test --filter IntegrationTests "$@" +# swift test runs what any --filter matches, so a filter given here replaces the default instead of adding to it. +filter=(--filter IntegrationTests) +[[ " $* " == *" --filter "* ]] && filter=() +MAC_MCP_INTEGRATION=1 swift test "${filter[@]}" "$@"