@aarwitz/tapp 0.33.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.
@@ -56,6 +56,7 @@
56
56
  <label class="prompt-field"><span class="sr-only">Website, repository, folder, or build</span><input id="prompt-input" name="input" placeholder="A website URL, a GitHub repo, a folder on this Mac, a bundle id, an .app or .apk…" spellcheck="false" required></label>
57
57
  <button class="primary prompt-go" type="submit" id="prompt-start" aria-label="Start">→</button>
58
58
  </form>
59
+ <div class="platform-strip" id="platform-strip" hidden></div>
59
60
  <ul class="prompt-suggestions" aria-label="Examples">
60
61
  <li><button type="button" data-kind="url" data-prompt="https://example.com"><span>⌁</span><b>https://example.com</b><small>audit a website read-only — safe on production, nothing is clicked</small></button></li>
61
62
  <li><button type="button" data-kind="path" data-prompt="~/code/my-app"><span>⌘</span><b>~/code/my-app</b><small>open a repo folder on this Mac — detects iOS, Android and web targets, builds locally</small></button></li>
@@ -89,6 +90,7 @@
89
90
  <nav class="primary-nav" aria-label="Product navigation">
90
91
  <button data-view="overview" class="active"><span><svg><use href="#i-grid"/></svg></span>Overview</button>
91
92
  <button data-view="runs"><span><svg><use href="#i-play"/></svg></span>Runs <i id="run-count" class="zero">0</i></button>
93
+ <button data-view="platforms"><span><svg><use href="#i-grid"/></svg></span>Platforms</button>
92
94
  <button data-view="admin" id="admin-nav" class="hidden"><span><svg><use href="#i-grid"/></svg></span>Admin</button>
93
95
  </nav>
94
96
  <div class="sidebar-project">
@@ -166,6 +168,10 @@
166
168
  </section>
167
169
  </section>
168
170
 
171
+ <section class="workspace-view" data-view-panel="platforms">
172
+ <div class="view-heading simple"><div><p class="eyebrow">Platforms</p><h1>What tapp can drive</h1><p>tapp is one engine with a driver per platform. This page says what this Studio can start right now, and where the rest runs.</p></div></div>
173
+ <div id="platform-list"><div class="empty">Checking this machine…</div></div>
174
+ </section>
169
175
  <section class="workspace-view" data-view-panel="admin">
170
176
  <div class="command-bar"><div><h1>Admin</h1><p>Everything this deployment knows about itself. Never a credential — those are encrypted and are not decrypted to be looked at.</p></div></div>
171
177
  <div id="admin-body"><div class="empty">Loading…</div></div>
