@aarwitz/tapp 0.34.0 → 0.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +2 -2
- package/MacHarness/tapp-mac-ax.swift +291 -0
- package/README.md +1 -0
- package/bin/tapp.js +53 -8
- package/browser/product-contract.js +4 -4
- package/mcp-server/src/browser-product.js +10 -3
- package/mcp-server/src/index.js +54 -0
- package/mcp-server/src/macos-driver.js +253 -0
- package/mcp-server/src/macos-explorer.js +210 -0
- package/mcp-server/src/macos-flow.js +138 -0
- package/mcp-server/src/platforms.js +15 -9
- package/package.json +4 -2
- package/scripts/run-macos-flow.js +32 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tapp",
|
|
3
3
|
"description": "Give Claude hands and eyes on iOS, Android, and web apps, with exploration, replayable flows, evidence, and deterministic CI gates.",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.35.0",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Aaron Horowitz",
|
|
7
7
|
"url": "https://github.com/aarwitz"
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"command": "npx",
|
|
25
25
|
"args": [
|
|
26
26
|
"-y",
|
|
27
|
-
"@aarwitz/tapp@0.
|
|
27
|
+
"@aarwitz/tapp@0.35.0",
|
|
28
28
|
"mcp"
|
|
29
29
|
],
|
|
30
30
|
"cwd": "${CLAUDE_PROJECT_DIR}"
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
// tapp's macOS desktop driver, one process away from the engine.
|
|
2
|
+
//
|
|
3
|
+
// Android is driven through `adb` and a UIAutomator dump; iOS through XCUITest. macOS has an
|
|
4
|
+
// equivalent that needs neither a test bundle nor a rebuild of the application under test: the
|
|
5
|
+
// Accessibility API. Any running application exposes a tree of AXUIElements with roles, titles,
|
|
6
|
+
// values and actions, which is the same shape the rest of tapp already speaks.
|
|
7
|
+
//
|
|
8
|
+
// This is deliberately a plain command-line tool rather than a test target, so tapp can be
|
|
9
|
+
// pointed at a .app the way it is pointed at an .apk — nothing to link, nothing to re-sign.
|
|
10
|
+
//
|
|
11
|
+
// It requires the Accessibility permission (System Settings → Privacy & Security →
|
|
12
|
+
// Accessibility) for whatever runs it. There is no way to grant that from code and tapp does not
|
|
13
|
+
// try: `trusted` reports the truth and the CLI explains the one-time step.
|
|
14
|
+
//
|
|
15
|
+
// Elements are addressed by their path of child indices from the application element ("0.3.1").
|
|
16
|
+
// A path is only valid for the snapshot it came from, so every action re-reads the tree first —
|
|
17
|
+
// the same discipline as the Android driver's `snap`.
|
|
18
|
+
import ApplicationServices
|
|
19
|
+
import AppKit
|
|
20
|
+
import Foundation
|
|
21
|
+
|
|
22
|
+
// MARK: - Attribute reading
|
|
23
|
+
|
|
24
|
+
func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? {
|
|
25
|
+
var value: CFTypeRef?
|
|
26
|
+
return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
func stringAttribute(_ element: AXUIElement, _ name: String) -> String {
|
|
30
|
+
guard let value = attribute(element, name) else { return "" }
|
|
31
|
+
if let text = value as? String { return text }
|
|
32
|
+
if let number = value as? NSNumber { return number.stringValue }
|
|
33
|
+
// AXValue of a text area can arrive as an attributed string.
|
|
34
|
+
if let attributed = value as? NSAttributedString { return attributed.string }
|
|
35
|
+
return ""
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
func boolAttribute(_ element: AXUIElement, _ name: String, default fallback: Bool) -> Bool {
|
|
39
|
+
guard let value = attribute(element, name) as? NSNumber else { return fallback }
|
|
40
|
+
return value.boolValue
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
func frame(_ element: AXUIElement) -> [Double] {
|
|
44
|
+
var origin = CGPoint.zero
|
|
45
|
+
var size = CGSize.zero
|
|
46
|
+
if let value = attribute(element, kAXPositionAttribute as String) {
|
|
47
|
+
AXValueGetValue(value as! AXValue, .cgPoint, &origin)
|
|
48
|
+
}
|
|
49
|
+
if let value = attribute(element, kAXSizeAttribute as String) {
|
|
50
|
+
AXValueGetValue(value as! AXValue, .cgSize, &size)
|
|
51
|
+
}
|
|
52
|
+
return [Double(origin.x), Double(origin.y), Double(size.width), Double(size.height)]
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
func children(_ element: AXUIElement) -> [AXUIElement] {
|
|
56
|
+
guard let value = attribute(element, kAXChildrenAttribute as String) as? [AXUIElement] else { return [] }
|
|
57
|
+
return value
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
func actions(_ element: AXUIElement) -> [String] {
|
|
61
|
+
var names: CFArray?
|
|
62
|
+
guard AXUIElementCopyActionNames(element, &names) == .success, let list = names as? [String] else { return [] }
|
|
63
|
+
return list
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// MARK: - Walking
|
|
67
|
+
|
|
68
|
+
struct Node: Encodable {
|
|
69
|
+
let path: String
|
|
70
|
+
let role: String
|
|
71
|
+
let subrole: String
|
|
72
|
+
let title: String
|
|
73
|
+
let desc: String
|
|
74
|
+
let value: String
|
|
75
|
+
let identifier: String
|
|
76
|
+
let enabled: Bool
|
|
77
|
+
let focused: Bool
|
|
78
|
+
let frame: [Double]
|
|
79
|
+
let actions: [String]
|
|
80
|
+
var children: [Node]
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/// Caps exist because a document-shaped application (a long outline, a big table) can expose tens
|
|
84
|
+
/// of thousands of elements, and a snapshot that takes a minute is not a snapshot.
|
|
85
|
+
let maxNodesDefault = 2500
|
|
86
|
+
let maxDepthDefault = 28
|
|
87
|
+
|
|
88
|
+
final class Walker {
|
|
89
|
+
var visited = 0
|
|
90
|
+
let maxNodes: Int
|
|
91
|
+
let maxDepth: Int
|
|
92
|
+
init(maxNodes: Int, maxDepth: Int) { self.maxNodes = maxNodes; self.maxDepth = maxDepth }
|
|
93
|
+
|
|
94
|
+
func walk(_ element: AXUIElement, path: String, depth: Int) -> Node {
|
|
95
|
+
visited += 1
|
|
96
|
+
let box = frame(element)
|
|
97
|
+
var node = Node(
|
|
98
|
+
path: path,
|
|
99
|
+
role: stringAttribute(element, kAXRoleAttribute as String),
|
|
100
|
+
subrole: stringAttribute(element, kAXSubroleAttribute as String),
|
|
101
|
+
title: stringAttribute(element, kAXTitleAttribute as String),
|
|
102
|
+
desc: stringAttribute(element, kAXDescriptionAttribute as String),
|
|
103
|
+
value: String(stringAttribute(element, kAXValueAttribute as String).prefix(400)),
|
|
104
|
+
identifier: stringAttribute(element, kAXIdentifierAttribute as String),
|
|
105
|
+
enabled: boolAttribute(element, kAXEnabledAttribute as String, default: true),
|
|
106
|
+
focused: boolAttribute(element, kAXFocusedAttribute as String, default: false),
|
|
107
|
+
frame: box,
|
|
108
|
+
actions: actions(element),
|
|
109
|
+
children: []
|
|
110
|
+
)
|
|
111
|
+
if depth >= maxDepth || visited >= maxNodes { return node }
|
|
112
|
+
for (index, child) in children(element).enumerated() {
|
|
113
|
+
if visited >= maxNodes { break }
|
|
114
|
+
node.children.append(walk(child, path: path.isEmpty ? "\(index)" : "\(path).\(index)", depth: depth + 1))
|
|
115
|
+
}
|
|
116
|
+
return node
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
func element(at path: String, from root: AXUIElement) -> AXUIElement? {
|
|
121
|
+
if path.isEmpty { return root }
|
|
122
|
+
var current = root
|
|
123
|
+
for component in path.split(separator: ".") {
|
|
124
|
+
guard let index = Int(component) else { return nil }
|
|
125
|
+
let kids = children(current)
|
|
126
|
+
guard index >= 0 && index < kids.count else { return nil }
|
|
127
|
+
current = kids[index]
|
|
128
|
+
}
|
|
129
|
+
return current
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// MARK: - Output
|
|
133
|
+
|
|
134
|
+
func emit(_ value: Encodable, pretty: Bool = false) {
|
|
135
|
+
let encoder = JSONEncoder()
|
|
136
|
+
if pretty { encoder.outputFormatting = [.prettyPrinted, .sortedKeys] }
|
|
137
|
+
struct Box<T: Encodable>: Encodable { let v: T }
|
|
138
|
+
guard let data = try? encoder.encode(AnyEncodable(value)) else { fail("could not encode result") }
|
|
139
|
+
FileHandle.standardOutput.write(data)
|
|
140
|
+
FileHandle.standardOutput.write("\n".data(using: .utf8)!)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
struct AnyEncodable: Encodable {
|
|
144
|
+
private let encodeTo: (Encoder) throws -> Void
|
|
145
|
+
init(_ wrapped: Encodable) { encodeTo = wrapped.encode }
|
|
146
|
+
func encode(to encoder: Encoder) throws { try encodeTo(encoder) }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
func fail(_ message: String) -> Never {
|
|
150
|
+
struct Failure: Encodable { let ok = false; let error: String }
|
|
151
|
+
if let data = try? JSONEncoder().encode(Failure(error: message)) {
|
|
152
|
+
FileHandle.standardError.write(data)
|
|
153
|
+
FileHandle.standardError.write("\n".data(using: .utf8)!)
|
|
154
|
+
}
|
|
155
|
+
exit(1)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
struct Ok: Encodable { let ok = true; let detail: String }
|
|
159
|
+
|
|
160
|
+
// MARK: - Arguments
|
|
161
|
+
|
|
162
|
+
var arguments = Array(CommandLine.arguments.dropFirst())
|
|
163
|
+
guard let command = arguments.first else {
|
|
164
|
+
fail("usage: tapp-mac-ax <trusted|launch|tree|press|setvalue|key|windows|quit> [options]")
|
|
165
|
+
}
|
|
166
|
+
arguments = Array(arguments.dropFirst())
|
|
167
|
+
|
|
168
|
+
func option(_ name: String) -> String? {
|
|
169
|
+
guard let index = arguments.firstIndex(of: "--\(name)"), index + 1 < arguments.count else { return nil }
|
|
170
|
+
return arguments[index + 1]
|
|
171
|
+
}
|
|
172
|
+
func intOption(_ name: String, _ fallback: Int) -> Int { Int(option(name) ?? "") ?? fallback }
|
|
173
|
+
|
|
174
|
+
func requirePid() -> pid_t {
|
|
175
|
+
guard let raw = option("pid"), let pid = Int32(raw) else { fail("--pid is required") }
|
|
176
|
+
return pid
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
func requireTrusted() {
|
|
180
|
+
guard AXIsProcessTrusted() else {
|
|
181
|
+
fail("This program is not allowed to use the Accessibility API. Grant it in System Settings → Privacy & Security → Accessibility, for the application that runs tapp (your terminal, or the tapp app).")
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// MARK: - Commands
|
|
186
|
+
|
|
187
|
+
switch command {
|
|
188
|
+
case "trusted":
|
|
189
|
+
struct Trust: Encodable { let trusted: Bool }
|
|
190
|
+
emit(Trust(trusted: AXIsProcessTrusted()))
|
|
191
|
+
|
|
192
|
+
case "launch":
|
|
193
|
+
// Launching is ordinary AppKit, not Accessibility: no permission needed to start a program.
|
|
194
|
+
guard let bundlePath = option("app") else { fail("--app /path/to/App.app is required") }
|
|
195
|
+
let url = URL(fileURLWithPath: bundlePath)
|
|
196
|
+
guard FileManager.default.fileExists(atPath: url.path) else { fail("No application at \(url.path)") }
|
|
197
|
+
let configuration = NSWorkspace.OpenConfiguration()
|
|
198
|
+
configuration.activates = true
|
|
199
|
+
configuration.createsNewApplicationInstance = false
|
|
200
|
+
let semaphore = DispatchSemaphore(value: 0)
|
|
201
|
+
var launched: NSRunningApplication?
|
|
202
|
+
var launchError: Error?
|
|
203
|
+
NSWorkspace.shared.openApplication(at: url, configuration: configuration) { application, error in
|
|
204
|
+
launched = application; launchError = error; semaphore.signal()
|
|
205
|
+
}
|
|
206
|
+
if semaphore.wait(timeout: .now() + 30) == .timedOut { fail("Timed out launching \(url.lastPathComponent)") }
|
|
207
|
+
if let error = launchError { fail("Could not launch \(url.lastPathComponent): \(error.localizedDescription)") }
|
|
208
|
+
guard let application = launched else { fail("Could not launch \(url.lastPathComponent)") }
|
|
209
|
+
struct Launched: Encodable { let ok = true; let pid: Int32; let bundleId: String; let name: String }
|
|
210
|
+
emit(Launched(pid: application.processIdentifier,
|
|
211
|
+
bundleId: application.bundleIdentifier ?? "",
|
|
212
|
+
name: application.localizedName ?? url.deletingPathExtension().lastPathComponent))
|
|
213
|
+
|
|
214
|
+
case "tree":
|
|
215
|
+
requireTrusted()
|
|
216
|
+
let pid = requirePid()
|
|
217
|
+
let application = AXUIElementCreateApplication(pid)
|
|
218
|
+
let walker = Walker(maxNodes: intOption("max-nodes", maxNodesDefault), maxDepth: intOption("max-depth", maxDepthDefault))
|
|
219
|
+
struct Tree: Encodable { let ok = true; let pid: Int32; let app: String; let window: String; let truncated: Bool; let nodes: Int; let root: Node }
|
|
220
|
+
let root = walker.walk(application, path: "", depth: 0)
|
|
221
|
+
// The focused window names the screen, the way an h1 names a web page.
|
|
222
|
+
var window = ""
|
|
223
|
+
if let focused = attribute(application, kAXFocusedWindowAttribute as String) {
|
|
224
|
+
window = stringAttribute(focused as! AXUIElement, kAXTitleAttribute as String)
|
|
225
|
+
}
|
|
226
|
+
if window.isEmpty, let windows = attribute(application, kAXWindowsAttribute as String) as? [AXUIElement], let first = windows.first {
|
|
227
|
+
window = stringAttribute(first, kAXTitleAttribute as String)
|
|
228
|
+
}
|
|
229
|
+
let name = NSRunningApplication(processIdentifier: pid)?.localizedName ?? ""
|
|
230
|
+
emit(Tree(pid: pid, app: name, window: window, truncated: walker.visited >= walker.maxNodes, nodes: walker.visited, root: root))
|
|
231
|
+
|
|
232
|
+
case "press":
|
|
233
|
+
requireTrusted()
|
|
234
|
+
let pid = requirePid()
|
|
235
|
+
guard let path = option("path") else { fail("--path is required") }
|
|
236
|
+
let application = AXUIElementCreateApplication(pid)
|
|
237
|
+
guard let target = element(at: path, from: application) else { fail("No element at path \(path)") }
|
|
238
|
+
let available = actions(target)
|
|
239
|
+
let wanted = option("action") ?? (available.contains(kAXPressAction as String) ? kAXPressAction as String : available.first ?? "")
|
|
240
|
+
guard !wanted.isEmpty else { fail("Element at \(path) has no actions") }
|
|
241
|
+
let code = AXUIElementPerformAction(target, wanted as CFString)
|
|
242
|
+
guard code == .success else { fail("\(wanted) on \(path) failed (AXError \(code.rawValue))") }
|
|
243
|
+
emit(Ok(detail: wanted))
|
|
244
|
+
|
|
245
|
+
case "setvalue":
|
|
246
|
+
requireTrusted()
|
|
247
|
+
let pid = requirePid()
|
|
248
|
+
guard let path = option("path") else { fail("--path is required") }
|
|
249
|
+
let text = option("text") ?? ""
|
|
250
|
+
let application = AXUIElementCreateApplication(pid)
|
|
251
|
+
guard let target = element(at: path, from: application) else { fail("No element at path \(path)") }
|
|
252
|
+
// Focus first: some fields only accept a value while they are the responder, and a field the
|
|
253
|
+
// user can see being filled is what a recording should show.
|
|
254
|
+
AXUIElementSetAttributeValue(target, kAXFocusedAttribute as CFString, kCFBooleanTrue)
|
|
255
|
+
let code = AXUIElementSetAttributeValue(target, kAXValueAttribute as CFString, text as CFTypeRef)
|
|
256
|
+
guard code == .success else { fail("Could not set the value of \(path) (AXError \(code.rawValue))") }
|
|
257
|
+
emit(Ok(detail: "set"))
|
|
258
|
+
|
|
259
|
+
case "key":
|
|
260
|
+
requireTrusted()
|
|
261
|
+
let pid = requirePid()
|
|
262
|
+
guard let name = option("key") else { fail("--key is required") }
|
|
263
|
+
let codes: [String: CGKeyCode] = ["return": 36, "enter": 36, "tab": 48, "space": 49, "delete": 51, "escape": 53,
|
|
264
|
+
"left": 123, "right": 124, "down": 125, "up": 126]
|
|
265
|
+
guard let keyCode = codes[name.lowercased()] else { fail("Unknown key '\(name)'. Known: \(codes.keys.sorted().joined(separator: ", "))") }
|
|
266
|
+
guard let source = CGEventSource(stateID: .hidSystemState) else { fail("Could not create an event source") }
|
|
267
|
+
let down = CGEvent(keyboardEventSource: source, virtualKey: keyCode, keyDown: true)
|
|
268
|
+
let up = CGEvent(keyboardEventSource: source, virtualKey: keyCode, keyDown: false)
|
|
269
|
+
down?.postToPid(pid)
|
|
270
|
+
up?.postToPid(pid)
|
|
271
|
+
emit(Ok(detail: name))
|
|
272
|
+
|
|
273
|
+
case "windows":
|
|
274
|
+
requireTrusted()
|
|
275
|
+
let pid = requirePid()
|
|
276
|
+
let application = AXUIElementCreateApplication(pid)
|
|
277
|
+
struct Window: Encodable { let title: String; let frame: [Double] }
|
|
278
|
+
struct Windows: Encodable { let ok = true; let windows: [Window] }
|
|
279
|
+
let list = (attribute(application, kAXWindowsAttribute as String) as? [AXUIElement] ?? [])
|
|
280
|
+
.map { Window(title: stringAttribute($0, kAXTitleAttribute as String), frame: frame($0)) }
|
|
281
|
+
emit(Windows(windows: list))
|
|
282
|
+
|
|
283
|
+
case "quit":
|
|
284
|
+
let pid = requirePid()
|
|
285
|
+
guard let application = NSRunningApplication(processIdentifier: pid) else { emit(Ok(detail: "not running")); exit(0) }
|
|
286
|
+
application.terminate()
|
|
287
|
+
emit(Ok(detail: "terminated"))
|
|
288
|
+
|
|
289
|
+
default:
|
|
290
|
+
fail("Unknown command '\(command)'")
|
|
291
|
+
}
|
package/README.md
CHANGED
|
@@ -30,6 +30,7 @@ Supported targets:
|
|
|
30
30
|
| iOS | Simulator on macOS with Xcode; driven through XCUITest and accessibility |
|
|
31
31
|
| Android | Connected emulator or device with `adb`; driven through UIAutomator |
|
|
32
32
|
| Web | Owned browser app in Playwright Chromium |
|
|
33
|
+
| macOS desktop | Any `.app` on a Mac, driven through the Accessibility API; needs the Accessibility permission (`tapp doctor` says how) |
|
|
33
34
|
| Windows desktop | WPF, WinForms, and WinUI apps through Windows UI Automation — early runs are set up through the pilot |
|
|
34
35
|
|
|
35
36
|
Windows hosts Android and web testing when their prerequisites are installed, and is the home of
|
package/bin/tapp.js
CHANGED
|
@@ -265,11 +265,9 @@ function repeatedFlagValues(argv, name) {
|
|
|
265
265
|
// `--platform windows` used to be indistinguishable from `--platform wbe`: both got
|
|
266
266
|
// "must be ios|android|web", which tells someone who read runtapp.com's Windows card that they
|
|
267
267
|
// typed it wrong. They did not — tapp has no driver for it yet. Say which of the two it is.
|
|
268
|
-
const DRIVEN_PLATFORMS = ["ios", "android", "web"];
|
|
268
|
+
const DRIVEN_PLATFORMS = ["ios", "android", "web", "macos"];
|
|
269
269
|
const DECLARED_WITHOUT_DRIVER = {
|
|
270
270
|
windows: "Windows desktop applications (WPF, WinForms, WinUI)",
|
|
271
|
-
macos: "macOS desktop applications",
|
|
272
|
-
mac: "macOS desktop applications",
|
|
273
271
|
desktop: "desktop applications",
|
|
274
272
|
};
|
|
275
273
|
function refusePlatform(platform) {
|
|
@@ -277,9 +275,9 @@ function refusePlatform(platform) {
|
|
|
277
275
|
if (described) {
|
|
278
276
|
console.error(`❌ tapp has no driver for ${described} yet, so there is nothing to run here.`);
|
|
279
277
|
console.error(" Early runs are set up with us while the driver lands: hello@runtapp.com");
|
|
280
|
-
console.error(" Today tapp drives: web (anywhere), iOS
|
|
278
|
+
console.error(" Today tapp drives: web (anywhere), iOS and macOS apps (on a Mac), Android (adb).");
|
|
281
279
|
} else {
|
|
282
|
-
console.error("❌ --platform must be ios|android|web");
|
|
280
|
+
console.error("❌ --platform must be ios|android|web|macos");
|
|
283
281
|
}
|
|
284
282
|
process.exit(2);
|
|
285
283
|
}
|
|
@@ -313,10 +311,19 @@ function requireMacFor(what) {
|
|
|
313
311
|
process.exit(1);
|
|
314
312
|
}
|
|
315
313
|
|
|
314
|
+
// A macOS application bundle and an iOS simulator build are both directories called
|
|
315
|
+
// Something.app. The difference is where the executable lives: a Mac bundle keeps it in
|
|
316
|
+
// Contents/MacOS, a simulator build keeps it at the top level.
|
|
317
|
+
function looksLikeMacosBundle(target) {
|
|
318
|
+
try { return /\.app\/?$/.test(target) && fs.existsSync(path.join(target, "Contents", "MacOS")); }
|
|
319
|
+
catch { return false; }
|
|
320
|
+
}
|
|
321
|
+
|
|
316
322
|
function requestedPlatform(flags, target = "") {
|
|
317
323
|
if (typeof flags.platform === "string") return flags.platform.toLowerCase();
|
|
318
324
|
if (/^https?:\/\//i.test(target)) return "web";
|
|
319
325
|
if (/\.apk$/i.test(target)) return "android";
|
|
326
|
+
if (looksLikeMacosBundle(target)) return "macos";
|
|
320
327
|
return "ios";
|
|
321
328
|
}
|
|
322
329
|
|
|
@@ -1021,6 +1028,10 @@ switch (command) {
|
|
|
1021
1028
|
const platform = requestedPlatform(flags, target);
|
|
1022
1029
|
if (!DRIVEN_PLATFORMS.includes(platform)) refusePlatform(platform);
|
|
1023
1030
|
if (platform === "ios") requireMacFor("iOS testing");
|
|
1031
|
+
if (platform === "macos") {
|
|
1032
|
+
requireMacFor("macOS application testing");
|
|
1033
|
+
if (!target) { console.error("❌ macOS exploration needs an application: tapp explore /Applications/Yours.app"); process.exit(2); }
|
|
1034
|
+
}
|
|
1024
1035
|
if (flags.watch === true && platform !== "web") {
|
|
1025
1036
|
console.error("❌ --watch is currently available for web exploration only");
|
|
1026
1037
|
process.exit(2);
|
|
@@ -1035,7 +1046,7 @@ switch (command) {
|
|
|
1035
1046
|
}
|
|
1036
1047
|
const bundleId = platform === "ios" ? await resolveTargetOrExit(engine, target) : null;
|
|
1037
1048
|
const android = platform === "android" ? androidTarget(flags, target) : null;
|
|
1038
|
-
const progressMetric = platform === "web" ? "pages reached" : platform === "ios" ? "structural states observed" : "screens reached";
|
|
1049
|
+
const progressMetric = platform === "web" ? "pages reached" : platform === "ios" ? "structural states observed" : platform === "macos" ? "window states observed" : "screens reached";
|
|
1039
1050
|
const onProgress = (p) =>
|
|
1040
1051
|
writeProgress(`🔍 Exploring… ${p.action}/${p.max || flags.actions || 60} actions · ${p.states} ${progressMetric}`);
|
|
1041
1052
|
// --interactive: when the run meets a sign-in it has no credentials for, it stops and asks
|
|
@@ -1092,6 +1103,17 @@ switch (command) {
|
|
|
1092
1103
|
surface: "cli",
|
|
1093
1104
|
onProgress,
|
|
1094
1105
|
})
|
|
1106
|
+
: platform === "macos"
|
|
1107
|
+
? await engine.runQaMacos({
|
|
1108
|
+
appPath: target,
|
|
1109
|
+
maxActions: flags.actions,
|
|
1110
|
+
timeout: flags.timeout,
|
|
1111
|
+
testEmail: flags.email,
|
|
1112
|
+
testPassword: flags.password,
|
|
1113
|
+
baselineFindings,
|
|
1114
|
+
surface: "cli",
|
|
1115
|
+
onProgress,
|
|
1116
|
+
})
|
|
1095
1117
|
: await engine.runQaIos({
|
|
1096
1118
|
bundleId,
|
|
1097
1119
|
maxActions: flags.actions,
|
|
@@ -1495,7 +1517,7 @@ switch (command) {
|
|
|
1495
1517
|
process.exit(2);
|
|
1496
1518
|
}
|
|
1497
1519
|
const platform = String(flags.platform || flow.platform || (flow.url || /^https?:\/\//i.test(flow.app || "") ? "web" : "ios")).toLowerCase();
|
|
1498
|
-
if (!
|
|
1520
|
+
if (!DRIVEN_PLATFORMS.includes(platform)) {
|
|
1499
1521
|
console.error(`❌ Unsupported Flow platform: ${platform}`);
|
|
1500
1522
|
process.exit(2);
|
|
1501
1523
|
}
|
|
@@ -1578,6 +1600,11 @@ switch (command) {
|
|
|
1578
1600
|
} else if (platform === "android") {
|
|
1579
1601
|
const target = androidTarget(flags, typeof flags["app-id"] === "string" ? flags["app-id"] : flow.app || "");
|
|
1580
1602
|
invocation = [process.execPath, [path.join(packageRoot, "scripts", "run-android-flow.js"), absolute, target.appId, target.apkPath || "", target.serial || ""]];
|
|
1603
|
+
} else if (platform === "macos") {
|
|
1604
|
+
requireMacFor("macOS Flow replay");
|
|
1605
|
+
const app = typeof flags.app === "string" ? flags.app : flow.app || "";
|
|
1606
|
+
if (!app) { console.error("❌ A macOS Flow needs `app:` with the path to the application, or --app"); process.exit(2); }
|
|
1607
|
+
invocation = [process.execPath, [path.join(packageRoot, "scripts", "run-macos-flow.js"), absolute, app]];
|
|
1581
1608
|
} else {
|
|
1582
1609
|
requireMacFor("iOS Flow replay");
|
|
1583
1610
|
invocation = ["bash", [path.join(packageRoot, "scripts", "run-flow.sh"), absolute, typeof flags["bundle-id"] === "string" ? flags["bundle-id"] : flow.app || ""]];
|
|
@@ -1897,7 +1924,7 @@ switch (command) {
|
|
|
1897
1924
|
const { flags: doctorFlags } = parseVerbArgs(rest);
|
|
1898
1925
|
const jsonMode = doctorFlags.json === true;
|
|
1899
1926
|
const report = { version: pkg.version, healthy: true, node: {}, python3: {}, disk: {},
|
|
1900
|
-
platforms: { ios: {}, android: {}, web: {} }, home: tappHome };
|
|
1927
|
+
platforms: { ios: {}, macos: {}, android: {}, web: {} }, home: tappHome };
|
|
1901
1928
|
const say = (line) => { if (!jsonMode) console.log(line); };
|
|
1902
1929
|
const sayOk = (label, detail = "") => { if (!jsonMode) ok(label, detail); };
|
|
1903
1930
|
const sayBad = (label, detail = "") => { if (!jsonMode) bad(label, detail); };
|
|
@@ -1948,6 +1975,24 @@ switch (command) {
|
|
|
1948
1975
|
say(` ⬜ iOS — requires macOS (this host: ${process.platform})`);
|
|
1949
1976
|
}
|
|
1950
1977
|
|
|
1978
|
+
// macOS desktop applications. The driver is the Accessibility API, which needs a one-time
|
|
1979
|
+
// permission nothing can grant for you — so report the permission, not just the platform.
|
|
1980
|
+
if (process.platform === "darwin") {
|
|
1981
|
+
try {
|
|
1982
|
+
const { macAccessibilityTrusted, ACCESSIBILITY_REMEDIATION } = await import(path.join(packageRoot, "mcp-server", "src", "macos-driver.js"));
|
|
1983
|
+
const trusted = macAccessibilityTrusted({ home: tappHome });
|
|
1984
|
+
report.platforms.macos = { available: trusted, accessibility: trusted, ...(trusted ? {} : { reason: "Accessibility permission not granted" }) };
|
|
1985
|
+
if (trusted) sayOk("macOS apps", "Accessibility permission granted");
|
|
1986
|
+
else say(` ⬜ macOS apps — ${ACCESSIBILITY_REMEDIATION}`);
|
|
1987
|
+
} catch (error) {
|
|
1988
|
+
report.platforms.macos = { available: false, reason: String(error.message || error).slice(0, 160) };
|
|
1989
|
+
say(` ⬜ macOS apps — ${String(error.message || error).slice(0, 120)}`);
|
|
1990
|
+
}
|
|
1991
|
+
} else {
|
|
1992
|
+
report.platforms.macos = { available: false, reason: `requires macOS (this host: ${process.platform})` };
|
|
1993
|
+
say(` ⬜ macOS apps — requires macOS (this host: ${process.platform})`);
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1951
1996
|
const { resolveAdbPath, resolveAndroidSdkRoot } = await import(path.join(packageRoot, "mcp-server", "src", "android-driver.js"));
|
|
1952
1997
|
const adbPath = resolveAdbPath();
|
|
1953
1998
|
const adb = adbPath ? run(adbPath, ["devices"]) : { code: 1, stdout: "" };
|
|
@@ -6,10 +6,10 @@ export const customerProductContract = Object.freeze({
|
|
|
6
6
|
schemaVersion: 2,
|
|
7
7
|
product: "Tapp",
|
|
8
8
|
interface: "customer-browser",
|
|
9
|
-
// What tapp has a driver for.
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
targetPlatforms: ["ios", "android", "web"],
|
|
9
|
+
// What tapp has a driver for. Windows desktop applications are shown in the Studio's
|
|
10
|
+
// Platforms view as having no driver yet — declared honestly, never counted here, because
|
|
11
|
+
// this list is what the engine can actually drive (ADR-0010).
|
|
12
|
+
targetPlatforms: ["ios", "android", "web", "macos"],
|
|
13
13
|
// A repository is opened by path (`tapp app /path/to/repo`); a website by URL in the Studio.
|
|
14
14
|
repositorySources: ["local-path", "github"],
|
|
15
15
|
entryLayers: ["repository", "website"],
|
|
@@ -25,6 +25,7 @@ import { oauthProviders, oauthAuthorizeUrl, oauthEmailFromCode, isOauthProvider
|
|
|
25
25
|
import { journeyFromCapture, JourneyStore, slugify } from "./journeys.js";
|
|
26
26
|
import { AlertStore, alertForChange, alertMessage, deliverAlert } from "./alerts.js";
|
|
27
27
|
import { platformStates, selfHostAnswer, PLATFORM_TARGETS, hostToolchain } from "./platforms.js";
|
|
28
|
+
import { isMacosAppBundle } from "./macos-driver.js";
|
|
28
29
|
|
|
29
30
|
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
|
30
31
|
const assetRoot = path.join(packageRoot, "browser");
|
|
@@ -1474,14 +1475,20 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
1474
1475
|
return;
|
|
1475
1476
|
}
|
|
1476
1477
|
const prompt = classifyPrompt(body.input);
|
|
1477
|
-
if (!["bundle", "app", "apk"].includes(prompt.kind)) throw Object.assign(new Error("Give a bundle id (com.company.app), a
|
|
1478
|
+
if (!["bundle", "app", "apk"].includes(prompt.kind)) throw Object.assign(new Error("Give a bundle id (com.company.app), a .app (macOS or simulator), or an .apk"), { statusCode: 400 });
|
|
1478
1479
|
const job = startJob(operation, async (progress) => {
|
|
1479
1480
|
const engine = await import("./index.js");
|
|
1480
|
-
|
|
1481
|
+
// A .app is either a macOS application or an iOS simulator build; the difference is
|
|
1482
|
+
// whether its executable lives in Contents/MacOS (mcp-server/src/macos-driver.js).
|
|
1483
|
+
const macosBundle = prompt.kind === "app" && isMacosAppBundle(prompt.value);
|
|
1484
|
+
job.platform = prompt.kind === "apk" ? "android" : macosBundle ? "macos" : "ios";
|
|
1481
1485
|
job.liveSimulator = job.platform === "ios";
|
|
1482
1486
|
const forward = (entry) => progress({ phase: "explore", text: entry.narrative || `${entry.action || 0}/${entry.max || 0} actions · ${entry.states || 0} states`, ...(entry.action ? { current: entry.action, total: entry.max } : {}), ...(entry.screen ? { screen: entry.screen } : {}), ...(entry.screenshot ? { screenshot: entry.screenshot } : {}) });
|
|
1483
1487
|
let result;
|
|
1484
|
-
if (
|
|
1488
|
+
if (macosBundle) {
|
|
1489
|
+
progress({ phase: "runtime", text: `Launching ${path.basename(prompt.value)}` });
|
|
1490
|
+
result = await engine.runQaMacos({ appPath: prompt.value, maxActions: Number(body.maxActions) || 40, timeout: Number(body.timeout) || 600, onProgress: forward });
|
|
1491
|
+
} else if (prompt.kind === "apk") {
|
|
1485
1492
|
progress({ phase: "runtime", text: `Installing ${path.basename(prompt.value)} on the connected Android device` });
|
|
1486
1493
|
result = await engine.runQaAndroid({ apkPath: prompt.value, appId: String(body.appId || ""), maxActions: Number(body.maxActions) || 40, timeout: Number(body.timeout) || 600, onProgress: forward });
|
|
1487
1494
|
} else {
|
package/mcp-server/src/index.js
CHANGED
|
@@ -2094,6 +2094,60 @@ export async function runQaAndroid({ appId, apkPath, serial, maxActions, timeout
|
|
|
2094
2094
|
return { structured, text };
|
|
2095
2095
|
}
|
|
2096
2096
|
|
|
2097
|
+
/**
|
|
2098
|
+
* Explore a macOS desktop application. The shape mirrors runQaAndroid exactly, because the
|
|
2099
|
+
* marker contract is the same and everything downstream — report.js, the UI Map, the HTML
|
|
2100
|
+
* report, journeys, the gate — is platform-agnostic by design.
|
|
2101
|
+
*/
|
|
2102
|
+
export async function runQaMacos({ appPath, maxActions, timeout, testEmail, testPassword, baselineFindings, surface = "mcp", onProgress = () => {} }) {
|
|
2103
|
+
if (process.platform !== "darwin") {
|
|
2104
|
+
return { error: "macOS applications can only be driven on macOS. Use a Mac, or have tapp run it for you." };
|
|
2105
|
+
}
|
|
2106
|
+
const { storagePreflight } = await import("./environment-preflight.js");
|
|
2107
|
+
const storage = storagePreflight(capturesDir);
|
|
2108
|
+
if (!storage.ok) return { error: storage.message, details: { environment: "storage", storage } };
|
|
2109
|
+
const resolved = path.resolve(String(appPath || "").trim());
|
|
2110
|
+
if (!fs.existsSync(resolved)) return { error: `No application at ${resolved}` };
|
|
2111
|
+
const label = path.basename(resolved, ".app");
|
|
2112
|
+
const actions = Math.max(1, Math.min(1000, asInteger(maxActions, 40)));
|
|
2113
|
+
const timeoutSec = Math.max(30, Math.min(3600, asInteger(timeout, 600)));
|
|
2114
|
+
const id = "macos-" + new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14).replace(/^(\d{8})/, "$1-");
|
|
2115
|
+
const outDir = path.join(capturesDir, id);
|
|
2116
|
+
const provenance = writeCaptureProvenance(outDir, { kind: "explore", platform: "macos", target: resolved, projectDir: workspaceRoot });
|
|
2117
|
+
let macResult;
|
|
2118
|
+
try {
|
|
2119
|
+
const { exploreMacos } = await import("./macos-explorer.js");
|
|
2120
|
+
macResult = await exploreMacos({
|
|
2121
|
+
appPath: resolved,
|
|
2122
|
+
maxActions: actions,
|
|
2123
|
+
timeoutSec,
|
|
2124
|
+
outDir,
|
|
2125
|
+
testEmail: isNonEmptyString(testEmail) ? testEmail.trim() : "",
|
|
2126
|
+
testPassword: isNonEmptyString(testPassword) ? testPassword : "",
|
|
2127
|
+
onProgress,
|
|
2128
|
+
});
|
|
2129
|
+
} catch (error) {
|
|
2130
|
+
return { error: error.message || String(error), details: { capture: { id, path: outDir } } };
|
|
2131
|
+
}
|
|
2132
|
+
const report = buildQaReport(macResult.markersPath, { platform: "macos", target: resolved });
|
|
2133
|
+
if (!report) return { error: "macOS exploration produced no markers", details: { capture: { id, path: outDir } } };
|
|
2134
|
+
const backend = remoteAiOptedIn() ? resolveModelBackend() : null;
|
|
2135
|
+
if (backend && report.findings.length) {
|
|
2136
|
+
const { enrichFindings } = await import("./enrich.js");
|
|
2137
|
+
await enrichFindings(report.findings, { backend, callModel, screens: report.screens, appLabel: label });
|
|
2138
|
+
}
|
|
2139
|
+
const regression = computeRegression(report.findings, baselineFindings);
|
|
2140
|
+
const uiMap = await writeRunUiMap({ markersPath: macResult.markersPath, platform: "macos", target: resolved, runId: id, outDir });
|
|
2141
|
+
let reportHtml = null;
|
|
2142
|
+
try {
|
|
2143
|
+
const { writeHtmlReport } = await import("./html-report.js");
|
|
2144
|
+
reportHtml = writeHtmlReport(outDir, { report, label });
|
|
2145
|
+
} catch {}
|
|
2146
|
+
const structured = { ...report, regression, platform: "macos", uiMap, reportHtml, capture: { id, path: outDir, relativePath: path.relative(repoRoot, outDir), provenance } };
|
|
2147
|
+
const text = formatQaReport(report, { regression, bundleId: label, aiConfigured: !!backend, reportHtml, uiMap: uiMap.error ? null : uiMap, surface });
|
|
2148
|
+
return { structured, text };
|
|
2149
|
+
}
|
|
2150
|
+
|
|
2097
2151
|
export async function runQaIos({ bundleId, maxActions, timeout, args = {}, device = "", surface = "mcp", onProgress = () => {} }) {
|
|
2098
2152
|
const { storagePreflight } = await import("./environment-preflight.js");
|
|
2099
2153
|
const storage = storagePreflight(capturesDir);
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// Driving a macOS application, the same way tapp drives an Android device.
|
|
2
|
+
//
|
|
3
|
+
// Android is `adb` plus a UIAutomator dump; macOS is the Accessibility API plus a small Swift
|
|
4
|
+
// helper (MacHarness/tapp-mac-ax.swift), compiled once and cached. Neither needs the application
|
|
5
|
+
// under test to be rebuilt, re-signed or linked against anything.
|
|
6
|
+
//
|
|
7
|
+
// Two things make macOS different from every other target tapp drives, and both shape this file.
|
|
8
|
+
//
|
|
9
|
+
// 1. Element paths are not stable. An application re-lays out its accessibility tree as its state
|
|
10
|
+
// changes, so a path read a moment ago can address a different control or nothing at all.
|
|
11
|
+
// Every action therefore takes a FRESH snapshot and resolves its target by label on that
|
|
12
|
+
// snapshot — never by a remembered path. (Measured on Calculator: pressing four buttons in a
|
|
13
|
+
// row with paths from one snapshot pressed the wrong ones.)
|
|
14
|
+
//
|
|
15
|
+
// 2. This is the person's real machine. There is no simulator and no sandbox: a stray press lands
|
|
16
|
+
// on their actual Finder, their actual documents, their actual session. So the driver refuses
|
|
17
|
+
// destructive controls itself, rather than trusting whatever is choosing targets to be
|
|
18
|
+
// careful. An explorer bug must not be able to log somebody out.
|
|
19
|
+
import fs from "node:fs";
|
|
20
|
+
import os from "node:os";
|
|
21
|
+
import path from "node:path";
|
|
22
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
23
|
+
import { fileURLToPath } from "node:url";
|
|
24
|
+
|
|
25
|
+
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Controls tapp will not press on a desktop, however it was asked. The cost of a false positive
|
|
29
|
+
* is a control left alone; the cost of a false negative is somebody's session, their files, or
|
|
30
|
+
* their machine. The list is matched against the whole label, case-insensitively.
|
|
31
|
+
*/
|
|
32
|
+
export const DESTRUCTIVE_CONTROL = /\b(shut ?down|restart|log ?out|sign ?out|sleep|erase|empty trash|move to trash|delete|uninstall|deactivate|format|wipe|reset|revoke|remove|discard|destroy|force quit|quit)\b/i;
|
|
33
|
+
|
|
34
|
+
/** System chrome that belongs to macOS, not to the application under test. */
|
|
35
|
+
export const SYSTEM_MENU_TITLES = new Set(["Apple", "Services", "Window", "Help"]);
|
|
36
|
+
|
|
37
|
+
const MAC_ROLE_KIND = {
|
|
38
|
+
AXButton: "button", AXMenuItem: "menuItem", AXMenuBarItem: "menu", AXPopUpButton: "button",
|
|
39
|
+
AXCheckBox: "checkbox", AXRadioButton: "radio", AXTextField: "field", AXTextArea: "field",
|
|
40
|
+
AXSecureTextField: "secureField", AXSlider: "slider", AXLink: "link", AXTabGroup: "tabs",
|
|
41
|
+
AXStaticText: "text", AXImage: "image", AXRow: "row", AXCell: "cell", AXDisclosureTriangle: "disclosure",
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/** Where the compiled helper lives. Built on first use, like the iOS harness. */
|
|
45
|
+
export function macAxHelperPath(home = process.env.TAPP_HOME || path.join(os.homedir(), ".tapp")) {
|
|
46
|
+
return path.join(home, "bin", "tapp-mac-ax");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function macAxSourcePath() {
|
|
50
|
+
return path.join(packageRoot, "MacHarness", "tapp-mac-ax.swift");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Compile the helper if it is missing or older than its source. ~3s once; after that it is a
|
|
55
|
+
* cached binary and the driver is as quick as adb.
|
|
56
|
+
*/
|
|
57
|
+
export function ensureMacAxHelper({ home = process.env.TAPP_HOME || path.join(os.homedir(), ".tapp"), rebuild = false } = {}) {
|
|
58
|
+
if (process.platform !== "darwin") throw new Error("macOS applications can only be driven on macOS.");
|
|
59
|
+
const source = macAxSourcePath();
|
|
60
|
+
if (!fs.existsSync(source)) throw new Error(`The macOS helper source is missing: ${source}`);
|
|
61
|
+
const binary = macAxHelperPath(home);
|
|
62
|
+
const fresh = !rebuild && fs.existsSync(binary) && fs.statSync(binary).mtimeMs >= fs.statSync(source).mtimeMs;
|
|
63
|
+
if (fresh) return binary;
|
|
64
|
+
fs.mkdirSync(path.dirname(binary), { recursive: true });
|
|
65
|
+
const built = spawnSync("swiftc", ["-O", source, "-o", binary], { encoding: "utf8" });
|
|
66
|
+
if (built.status !== 0) {
|
|
67
|
+
throw new Error(`Could not build the macOS helper. Is Xcode or the Command Line Tools installed? ${String(built.stderr || built.error?.message || "").trim().slice(0, 300)}`);
|
|
68
|
+
}
|
|
69
|
+
return binary;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function runHelper(binary, args, { timeoutMs = 30_000 } = {}) {
|
|
73
|
+
const result = spawnSync(binary, args, { encoding: "utf8", timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 });
|
|
74
|
+
if (result.error) throw new Error(`The macOS helper did not run: ${result.error.message}`);
|
|
75
|
+
const text = String(result.stdout || "").trim();
|
|
76
|
+
if (result.status !== 0) {
|
|
77
|
+
let detail = String(result.stderr || "").trim();
|
|
78
|
+
try { detail = JSON.parse(detail).error || detail; } catch { /* plain text is fine */ }
|
|
79
|
+
throw new Error(detail || `The macOS helper exited ${result.status}`);
|
|
80
|
+
}
|
|
81
|
+
try { return JSON.parse(text); } catch { throw new Error(`The macOS helper answered something that is not JSON: ${text.slice(0, 200)}`); }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Has the person granted Accessibility to whatever is running tapp? Nothing works without it. */
|
|
85
|
+
export function macAccessibilityTrusted({ home } = {}) {
|
|
86
|
+
try { return Boolean(runHelper(ensureMacAxHelper({ home }), ["trusted"], { timeoutMs: 10_000 }).trusted); }
|
|
87
|
+
catch { return false; }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const ACCESSIBILITY_REMEDIATION =
|
|
91
|
+
"Grant Accessibility to whatever runs tapp: System Settings → Privacy & Security → Accessibility, then add your terminal (or the tapp app) and switch it on. macOS has no way for a program to grant this to itself.";
|
|
92
|
+
|
|
93
|
+
/** One flat, tapp-shaped control list out of the nested accessibility tree. */
|
|
94
|
+
export function normalizeMacElements(root, { includeSystemMenus = false } = {}) {
|
|
95
|
+
const elements = [];
|
|
96
|
+
const visit = (node, insideMenuBar, menuOwner) => {
|
|
97
|
+
if (!node) return;
|
|
98
|
+
const role = String(node.role || "");
|
|
99
|
+
// The menu bar carries the Apple menu and the system items; they are macOS, not the
|
|
100
|
+
// application, and nothing good comes of a crawler in there.
|
|
101
|
+
if (role === "AXMenuBarItem") {
|
|
102
|
+
const owner = String(node.title || "");
|
|
103
|
+
if (!includeSystemMenus && SYSTEM_MENU_TITLES.has(owner)) return;
|
|
104
|
+
for (const child of node.children || []) visit(child, true, owner);
|
|
105
|
+
elements.push(shape(node, true, owner));
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
elements.push(shape(node, insideMenuBar, menuOwner));
|
|
109
|
+
for (const child of node.children || []) visit(child, insideMenuBar, menuOwner);
|
|
110
|
+
};
|
|
111
|
+
const shape = (node, inMenu, menuOwner) => {
|
|
112
|
+
const role = String(node.role || "");
|
|
113
|
+
const label = String(node.title || node.desc || node.identifier || "").trim();
|
|
114
|
+
const value = String(node.value || "").trim();
|
|
115
|
+
const actions = Array.isArray(node.actions) ? node.actions : [];
|
|
116
|
+
const [x = 0, y = 0, width = 0, height = 0] = Array.isArray(node.frame) ? node.frame : [];
|
|
117
|
+
return {
|
|
118
|
+
path: String(node.path || ""),
|
|
119
|
+
type: role,
|
|
120
|
+
kind: MAC_ROLE_KIND[role] || "other",
|
|
121
|
+
role: MAC_ROLE_KIND[role] || "other",
|
|
122
|
+
id: String(node.identifier || ""),
|
|
123
|
+
label: label || value,
|
|
124
|
+
value,
|
|
125
|
+
secure: role === "AXSecureTextField",
|
|
126
|
+
enabled: node.enabled !== false,
|
|
127
|
+
// A control with no press action and no size is scenery.
|
|
128
|
+
clickable: actions.includes("AXPress") && node.enabled !== false && (inMenu || (width > 0 && height > 0)),
|
|
129
|
+
hittable: inMenu || (width > 0 && height > 0),
|
|
130
|
+
inMenu: Boolean(inMenu),
|
|
131
|
+
menu: menuOwner || "",
|
|
132
|
+
frame: [x, y, width, height],
|
|
133
|
+
destructive: DESTRUCTIVE_CONTROL.test(label || value),
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
visit(root, false, "");
|
|
137
|
+
return elements;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Everything tapp is willing to press here, best first. */
|
|
141
|
+
export function macActionableElements(elements) {
|
|
142
|
+
return elements.filter((element) => element.clickable && element.label && !element.destructive);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export class MacosDriver {
|
|
146
|
+
constructor({ home = process.env.TAPP_HOME || path.join(os.homedir(), ".tapp"), pid = null } = {}) {
|
|
147
|
+
this.home = home;
|
|
148
|
+
this.binary = ensureMacAxHelper({ home });
|
|
149
|
+
this.pid = pid;
|
|
150
|
+
this.appName = "";
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Start the application (or attach to it if it is already running) and wait for a window. */
|
|
154
|
+
launch(appPath, { settleMs = 1200 } = {}) {
|
|
155
|
+
const started = runHelper(this.binary, ["launch", "--app", appPath], { timeoutMs: 45_000 });
|
|
156
|
+
this.pid = started.pid;
|
|
157
|
+
this.appName = started.name || "";
|
|
158
|
+
this.bundleId = started.bundleId || "";
|
|
159
|
+
spawnSync("sleep", [String(Math.max(0.2, settleMs / 1000))]);
|
|
160
|
+
return started;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
requirePid() {
|
|
164
|
+
if (!this.pid) throw new Error("No application is attached; launch one first.");
|
|
165
|
+
return String(this.pid);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** A fresh snapshot. Everything else in this class takes one of these, never a stale path. */
|
|
169
|
+
settle({ maxNodes = 2500, maxDepth = 28, includeSystemMenus = false } = {}) {
|
|
170
|
+
const tree = runHelper(this.binary, ["tree", "--pid", this.requirePid(), "--max-nodes", String(maxNodes), "--max-depth", String(maxDepth)]);
|
|
171
|
+
const elements = normalizeMacElements(tree.root, { includeSystemMenus });
|
|
172
|
+
return {
|
|
173
|
+
platform: "macos",
|
|
174
|
+
app: tree.app || this.appName,
|
|
175
|
+
// The window title names the screen, the way a visible h1 names a web page.
|
|
176
|
+
screen: tree.window || tree.app || this.appName,
|
|
177
|
+
truncated: Boolean(tree.truncated),
|
|
178
|
+
nodeCount: tree.nodes || elements.length,
|
|
179
|
+
elements,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Resolve a semantic target against THIS snapshot. Never against a remembered one. */
|
|
184
|
+
find(target, snap) {
|
|
185
|
+
const wanted = String(target || "").trim().toLowerCase();
|
|
186
|
+
if (!wanted) return null;
|
|
187
|
+
const candidates = snap.elements.filter((element) => element.hittable && element.enabled);
|
|
188
|
+
return candidates.find((element) => element.id && element.id.toLowerCase() === wanted)
|
|
189
|
+
|| candidates.find((element) => element.label.toLowerCase() === wanted)
|
|
190
|
+
|| candidates.find((element) => element.label.toLowerCase().startsWith(wanted))
|
|
191
|
+
|| candidates.find((element) => element.label.toLowerCase().includes(wanted))
|
|
192
|
+
|| null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
tap(target, snap) {
|
|
196
|
+
const element = this.find(target, snap);
|
|
197
|
+
if (!element) return { status: "not_found", detail: `No control named ‘${target}’` };
|
|
198
|
+
// The refusal lives here, not only in whatever chose the target: this runs against the
|
|
199
|
+
// person's real machine and an explorer bug must not be able to log them out.
|
|
200
|
+
if (element.destructive) return { status: "refused", detail: `tapp does not press ‘${element.label}’ on a real machine` };
|
|
201
|
+
if (!element.clickable) return { status: "not_actionable", detail: `‘${element.label}’ cannot be pressed` };
|
|
202
|
+
try {
|
|
203
|
+
runHelper(this.binary, ["press", "--pid", this.requirePid(), "--path", element.path]);
|
|
204
|
+
return { status: "ok", detail: element.label, element };
|
|
205
|
+
} catch (error) { return { status: "failed", detail: error.message }; }
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
type(target, text, snap) {
|
|
209
|
+
const element = this.find(target, snap);
|
|
210
|
+
if (!element) return { status: "not_found", detail: `No field named ‘${target}’` };
|
|
211
|
+
try {
|
|
212
|
+
runHelper(this.binary, ["setvalue", "--pid", this.requirePid(), "--path", element.path, "--text", String(text ?? "")]);
|
|
213
|
+
return { status: "ok", detail: element.label, element };
|
|
214
|
+
} catch (error) { return { status: "failed", detail: error.message }; }
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
key(name) {
|
|
218
|
+
try { runHelper(this.binary, ["key", "--pid", this.requirePid(), "--key", String(name)]); return { status: "ok", detail: String(name) }; }
|
|
219
|
+
catch (error) { return { status: "failed", detail: error.message }; }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* A picture of the window, if the person has granted Screen Recording. Evidence is better with
|
|
224
|
+
* one and still usable without, so a refusal is reported rather than thrown.
|
|
225
|
+
*/
|
|
226
|
+
screenshot(destination, snap = null) {
|
|
227
|
+
const frame = snap?.elements?.find((element) => element.type === "AXWindow")?.frame;
|
|
228
|
+
const args = ["-x", "-o"];
|
|
229
|
+
if (frame && frame[2] > 0 && frame[3] > 0) args.push("-R", frame.map((value) => Math.round(value)).join(","));
|
|
230
|
+
args.push(destination);
|
|
231
|
+
const shot = spawnSync("screencapture", args, { encoding: "utf8", timeout: 20_000 });
|
|
232
|
+
if (shot.status === 0 && fs.existsSync(destination) && fs.statSync(destination).size > 0) return { status: "ok", path: destination };
|
|
233
|
+
return { status: "unavailable", detail: "screencapture produced nothing — macOS Screen Recording permission is probably not granted" };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
quit() {
|
|
237
|
+
if (!this.pid) return { status: "ok", detail: "nothing to quit" };
|
|
238
|
+
try { runHelper(this.binary, ["quit", "--pid", String(this.pid)], { timeoutMs: 15_000 }); return { status: "ok" }; }
|
|
239
|
+
catch (error) { return { status: "failed", detail: error.message }; }
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Is this .app a macOS application or an iOS simulator build? Both are directories called
|
|
245
|
+
* Something.app, and tapp is given either. A macOS bundle keeps its executable in Contents/MacOS;
|
|
246
|
+
* a simulator build keeps it at the top level and declares an iPhone platform.
|
|
247
|
+
*/
|
|
248
|
+
export function isMacosAppBundle(bundlePath) {
|
|
249
|
+
try {
|
|
250
|
+
if (!/\.app\/?$/.test(bundlePath) || !fs.statSync(bundlePath).isDirectory()) return false;
|
|
251
|
+
return fs.existsSync(path.join(bundlePath, "Contents", "MacOS"));
|
|
252
|
+
} catch { return false; }
|
|
253
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
// Bounded deterministic exploration of a macOS application.
|
|
2
|
+
//
|
|
3
|
+
// It emits the same marker contract as the XCUITest harness and the Android explorer, so
|
|
4
|
+
// report.js, the UI Map, journeys, baselines and the CI gate do not know or care which platform
|
|
5
|
+
// produced the evidence.
|
|
6
|
+
//
|
|
7
|
+
// Two rules are specific to the desktop, and both exist because this is the person's own
|
|
8
|
+
// machine rather than a simulator:
|
|
9
|
+
//
|
|
10
|
+
// • Destructive controls are never pressed. The driver refuses them too; this is the second
|
|
11
|
+
// of the two locks (mcp-server/src/macos-driver.js).
|
|
12
|
+
// • Menu items are INVENTORIED, NOT PRESSED. A desktop menu is where "Quit", "Delete" and
|
|
13
|
+
// "Move to Trash" live, and it is also full of items that open modal file pickers a crawler
|
|
14
|
+
// cannot close. The report says what the menus contain and says plainly that nothing in them
|
|
15
|
+
// was exercised, which is an honest coverage boundary rather than a silent one.
|
|
16
|
+
import fs from "node:fs";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
|
|
19
|
+
import { MacosDriver, macActionableElements } from "./macos-driver.js";
|
|
20
|
+
|
|
21
|
+
const ERROR_RE = /\b(something went wrong|an error occurred|failed to load|unexpected error|could not be completed|unable to)\b/i;
|
|
22
|
+
const AUTH_SUBMIT_RE = /\b(sign[ -]?in|log[ -]?in|continue|submit|unlock)\b/i;
|
|
23
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
24
|
+
|
|
25
|
+
export function macStateHash(snap) {
|
|
26
|
+
return (snap.elements || []).filter((element) => !element.inMenu)
|
|
27
|
+
.map((element) => `${element.type}:${element.id}:${element.label}:${element.value}`).join("|");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function isMacAuthSubmit(element) {
|
|
31
|
+
return AUTH_SUBMIT_RE.test(`${element?.label || ""} ${element?.id || ""}`.replace(/[_-]+/g, " "));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The control inventory a UI Map node wants, for the window only. */
|
|
35
|
+
export function macMapControls(elements) {
|
|
36
|
+
// A disabled button is still part of the screen's inventory — "enabled: false" is a state a
|
|
37
|
+
// UI Map should record, not a reason to omit the control (same as the Android map).
|
|
38
|
+
const PRESSABLE = new Set(["button", "checkbox", "radio", "tabs", "link", "disclosure"]);
|
|
39
|
+
return elements.filter((element) => !element.inMenu && (element.clickable || PRESSABLE.has(element.kind) || element.kind === "field" || element.kind === "secureField"))
|
|
40
|
+
.map((element) => ({
|
|
41
|
+
kind: element.kind === "secureField" ? "secureField" : element.kind === "field" ? "field" : element.kind === "checkbox" || element.kind === "radio" ? "toggle" : "button",
|
|
42
|
+
type: element.type,
|
|
43
|
+
id: element.id || "",
|
|
44
|
+
accessibilityId: element.id || "",
|
|
45
|
+
label: element.label,
|
|
46
|
+
secure: Boolean(element.secure),
|
|
47
|
+
enabled: element.enabled !== false,
|
|
48
|
+
hittable: Boolean(element.hittable),
|
|
49
|
+
}));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A window with nothing in it is a finding, not a successful visit. */
|
|
53
|
+
export function isMacBlankSnapshot(snap) {
|
|
54
|
+
const elements = (snap?.elements || []).filter((element) => !element.inMenu);
|
|
55
|
+
const meaningful = elements.some((element) => String(element.label || "").trim() || String(element.value || "").trim());
|
|
56
|
+
const interactive = elements.some((element) => element.clickable || element.kind === "field");
|
|
57
|
+
return !meaningful && !interactive;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function exploreMacos({
|
|
61
|
+
appPath, maxActions = 40, timeoutSec = 300, outDir,
|
|
62
|
+
testEmail = "", testPassword = "", onProgress = () => {}, driver, home,
|
|
63
|
+
}) {
|
|
64
|
+
const d = driver || new MacosDriver({ home });
|
|
65
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
66
|
+
const screenshots = path.join(outDir, "screenshots");
|
|
67
|
+
fs.mkdirSync(screenshots, { recursive: true });
|
|
68
|
+
const markersPath = path.join(outDir, "ocqa-markers.txt");
|
|
69
|
+
fs.rmSync(markersPath, { force: true });
|
|
70
|
+
const emit = (kind, payload) => fs.appendFileSync(markersPath, `OCQA_${kind}:${JSON.stringify(payload)}\n`);
|
|
71
|
+
|
|
72
|
+
const deadline = Date.now() + timeoutSec * 1000;
|
|
73
|
+
const tried = new Set();
|
|
74
|
+
const visited = new Map();
|
|
75
|
+
let issues = 0;
|
|
76
|
+
let actions = 0;
|
|
77
|
+
let loginTried = false;
|
|
78
|
+
let shotsUnavailable = false;
|
|
79
|
+
|
|
80
|
+
const launched = d.launch(appPath);
|
|
81
|
+
emit("ACTION", { type: "open", target: launched.name || appPath, via: appPath, narrative: `Launched ${launched.name || path.basename(appPath)}` });
|
|
82
|
+
let snap = d.settle();
|
|
83
|
+
|
|
84
|
+
const stillRunning = () => {
|
|
85
|
+
try { process.kill(d.pid, 0); return true; } catch { return false; }
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const recordState = (snapshot) => {
|
|
89
|
+
const hash = macStateHash(snapshot);
|
|
90
|
+
const screen = snapshot.screen || snapshot.app || "Window";
|
|
91
|
+
if (!visited.has(hash)) {
|
|
92
|
+
visited.set(hash, screen);
|
|
93
|
+
const file = path.join(screenshots, `${String(visited.size).padStart(2, "0")}-${screen.replace(/[^a-z0-9]+/gi, "-").toLowerCase().slice(0, 50) || "window"}.png`);
|
|
94
|
+
const shot = d.screenshot(file, snapshot);
|
|
95
|
+
if (shot.status !== "ok") shotsUnavailable = true;
|
|
96
|
+
}
|
|
97
|
+
const inputs = snapshot.elements.filter((element) => element.kind === "field" || element.kind === "secureField")
|
|
98
|
+
.map((element) => ({ key: element.id || element.label, label: element.label, secure: Boolean(element.secure) }));
|
|
99
|
+
emit("STATE", {
|
|
100
|
+
screen, hash, elements: snapshot.elements.length, action: actions,
|
|
101
|
+
role: inputs.some((input) => input.secure) ? "login" : "app",
|
|
102
|
+
inputs, controls: macMapControls(snapshot.elements),
|
|
103
|
+
});
|
|
104
|
+
return { hash, screen, inputs };
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
// Everything in the application's own menus, recorded once as coverage. Nothing here is
|
|
108
|
+
// pressed; see the note at the top of this file.
|
|
109
|
+
const menuInventory = [...new Set(snap.elements.filter((element) => element.inMenu && element.label)
|
|
110
|
+
.map((element) => `${element.menu} › ${element.label}`))].slice(0, 400);
|
|
111
|
+
if (menuInventory.length) emit("COVERAGE", { kind: "menu-items", listed: menuInventory.length, pressed: 0, items: menuInventory });
|
|
112
|
+
|
|
113
|
+
while (actions < maxActions && Date.now() < deadline) {
|
|
114
|
+
if (!stillRunning()) {
|
|
115
|
+
emit("ISSUE", { type: "crash", severity: "critical", title: "The application exited during exploration", screen: visited.size ? [...visited.values()].at(-1) : "Launch", step: actions });
|
|
116
|
+
issues += 1;
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
const { hash, screen, inputs } = recordState(snap);
|
|
120
|
+
onProgress({ action: actions, max: maxActions, states: visited.size });
|
|
121
|
+
|
|
122
|
+
const visibleText = snap.elements.filter((element) => !element.inMenu).map((element) => element.label || element.value).filter(Boolean).join(" ");
|
|
123
|
+
if (ERROR_RE.test(visibleText)) {
|
|
124
|
+
emit("ISSUE", { type: "error_surface", severity: "high", title: "Visible error surface", screen, step: actions });
|
|
125
|
+
issues += 1;
|
|
126
|
+
}
|
|
127
|
+
if (isMacBlankSnapshot(snap)) {
|
|
128
|
+
emit("ISSUE", { type: "blank_screen", severity: "high", title: "No usable controls or content", screen, step: actions });
|
|
129
|
+
issues += 1;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Fill a field before pressing things, so a form is submitted with something in it.
|
|
133
|
+
const unfilled = snap.elements.find((element) => !element.inMenu && (element.kind === "field" || element.kind === "secureField")
|
|
134
|
+
&& element.enabled && !tried.has(`${screen}|input|${element.id || element.label}`));
|
|
135
|
+
if (unfilled) {
|
|
136
|
+
const key = unfilled.id || unfilled.label;
|
|
137
|
+
const lower = `${key} ${unfilled.label}`.toLowerCase();
|
|
138
|
+
const value = unfilled.secure || lower.includes("password") ? (testPassword || "TestPass123!")
|
|
139
|
+
: lower.includes("email") ? (testEmail || "test@example.com") : "Tapp test";
|
|
140
|
+
tried.add(`${screen}|input|${key}`);
|
|
141
|
+
const typed = d.type(key, value, snap);
|
|
142
|
+
actions += 1;
|
|
143
|
+
emit("ACTION", {
|
|
144
|
+
type: "type", target: key, screen, status: typed.status,
|
|
145
|
+
valueSource: unfilled.secure || lower.includes("password") ? "test-password" : lower.includes("email") ? "test-email" : "generated-text",
|
|
146
|
+
reason: "complete_form", step: actions, narrative: `Typed into “${unfilled.label || key}”`,
|
|
147
|
+
});
|
|
148
|
+
snap = d.settle();
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const candidate = macActionableElements(snap.elements)
|
|
153
|
+
.find((element) => !element.inMenu && !tried.has(`${hash}|tap|${element.label}`));
|
|
154
|
+
if (candidate) {
|
|
155
|
+
const target = candidate.label;
|
|
156
|
+
const loginSubmit = inputs.some((input) => input.secure) && isMacAuthSubmit(candidate);
|
|
157
|
+
if (loginSubmit) loginTried = true;
|
|
158
|
+
tried.add(`${hash}|tap|${target}`);
|
|
159
|
+
const pressed = d.tap(target, snap);
|
|
160
|
+
actions += 1;
|
|
161
|
+
await sleep(250);
|
|
162
|
+
snap = d.settle();
|
|
163
|
+
const after = macStateHash(snap);
|
|
164
|
+
emit("ACTION", {
|
|
165
|
+
type: loginSubmit ? "login_submit" : "tap", target, screen, status: pressed.status,
|
|
166
|
+
reason: "untried_control", step: actions, narrative: `Pressed “${target}”`,
|
|
167
|
+
});
|
|
168
|
+
emit("TRANSITION", { from: screen, to: snap.screen, action: target, changed: hash !== after });
|
|
169
|
+
const authFailed = loginSubmit && snap.elements.some((element) => element.secure && !element.inMenu);
|
|
170
|
+
if (pressed.status === "ok" && authFailed) {
|
|
171
|
+
emit("ISSUE", { type: "auth_failed", severity: "high", title: "Sign-in attempt remained on the sign-in window", screen, target, step: actions });
|
|
172
|
+
issues += 1;
|
|
173
|
+
} else if (pressed.status === "ok" && hash === after) {
|
|
174
|
+
emit("ISSUE", { type: "unresponsive_element", severity: "medium", title: `Control did not respond: ${target}`, screen, target, step: actions });
|
|
175
|
+
issues += 1;
|
|
176
|
+
}
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Nothing left here. Escape closes a sheet, a popover or a menu — the desktop's "back".
|
|
181
|
+
const escapeKey = `${hash}|escape`;
|
|
182
|
+
if (!tried.has(escapeKey)) {
|
|
183
|
+
tried.add(escapeKey);
|
|
184
|
+
d.key("escape");
|
|
185
|
+
actions += 1;
|
|
186
|
+
await sleep(250);
|
|
187
|
+
const next = d.settle();
|
|
188
|
+
emit("ACTION", { type: "back", target: "escape", reason: "state_exhausted", step: actions, screen, narrative: "Pressed Escape" });
|
|
189
|
+
emit("TRANSITION", { from: screen, to: next.screen, action: "escape", changed: macStateHash(next) !== hash });
|
|
190
|
+
if (macStateHash(next) !== hash) { snap = next; continue; }
|
|
191
|
+
}
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const timedOut = Date.now() >= deadline;
|
|
196
|
+
emit("COMPLETE", {
|
|
197
|
+
actions, states: visited.size, issues,
|
|
198
|
+
screens: [...new Set(visited.values())].join(","),
|
|
199
|
+
outcome: timedOut ? "timeout" : "complete", timedOut,
|
|
200
|
+
credentialsProvided: Boolean(testEmail || testPassword), credentialsUsed: loginTried,
|
|
201
|
+
// Said out loud, every run: what a desktop run deliberately does not touch.
|
|
202
|
+
notChecked: [
|
|
203
|
+
`${menuInventory.length} menu item(s) were listed but not pressed — a desktop menu holds Quit, Delete and file pickers.`,
|
|
204
|
+
...(shotsUnavailable ? ["Screenshots were unavailable: macOS Screen Recording permission is not granted to whatever runs tapp."] : []),
|
|
205
|
+
],
|
|
206
|
+
...(timedOut ? { timeoutSeconds: timeoutSec } : {}),
|
|
207
|
+
});
|
|
208
|
+
onProgress({ action: actions, max: maxActions, states: visited.size });
|
|
209
|
+
return { markersPath, outDir, actions, states: visited.size, issues, timedOut, menuItems: menuInventory.length, screenshots: !shotsUnavailable };
|
|
210
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Deterministic replay of a Flow against a macOS application.
|
|
2
|
+
//
|
|
3
|
+
// Same vocabulary as every other platform, so a journey kept from a macOS exploration is an
|
|
4
|
+
// ordinary Flow file and the Studio, the scheduler and the agent token all work unchanged.
|
|
5
|
+
// `swipe` is the one step with no sensible desktop meaning; it is skipped and said so, rather
|
|
6
|
+
// than silently passing.
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
|
|
10
|
+
import { MacosDriver } from "./macos-driver.js";
|
|
11
|
+
import { FlowLog, flowVariables, normalizeFlowStep, substituteFlowValue } from "./flow-runtime.js";
|
|
12
|
+
import { chooseSignInSubmit } from "./sign-in.js";
|
|
13
|
+
|
|
14
|
+
const DEFAULT_TIMEOUT = 6000;
|
|
15
|
+
|
|
16
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
17
|
+
|
|
18
|
+
function screenMatches(snap, wanted) {
|
|
19
|
+
return String(snap.screen || "").trim().toLowerCase() === String(wanted || "").trim().toLowerCase();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function waitFor(driver, predicate, timeout) {
|
|
23
|
+
const deadline = Date.now() + timeout;
|
|
24
|
+
let snap = driver.settle();
|
|
25
|
+
while (Date.now() < deadline) {
|
|
26
|
+
if (predicate(snap)) return snap;
|
|
27
|
+
await sleep(200);
|
|
28
|
+
snap = driver.settle();
|
|
29
|
+
}
|
|
30
|
+
return predicate(snap) ? snap : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function runMacosFlow({ flow, appPath, logPath, screenshotDir, driver, home }) {
|
|
34
|
+
const target = appPath || flow.app || flow.url;
|
|
35
|
+
if (!target) throw new Error("A macOS Flow needs `app:` with the path to the application");
|
|
36
|
+
if (logPath) fs.rmSync(logPath, { force: true });
|
|
37
|
+
const d = driver || new MacosDriver({ home });
|
|
38
|
+
d.launch(target);
|
|
39
|
+
let snap = d.settle();
|
|
40
|
+
const log = new FlowLog({ logPath, flow });
|
|
41
|
+
const vars = flowVariables(flow);
|
|
42
|
+
|
|
43
|
+
for (let index = 0; index < flow.steps.length; index += 1) {
|
|
44
|
+
const raw = normalizeFlowStep(flow.steps[index]);
|
|
45
|
+
const action = raw.action;
|
|
46
|
+
const stepTarget = substituteFlowValue(raw.target, vars);
|
|
47
|
+
const value = substituteFlowValue(raw.value, vars);
|
|
48
|
+
const timeout = Number(raw.params.timeoutMs ?? raw.params.timeout) || DEFAULT_TIMEOUT;
|
|
49
|
+
let status = "pass";
|
|
50
|
+
let detail = "";
|
|
51
|
+
try {
|
|
52
|
+
if (action === "tap") {
|
|
53
|
+
const result = d.tap(stepTarget, snap);
|
|
54
|
+
if (result.status !== "ok") throw new Error(result.detail || `could not press ‘${stepTarget}’`);
|
|
55
|
+
} else if (action === "type") {
|
|
56
|
+
const result = d.type(stepTarget, value, snap);
|
|
57
|
+
if (result.status !== "ok") throw new Error(result.detail || `no field ‘${stepTarget}’ to type into`);
|
|
58
|
+
} else if (action === "login") {
|
|
59
|
+
const fields = snap.elements.filter((element) => !element.inMenu && (element.kind === "field" || element.kind === "secureField"));
|
|
60
|
+
const emailField = fields.find((element) => /email|user|account/i.test(`${element.id} ${element.label}`)) || fields.find((element) => !element.secure);
|
|
61
|
+
const passwordField = fields.find((element) => element.secure || /password|passcode/i.test(`${element.id} ${element.label}`));
|
|
62
|
+
if (!emailField || !passwordField) throw new Error("could not identify email and password fields");
|
|
63
|
+
const emailValue = substituteFlowValue(raw.params.email || "$TEST_EMAIL", vars);
|
|
64
|
+
const passwordValue = substituteFlowValue(raw.params.password || "$TEST_PASSWORD", vars);
|
|
65
|
+
const filledEmail = d.type(emailField.id || emailField.label, emailValue, snap);
|
|
66
|
+
if (filledEmail.status !== "ok") throw new Error(filledEmail.detail || "could not fill the email field");
|
|
67
|
+
snap = d.settle();
|
|
68
|
+
const filledPassword = d.type(passwordField.id || passwordField.label, passwordValue, snap);
|
|
69
|
+
if (filledPassword.status !== "ok") throw new Error(filledPassword.detail || "could not fill the password field");
|
|
70
|
+
snap = d.settle();
|
|
71
|
+
// The one sign-in rule, shared with web, Android and the explorer: rule out "Forgot
|
|
72
|
+
// password" and "Continue with Google" by name, prefer a sign-in name, otherwise take
|
|
73
|
+
// the first pressable control after the password field (mcp-server/src/sign-in.js).
|
|
74
|
+
const passwordIndex = snap.elements.findIndex((element) => element.secure);
|
|
75
|
+
const choice = chooseSignInSubmit(snap.elements.map((element, position) => ({
|
|
76
|
+
index: position,
|
|
77
|
+
name: element.label || element.id,
|
|
78
|
+
visible: Boolean(element.clickable) && !element.inMenu,
|
|
79
|
+
disabled: element.enabled === false,
|
|
80
|
+
after: position > passwordIndex,
|
|
81
|
+
})));
|
|
82
|
+
const submit = choice ? snap.elements[choice.index] : null;
|
|
83
|
+
if (!submit) throw new Error("could not identify a sign-in control");
|
|
84
|
+
const pressed = d.tap(submit.label || submit.id, snap);
|
|
85
|
+
if (pressed.status !== "ok") throw new Error(pressed.detail || "could not submit the sign-in form");
|
|
86
|
+
} else if (action === "back") {
|
|
87
|
+
d.key("escape");
|
|
88
|
+
} else if (action === "wait_for") {
|
|
89
|
+
const seen = await waitFor(d, (candidate) => screenMatches(candidate, stepTarget)
|
|
90
|
+
|| candidate.elements.some((element) => `${element.label} ${element.value}`.toLowerCase().includes(String(stepTarget).toLowerCase())), timeout);
|
|
91
|
+
if (!seen) throw new Error(`‘${stepTarget}’ never appeared within ${timeout}ms`);
|
|
92
|
+
snap = seen;
|
|
93
|
+
} else if (action === "wait") {
|
|
94
|
+
await sleep(timeout);
|
|
95
|
+
} else if (action === "assert_screen") {
|
|
96
|
+
const wanted = value || stepTarget;
|
|
97
|
+
const seen = await waitFor(d, (candidate) => screenMatches(candidate, wanted), timeout);
|
|
98
|
+
if (!seen) throw new Error(`expected window ‘${wanted}’, saw ‘${d.settle().screen}’`);
|
|
99
|
+
snap = seen;
|
|
100
|
+
} else if (action === "assert_exists") {
|
|
101
|
+
const seen = await waitFor(d, (candidate) => Boolean(d.find(stepTarget, candidate)), timeout);
|
|
102
|
+
if (!seen) throw new Error(`‘${stepTarget}’ not found`);
|
|
103
|
+
snap = seen;
|
|
104
|
+
} else if (action === "assert_absent") {
|
|
105
|
+
snap = d.settle();
|
|
106
|
+
if (d.find(stepTarget, snap)) throw new Error(`‘${stepTarget}’ was present but should be absent`);
|
|
107
|
+
} else if (action === "assert_text") {
|
|
108
|
+
const of = substituteFlowValue(raw.params.of || stepTarget, vars);
|
|
109
|
+
const needle = substituteFlowValue(raw.params.contains || value, vars);
|
|
110
|
+
snap = d.settle();
|
|
111
|
+
const element = d.find(of, snap);
|
|
112
|
+
if (!element || !`${element.value || element.label}`.toLowerCase().includes(String(needle).toLowerCase())) {
|
|
113
|
+
throw new Error(`‘${of}’ did not contain ‘${needle}’`);
|
|
114
|
+
}
|
|
115
|
+
} else if (action === "swipe") {
|
|
116
|
+
status = "skip";
|
|
117
|
+
detail = "swipe has no meaning on a desktop window";
|
|
118
|
+
} else if (action === "assert_ai") {
|
|
119
|
+
status = "skip";
|
|
120
|
+
detail = "AI assertions are advisory and are not part of deterministic macOS replay";
|
|
121
|
+
} else {
|
|
122
|
+
throw new Error(`unknown action ‘${action}’`);
|
|
123
|
+
}
|
|
124
|
+
if (!["wait_for", "assert_screen", "assert_exists", "assert_absent", "assert_text", "assert_ai", "swipe"].includes(action)) {
|
|
125
|
+
await sleep(200);
|
|
126
|
+
snap = d.settle();
|
|
127
|
+
}
|
|
128
|
+
} catch (error) {
|
|
129
|
+
status = "fail";
|
|
130
|
+
detail = error.message || String(error);
|
|
131
|
+
if (screenshotDir) d.screenshot(path.join(screenshotDir, `flow-failure-${index + 1}.png`), snap);
|
|
132
|
+
}
|
|
133
|
+
log.step({ index: index + 1, action, target: action === "login" ? "sign-in form" : stepTarget || value, status, detail, task: raw.task });
|
|
134
|
+
if (status === "fail" && !flow.continueOnFailure) break;
|
|
135
|
+
}
|
|
136
|
+
if (screenshotDir) d.screenshot(path.join(screenshotDir, "flow-final.png"), snap);
|
|
137
|
+
return log.finish();
|
|
138
|
+
}
|
|
@@ -16,6 +16,7 @@ import fs from "node:fs";
|
|
|
16
16
|
import path from "node:path";
|
|
17
17
|
|
|
18
18
|
import { resolveAdbPath } from "./android-driver.js";
|
|
19
|
+
import { macAccessibilityTrusted } from "./macos-driver.js";
|
|
19
20
|
|
|
20
21
|
/**
|
|
21
22
|
* The states a platform can be in, worst-named-first so nobody mistakes one for another:
|
|
@@ -47,7 +48,7 @@ export const PLATFORM_TARGETS = Object.freeze([
|
|
|
47
48
|
},
|
|
48
49
|
{
|
|
49
50
|
id: "macos", label: "macOS app", give: "A .app on your Mac",
|
|
50
|
-
driver:
|
|
51
|
+
driver: "accessibility", needs: "macOS, and the Accessibility permission",
|
|
51
52
|
machine: "a Mac",
|
|
52
53
|
},
|
|
53
54
|
{
|
|
@@ -73,6 +74,10 @@ export function hostToolchain({ env = process.env, platform = process.platform }
|
|
|
73
74
|
// cask with ANDROID_HOME unset, and the Studio must not say "no Android" about a machine
|
|
74
75
|
// where `tapp explore` would happily find adb.
|
|
75
76
|
android: platform === "linux" || platform === "darwin" || platform === "win32" ? Boolean(resolveAdbPath(env)) : false,
|
|
77
|
+
// Driven through the Accessibility API, which needs a permission nothing can grant for
|
|
78
|
+
// itself. A Mac without it is not ready, and saying otherwise would promise a run that
|
|
79
|
+
// fails on its first action.
|
|
80
|
+
macos: platform === "darwin" && macAccessibilityTrusted(),
|
|
76
81
|
// Chromium is fetched on demand, so web is reachable from any host; whether this particular
|
|
77
82
|
// one has it unpacked is checked when the run starts, which is where the error belongs.
|
|
78
83
|
web: true,
|
|
@@ -91,14 +96,15 @@ export const SELF_HOST_COMMAND = "npx -y @aarwitz/tapp@latest app";
|
|
|
91
96
|
export function platformStates({ hosted = false, env = process.env, platform = process.platform, toolchain = null } = {}) {
|
|
92
97
|
const has = toolchain || hostToolchain({ env, platform });
|
|
93
98
|
return PLATFORM_TARGETS.map((target) => {
|
|
94
|
-
// No driver is no driver, on any host
|
|
95
|
-
//
|
|
99
|
+
// No driver is no driver, on any host — so this must not read as "buy a Mac and it works".
|
|
100
|
+
// But the machine still matters: when the driver lands, running it locally will need one,
|
|
101
|
+
// and somebody deciding today should know which. State both, and the way round it.
|
|
96
102
|
if (!target.driver) {
|
|
97
103
|
return {
|
|
98
104
|
...target,
|
|
99
|
-
state: "pilot",
|
|
100
|
-
summary: `tapp has no ${target.label} driver yet.`,
|
|
101
|
-
how: `
|
|
105
|
+
state: "pilot", because: "no-driver",
|
|
106
|
+
summary: `tapp has no ${target.label} driver yet — it is being built.`,
|
|
107
|
+
how: `Running ${lower(target.label)}s locally will need ${target.machine}. Until the driver lands we do these runs with you: tell us about your app, or have tapp run it for you.`,
|
|
102
108
|
command: "",
|
|
103
109
|
};
|
|
104
110
|
}
|
|
@@ -122,9 +128,9 @@ export function platformStates({ hosted = false, env = process.env, platform = p
|
|
|
122
128
|
summary: because === "not-exposed"
|
|
123
129
|
? `tapp drives ${target.label}, and this machine could — but a public Studio only starts website runs.`
|
|
124
130
|
: `tapp drives ${target.label}, but this Studio is not on ${target.machine}.`,
|
|
125
|
-
//
|
|
126
|
-
//
|
|
127
|
-
how: `Run this Studio on ${target.machine} and give it ${lower(target.give)} there
|
|
131
|
+
// Two ways out, always both: self-host is the same product without the hosting (ADR-0006),
|
|
132
|
+
// and not everyone has the machine or wants to keep it awake.
|
|
133
|
+
how: `Run this Studio on ${target.machine} and give it ${lower(target.give)} there — or have tapp run it for you.`,
|
|
128
134
|
command: SELF_HOST_COMMAND,
|
|
129
135
|
};
|
|
130
136
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aarwitz/tapp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.35.0",
|
|
4
4
|
"mcpName": "io.github.aarwitz/tapp",
|
|
5
5
|
"description": "Let coding agents verify UI changes on real iOS, Android, and web surfaces, then enforce reviewed proof in deterministic CI.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -40,6 +40,7 @@
|
|
|
40
40
|
"scripts/platform-gate.js",
|
|
41
41
|
"scripts/pr-plan.js",
|
|
42
42
|
"scripts/quick-capture.sh",
|
|
43
|
+
"scripts/run-macos-flow.js",
|
|
43
44
|
"scripts/run-android-flow.js",
|
|
44
45
|
"scripts/run-flow.sh",
|
|
45
46
|
"scripts/run-web-flow.js",
|
|
@@ -48,6 +49,7 @@
|
|
|
48
49
|
"Harness/OCQAHarnessUITests/",
|
|
49
50
|
"Harness/OCQAHarness.xcodeproj/",
|
|
50
51
|
"Harness/generate-harness-xcodeproj.rb",
|
|
52
|
+
"MacHarness/",
|
|
51
53
|
"skills/",
|
|
52
54
|
".claude-plugin/",
|
|
53
55
|
"AGENTS.md"
|
|
@@ -96,7 +98,7 @@
|
|
|
96
98
|
"mobile"
|
|
97
99
|
],
|
|
98
100
|
"scripts": {
|
|
99
|
-
"test": "node --test tests/report.test.js tests/regression.test.js tests/engine.test.js tests/project-config.test.js tests/application-model.test.js tests/ui-map.test.js tests/focused-navigation.test.js tests/task-runtime.test.js tests/release-contract.test.js tests/pr-selection.test.js tests/flow-runtime.test.js tests/web-explorer.test.js tests/web-session.test.js tests/web-link-audit.test.js tests/web-overlay.test.js tests/web-audit.test.js tests/page-observations.test.js tests/capture-provenance.test.js tests/capture-frames.test.js tests/actor-store.test.js tests/account-store.test.js tests/alerts.test.js tests/access-jwt.test.js tests/oauth.test.js tests/studio-client.test.js tests/journeys.test.js tests/ios-crash-attribution.test.js tests/ios-simulator-selection.test.js tests/ios-recording-stop.test.js tests/web-flow.test.js tests/sign-in.test.js tests/scenario-runtime.test.js tests/android-driver.test.js tests/android-explorer.test.js tests/android-flow.test.js tests/android-primitives-protocol.test.js tests/managed-web.test.js tests/product-operations.test.js tests/job-lanes.test.js tests/browser-product.test.js tests/browser-chat-narration.test.js tests/browser-onboarding.test.js tests/managed-operation.test.js tests/ci-setup.test.js tests/ci-install.test.js tests/cli.test.js tests/mcp-workspace.test.js tests/action.test.js tests/package-surface.test.js tests/agent-surface.test.js tests/platforms.test.js tests/presentation-contract.test.js tests/landing-brand.test.js tests/ci-gate.test.js tests/ci-report.test.js tests/desktop-protocol.test.js tests/ios-flow-protocol.test.js tests/feedback-triage-0919.test.js vscode-extension/test/bridge.test.js",
|
|
101
|
+
"test": "node --test tests/report.test.js tests/regression.test.js tests/engine.test.js tests/project-config.test.js tests/application-model.test.js tests/ui-map.test.js tests/focused-navigation.test.js tests/task-runtime.test.js tests/release-contract.test.js tests/pr-selection.test.js tests/flow-runtime.test.js tests/web-explorer.test.js tests/web-session.test.js tests/web-link-audit.test.js tests/web-overlay.test.js tests/web-audit.test.js tests/page-observations.test.js tests/capture-provenance.test.js tests/capture-frames.test.js tests/actor-store.test.js tests/account-store.test.js tests/alerts.test.js tests/access-jwt.test.js tests/oauth.test.js tests/studio-client.test.js tests/journeys.test.js tests/ios-crash-attribution.test.js tests/ios-simulator-selection.test.js tests/ios-recording-stop.test.js tests/web-flow.test.js tests/sign-in.test.js tests/scenario-runtime.test.js tests/android-driver.test.js tests/android-explorer.test.js tests/android-flow.test.js tests/macos-driver.test.js tests/android-primitives-protocol.test.js tests/managed-web.test.js tests/product-operations.test.js tests/job-lanes.test.js tests/browser-product.test.js tests/browser-chat-narration.test.js tests/browser-onboarding.test.js tests/managed-operation.test.js tests/ci-setup.test.js tests/ci-install.test.js tests/cli.test.js tests/mcp-workspace.test.js tests/action.test.js tests/package-surface.test.js tests/agent-surface.test.js tests/platforms.test.js tests/presentation-contract.test.js tests/landing-brand.test.js tests/ci-gate.test.js tests/ci-report.test.js tests/desktop-protocol.test.js tests/ios-flow-protocol.test.js tests/feedback-triage-0919.test.js vscode-extension/test/bridge.test.js",
|
|
100
102
|
"test:browser-journey": "node --test tests/browser-journey.test.js",
|
|
101
103
|
"test:browser-native": "TAPP_RUN_NATIVE_BROWSER=1 node --test tests/browser-native-journey.test.js"
|
|
102
104
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Replay a Flow against a macOS application. Mirrors scripts/run-android-flow.js: the platform
|
|
3
|
+
// runner the CLI spawns, so evidence and the log land where every other platform puts them.
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
|
|
7
|
+
import { loadFlowFile } from "../mcp-server/src/flow-runtime.js";
|
|
8
|
+
import { runMacosFlow } from "../mcp-server/src/macos-flow.js";
|
|
9
|
+
|
|
10
|
+
const [, , flowPath, appPath = ""] = process.argv;
|
|
11
|
+
if (!flowPath) {
|
|
12
|
+
console.error("usage: run-macos-flow.js <flow.yml> [/path/to/App.app]");
|
|
13
|
+
process.exit(2);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const evidenceDir = process.env.TAPP_FLOW_EVIDENCE_DIR || "";
|
|
17
|
+
if (evidenceDir) fs.mkdirSync(evidenceDir, { recursive: true });
|
|
18
|
+
|
|
19
|
+
try {
|
|
20
|
+
const flow = loadFlowFile(path.resolve(flowPath));
|
|
21
|
+
const result = await runMacosFlow({
|
|
22
|
+
flow,
|
|
23
|
+
appPath: appPath || flow.app || "",
|
|
24
|
+
logPath: process.env.FLOW_LOG || (evidenceDir ? path.join(evidenceDir, "flow.log") : ""),
|
|
25
|
+
screenshotDir: evidenceDir || "",
|
|
26
|
+
});
|
|
27
|
+
console.log(`${result.passed ? "✅" : "❌"} ${result.name} — ${result.executed}/${result.total} steps, ${result.failed} failed`);
|
|
28
|
+
process.exit(result.passed ? 0 : 1);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
console.error(`❌ ${error.message || error}`);
|
|
31
|
+
process.exit(1);
|
|
32
|
+
}
|