@aarwitz/tapp 0.34.0 → 0.35.1
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 +22 -16
- package/package.json +4 -2
- package/scripts/run-macos-flow.js +32 -0
|
@@ -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
|
+
}
|