@@ -6,7 +6,10 @@ export const customerProductContract = Object.freeze({
6
6
  schemaVersion: 2,
7
7
  product: "Tapp",
8
8
  interface: "customer-browser",
9
- 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"],
10
13
  // A repository is opened by path (`tapp app /path/to/repo`); a website by URL in the Studio.
11
14
  repositorySources: ["local-path", "github"],
12
15
  entryLayers: ["repository", "website"],
@@ -15,7 +18,9 @@ export const customerProductContract = Object.freeze({
15
18
  { id: "runs", label: "Runs", capabilities: ["run-history", "run-detail", "evidence-page", "website-audit"] },
16
19
  // Only an owner of this deployment ever sees this one (TAPP_ADMIN_EMAILS); to anybody else
17
20
  // the nav item is absent and the route is a 404.
18
- { id: "admin", label: "Admin", capabilities: ["deployment-usage", "account-list"] },
21
+ // Says what tapp drives, what THIS Studio can start, and what to do about the difference.
22
+ { id: "platforms", label: "Platforms", capabilities: ["platform-matrix", "self-host-command", "platform-interest"] },
23
+ { id: "admin", label: "Admin", capabilities: ["deployment-usage", "account-list", "platform-demand"] },
19
24
  ],
20
25
  operations: ["initialize", "session-start", "session-act", "session-save-flow", "session-end", "gate", "audit"],
21
26
  invariants: [
@@ -25,5 +30,6 @@ export const customerProductContract = Object.freeze({
25
30
  "Repositories are opened from the machine the Studio runs on; nothing is uploaded or cloned by the Studio.",
26
31
  "Deterministic replay and ordinary merge decisions are keyless.",
27
32
  "The admin view reports counts about this deployment; credentials are encrypted and are never decrypted to be shown.",
33
+ "The Platforms view states what this machine can start, computed from the machine; a platform with no driver says so in those words and is never described as needing different hardware.",
28
34
  ],
29
35
  });
@@ -24,6 +24,8 @@ import { accessConfig, createAccessVerifier } from "./access-jwt.js";
24
24
  import { oauthProviders, oauthAuthorizeUrl, oauthEmailFromCode, isOauthProvider } from "./oauth.js";
25
25
  import { journeyFromCapture, JourneyStore, slugify } from "./journeys.js";
26
26
  import { AlertStore, alertForChange, alertMessage, deliverAlert } from "./alerts.js";
27
+ import { platformStates, selfHostAnswer, PLATFORM_TARGETS, hostToolchain } from "./platforms.js";
28
+ import { isMacosAppBundle } from "./macos-driver.js";
27
29
 
28
30
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
29
31
  const assetRoot = path.join(packageRoot, "browser");
@@ -134,6 +136,7 @@ const OAUTH_STATE_COOKIE = "tapp_oauth_state";
134
136
  function anonymousAllows(method, pathname) {
135
137
  if (method === "GET") {
136
138
  if (pathname === "/" || pathname === "/admin" || pathname === "/api/version" || pathname === "/api/session" || pathname === "/api/audits") return true;
139
+ if (pathname === "/api/platforms") return true;
137
140
  if (pathname.startsWith("/assets/")) return true;
138
141
  if (/^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/files$/.test(pathname)) return true;
139
142
  if (/^\/evidence\/captures\//.test(pathname)) return true;
@@ -150,6 +153,9 @@ function anonymousAllows(method, pathname) {
150
153
  // repo into the landing page, which is how five of its six examples used to dead-end.
151
154
  // `explore` is listed so a visitor receives the honest "run this on your own machine" answer
152
155
  // from the handler, rather than a bare 401 that reads as broken.
156
+ // Saying "I would use this for Android" is the one piece of demand a stranger can give us,
157
+ // and the reason to ask is strongest exactly when the answer was "not from here".
158
+ if (method === "POST" && pathname === "/api/platforms/interest") return true;
153
159
  return method === "POST" && ["/api/operations/audit", "/api/operations/open", "/api/operations/explore-build", "/api/operations/explore"].includes(pathname);
154
160
  }
155
161
 
@@ -461,9 +467,9 @@ function runnerSummary({ hosted = false } = {}) {
461
467
  { id:"managed-android", platform:"android", label:"Managed Android runner", status:"unavailable", remediation:"The hosted customer adapter is not yet connected to a lease-backed Android runner." },
462
468
  { id:"hosted-web", platform:"web", label:"Hosted Chromium", status:"needs-check", remediation:"Tapp verifies the isolated Chromium runtime when the selected web target starts." },
463
469
  ];
464
- const executable = (name) => String(process.env.PATH || "").split(path.delimiter).some((dir) => dir && fs.existsSync(path.join(dir, name)));
465
- const ios = process.platform === "darwin" && (fs.existsSync("/usr/bin/xcodebuild") || executable("xcodebuild"));
466
- const android = executable(process.platform === "win32" ? "adb.exe" : "adb") || !!process.env.ANDROID_SDK_ROOT || !!process.env.ANDROID_HOME;
470
+ // One probe for the whole product, so the runner list and the platform surface can never
471
+ // disagree about whether this machine has Xcode or adb (mcp-server/src/platforms.js).
472
+ const { ios, android } = hostToolchain();
467
473
  return [
468
474
  { id: "local-ios", platform: "ios", label: "Local Xcode simulator", status: ios ? "available" : "unavailable", remediation: ios ? "" : "Use a macOS runner with Xcode for iOS." },
469
475
  { id: "local-android", platform: "android", label: "Local Android runtime", status: android ? "available" : "needs-check", remediation: android ? "Start or connect an emulator/device." : "Install Android SDK platform-tools or connect a managed Android runner." },
@@ -1194,6 +1200,17 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1194
1200
  },
1195
1201
  recentRuns: runs.slice(0, 40),
1196
1202
  totalRuns: runs.length,
1203
+ // What people wanted that this deployment could not do. "Asked for" is someone
1204
+ // pressing "tell me when tapp can run this"; "turned away" is someone who actually
1205
+ // pointed tapp at a target it could not start here. The second is the stronger
1206
+ // signal, because they tried.
1207
+ demand: PLATFORM_TARGETS.map((target) => ({
1208
+ id: target.id,
1209
+ label: target.label,
1210
+ state: platformStates({ hosted }).find((entry) => entry.id === target.id)?.state || "unknown",
1211
+ askedFor: events.filter((entry) => entry.event === "platform.asked" && entry.platform === target.id).length,
1212
+ turnedAway: events.filter((entry) => entry.event === "self-host.answered" && entry.platform === target.id).length,
1213
+ })),
1197
1214
  });
1198
1215
  return;
1199
1216
  }
@@ -1246,6 +1263,28 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1246
1263
  json(response, 200, { ok: accounts.revokeToken(account.id, revokeTokenMatch[1]) });
1247
1264
  return;
1248
1265
  }
1266
+ // What tapp drives, and what this particular Studio can start. Public, because the honest
1267
+ // answer to "does this do iOS?" is yes-but-not-from-here, and a visitor who cannot see
1268
+ // that concludes tapp is a website checker (ADR-0010).
1269
+ if (request.method === "GET" && url.pathname === "/api/platforms") {
1270
+ json(response, 200, { hosted, platforms: platformStates({ hosted }) });
1271
+ return;
1272
+ }
1273
+ // "I would use this for Android." The only demand signal a stranger can give us, and it
1274
+ // matters most at the moment the answer was "not from here". No contact details are taken:
1275
+ // this is a counter, not a lead form, and the usage journal keeps no handle.
1276
+ if (request.method === "POST" && url.pathname === "/api/platforms/interest") {
1277
+ guardMutation(request);
1278
+ const asked = await readJsonBody(request);
1279
+ const wanted = String(asked?.platform || "");
1280
+ if (!PLATFORM_TARGETS.some((target) => target.id === wanted)) {
1281
+ json(response, 400, { error: `Unknown platform '${wanted}'` });
1282
+ return;
1283
+ }
1284
+ logUsage("platform.asked", { platform: wanted, ...(account ? { account: account.id.slice(0, 8) } : { visitor: String(visitorId || "").slice(0, 8) }) });
1285
+ json(response, 200, { ok: true, platform: wanted });
1286
+ return;
1287
+ }
1249
1288
  if (request.method === "GET" && url.pathname === "/api/session") {
1250
1289
  if (account) {
1251
1290
  json(response, 200, {
@@ -1254,6 +1293,10 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1254
1293
  access: "account", email: account.email, signInProvider, signInOptions, viaToken, admin: isAdmin(account),
1255
1294
  accepts: ["url"],
1256
1295
  selfHostOnly: ["path", "github", "bundle", "app", "apk"],
1296
+ // What tapp drives, and what THIS machine can start. The Studio shows all of it:
1297
+ // hiding iOS and Android is what made a cross-platform product look like a website
1298
+ // checker (ADR-0010).
1299
+ platforms: platformStates({ hosted: true }),
1257
1300
  });
1258
1301
  return;
1259
1302
  }
@@ -1262,15 +1305,18 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1262
1305
  csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
1263
1306
  contract: customerProductContract, supportedPlatforms: ["web"], runners: [],
1264
1307
  access: "anonymous", signInProvider, signInOptions,
1265
- // The prompt screen offers folders, bundle ids and builds. None of them can work in
1266
- // a hosted Studio — there is no Mac, no simulator and no access to the visitor's
1267
- // disk — so say so here rather than letting the UI offer them.
1308
+ // The prompt screen offers folders, bundle ids and builds. None of them can be
1309
+ // STARTED in a hosted Studio — there is no Mac, no simulator and no access to the
1310
+ // visitor's disk. `accepts` says what can start here; `platforms` says what tapp
1311
+ // drives and where, because a visitor deserves to know the product does phones
1312
+ // even when this deployment cannot (ADR-0010).
1268
1313
  accepts: ["url"],
1269
1314
  selfHostOnly: ["path", "github", "bundle", "app", "apk"],
1315
+ platforms: platformStates({ hosted: true }),
1270
1316
  });
1271
1317
  return;
1272
1318
  }
1273
- json(response, 200, { csrfToken, mode: hosted ? "managed" : "local", product: "Tapp", root: hosted ? null : registry.currentRoot(), repository: hosted ? hostedRepository(registry.current()) : registry.current(), repositories: hosted ? registry.list().map(hostedRepository) : registry.list(), contract: customerProductContract, supportedPlatforms: customerProductContract.targetPlatforms, runners: runnerSummary({ hosted }) });
1319
+ json(response, 200, { csrfToken, mode: hosted ? "managed" : "local", product: "Tapp", root: hosted ? null : registry.currentRoot(), repository: hosted ? hostedRepository(registry.current()) : registry.current(), repositories: hosted ? registry.list().map(hostedRepository) : registry.list(), contract: customerProductContract, supportedPlatforms: customerProductContract.targetPlatforms, runners: runnerSummary({ hosted }), platforms: platformStates({ hosted }) });
1274
1320
  return;
1275
1321
  }
1276
1322
  if (request.method === "GET" && url.pathname === "/api/repositories") { json(response, 200, hosted ? { current:hostedRepository(registry.current()), repositories:registry.list().map(hostedRepository) } : { current: registry.current(), repositories: registry.list() }); return; }
@@ -1413,22 +1459,36 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1413
1459
  if (operation === "explore-build") {
1414
1460
  if (anonymous) {
1415
1461
  const asked = classifyPrompt(body.input);
1416
- logUsage("self-host.answered", { visitor: visitorId.slice(0, 8), kind: asked.kind });
1417
- const where = asked.kind === "apk" ? "an Android device or emulator" : "a Mac with an iOS simulator";
1418
- json(response, 200, { kind: "self-host", target: asked.value, command: "npx -y @aarwitz/tapp@latest app",
1419
- message: `Running ${asked.value || "a build"} needs ${where}, which the cloud does not have. Start the Studio on that machine: npx -y @aarwitz/tapp@latest app` });
1462
+ const wanted = asked.kind === "apk" ? "android" : "ios";
1463
+ logUsage("self-host.answered", { visitor: visitorId.slice(0, 8), kind: asked.kind, platform: wanted });
1464
+ json(response, 200, selfHostAnswer(wanted, asked.value, { hosted: true }));
1465
+ return;
1466
+ }
1467
+ if (hosted) {
1468
+ // A signed-in account used to get a bare 400 here, which reads as "tapp is broken"
1469
+ // rather than "tapp does this, just not on a machine without a simulator". Give the
1470
+ // same structured answer a visitor gets: where it runs, and the command to get there.
1471
+ const asked = classifyPrompt(body.input);
1472
+ const wanted = asked.kind === "apk" ? "android" : "ios";
1473
+ logUsage("self-host.answered", { account: account?.id?.slice(0, 8), kind: asked.kind, platform: wanted });
1474
+ json(response, 200, selfHostAnswer(wanted, asked.value, { hosted: true }));
1420
1475
  return;
1421
1476
  }
1422
- if (hosted) throw Object.assign(new Error("Builds are explored on the machine that has the simulator; run the Studio locally"), { statusCode: 400 });
1423
1477
  const prompt = classifyPrompt(body.input);
1424
- if (!["bundle", "app", "apk"].includes(prompt.kind)) throw Object.assign(new Error("Give a bundle id (com.company.app), a simulator .app, or an .apk"), { statusCode: 400 });
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 });
1425
1479
  const job = startJob(operation, async (progress) => {
1426
1480
  const engine = await import("./index.js");
1427
- job.platform = prompt.kind === "apk" ? "android" : "ios";
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";
1428
1485
  job.liveSimulator = job.platform === "ios";
1429
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 } : {}) });
1430
1487
  let result;
1431
- if (prompt.kind === "apk") {
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") {
1432
1492
  progress({ phase: "runtime", text: `Installing ${path.basename(prompt.value)} on the connected Android device` });
1433
1493
  result = await engine.runQaAndroid({ apkPath: prompt.value, appId: String(body.appId || ""), maxActions: Number(body.maxActions) || 40, timeout: Number(body.timeout) || 600, onProgress: forward });
1434
1494
  } else {
@@ -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);
@@ -3206,7 +3260,11 @@ async function handleTool(name, args = {}) {
3206
3260
  : { code: 1, stdout: "", stderr: "Xcode not found" };
3207
3261
  const bootedLine = (simctl.stdout || "").split("\n").find((l) => /\(Booted\)/.test(l));
3208
3262
  const bootedName = bootedLine ? bootedLine.trim().replace(/\s*\(.*$/, "") : null;
3209
- const adb = await runCommand("adb", ["devices"]);
3263
+ // The SDK is commonly an unlinked Homebrew cask with ANDROID_HOME unset, so a bare `adb`
3264
+ // reports "not found" on machines where `tapp explore --platform android` works. Use the
3265
+ // driver's own resolver, which is what the run will use (resolveAdbPath).
3266
+ const { resolveAdbPath } = await import("./android-driver.js");
3267
+ const adb = await runCommand(resolveAdbPath() || "adb", ["devices"]);
3210
3268
  const androidDevice = adb.code === 0
3211
3269
  ? (adb.stdout || "").split("\n").find((line) => /\tdevice\s*$/.test(line))
3212
3270
  : null;
@@ -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
+ }