@aarwitz/tapp 0.35.7 → 0.35.9

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.
@@ -0,0 +1,212 @@
1
+ // The agent is the person's own, on their own plan; tapp is its hands (ADR-0012).
2
+ //
3
+ // tapp signs nobody in to Claude or ChatGPT and holds no token for either. Anthropic's consumer
4
+ // terms (2026-02-19) forbid using a Claude Free/Pro/Max OAuth token in any product but Claude
5
+ // Code and claude.ai — the Agent SDK included — so the only honest way to put a person's Claude
6
+ // plan behind the Studio chat is the one Gideon uses: find the `claude` they already signed in
7
+ // to, and drive it. Codex and Gemini are found the same way. This module knows which of those are
8
+ // on this machine, whether each is signed in with a plan (or an API key, which bills per use),
9
+ // and how to run one with tapp's tools attached and nothing else — no shell, no file edits.
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import readline from "node:readline";
14
+ import { spawn, spawnSync } from "node:child_process";
15
+
16
+ export const ENGINES = Object.freeze([
17
+ { id: "claude", label: "Claude Code", binary: "claude", plan: "Claude", drives: true,
18
+ install: "Install Claude Code from claude.com/code, then run `claude` in a terminal and sign in with your Claude account." },
19
+ { id: "codex", label: "Codex", binary: "codex", plan: "ChatGPT", drives: false,
20
+ install: "Install Codex (npm i -g @openai/codex), then run `codex login` and sign in with your ChatGPT account." },
21
+ { id: "gemini", label: "Gemini CLI", binary: "gemini", plan: "Google", drives: false,
22
+ install: "Install Gemini CLI (npm i -g @google/gemini-cli), then run `gemini` and sign in with Google." },
23
+ ]);
24
+
25
+ // What the Studio chat lets the agent do: tapp's own tools, and reading the project. Never a
26
+ // shell, never an edit — the agent drives the application under test, not this machine.
27
+ export const AGENT_ALLOWED_TOOLS = "mcp__tapp,Read,Glob,Grep";
28
+ export const AGENT_DISALLOWED_TOOLS = "Bash,Edit,Write,MultiEdit,NotebookEdit,WebFetch,WebSearch,Agent";
29
+
30
+ /**
31
+ * A GUI-launched process often has a lean PATH, and these CLIs install into a handful of
32
+ * well-known places; look there too, so "not installed" is only said when it is true.
33
+ */
34
+ export function findBinary(name, { env = process.env, home = os.homedir() } = {}) {
35
+ const dirs = [...String(env.PATH || "").split(path.delimiter), path.join(home, ".local", "bin"), path.join(home, ".npm-global", "bin"), "/opt/homebrew/bin", "/usr/local/bin"];
36
+ for (const dir of dirs) {
37
+ if (!dir) continue;
38
+ const file = path.join(dir, name);
39
+ try { if (fs.statSync(file).isFile()) return file; } catch { /* not here */ }
40
+ }
41
+ return "";
42
+ }
43
+
44
+ export function execStatus(binary, args, { env = process.env, timeoutMs = 15_000 } = {}) {
45
+ const run = spawnSync(binary, args, { encoding: "utf8", timeout: timeoutMs, env });
46
+ return { code: run.status, out: String(run.stdout || ""), err: String(run.stderr || "") };
47
+ }
48
+
49
+ const base = (engine, binary) => ({ id: engine.id, label: engine.label, plan: engine.plan, binary, drives: engine.drives, account: null, billing: null });
50
+ const missing = (engine) => ({ ...base(engine, ""), state: "missing", usable: false, detail: "Not installed on this machine.", fix: engine.install });
51
+
52
+ /** Claude Code: `claude auth status` says how it is signed in. A plan is what makes this free to use. */
53
+ export function claudeStatus({ env = process.env, home = os.homedir(), exec = execStatus } = {}) {
54
+ const engine = ENGINES[0];
55
+ const binary = findBinary(engine.binary, { env, home });
56
+ if (!binary) return missing(engine);
57
+ let info = null;
58
+ try { info = JSON.parse(exec(binary, ["auth", "status"], { env }).out); } catch { /* not JSON: an old build, or not signed in */ }
59
+ if (!info || info.loggedIn !== true) {
60
+ return { ...base(engine, binary), state: "warning", usable: false, detail: "Not signed in.", fix: "Run `claude` in a terminal and sign in with your Claude account." };
61
+ }
62
+ const account = { email: String(info.email || ""), plan: String(info.subscriptionType || "") };
63
+ if (info.authMethod === "claude.ai") {
64
+ const plan = account.plan ? `Claude ${account.plan[0].toUpperCase()}${account.plan.slice(1)}` : "Claude";
65
+ return { ...base(engine, binary), state: "ok", usable: true, billing: "plan", account, detail: `${plan} plan${account.email ? ` · ${account.email}` : ""}`, fix: "" };
66
+ }
67
+ return { ...base(engine, binary), state: "warning", usable: true, billing: "api-key", account, detail: "Signed in with an API key, which bills per use.", fix: "Sign in with your Claude account instead: run `claude`, then /login." };
68
+ }
69
+
70
+ // The ChatGPT account Codex is signed in with, from its saved sign-in: the id token's payload
71
+ // carries the address. Read for display only; nothing here is verified or sent anywhere.
72
+ function codexEmail(home) {
73
+ try {
74
+ const saved = JSON.parse(fs.readFileSync(path.join(home, ".codex", "auth.json"), "utf8"));
75
+ const token = String(saved?.tokens?.id_token || "");
76
+ const payload = token.split(".")[1];
77
+ if (!payload) return "";
78
+ const claims = JSON.parse(Buffer.from(payload.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
79
+ return String(claims.email || "");
80
+ } catch { return ""; }
81
+ }
82
+
83
+ /** Codex: `codex login status` says "Logged in using ChatGPT", or an API key, or nothing. */
84
+ export function codexStatus({ env = process.env, home = os.homedir(), exec = execStatus } = {}) {
85
+ const engine = ENGINES[1];
86
+ const binary = findBinary(engine.binary, { env, home });
87
+ if (!binary) return missing(engine);
88
+ const { out, err } = exec(binary, ["login", "status"], { env });
89
+ const text = `${out}\n${err}`;
90
+ if (/logged in using chatgpt/i.test(text)) {
91
+ const email = codexEmail(home);
92
+ return { ...base(engine, binary), state: "ok", usable: true, billing: "plan", account: { email, plan: "ChatGPT" }, detail: `ChatGPT plan${email ? ` · ${email}` : ""}`, fix: "" };
93
+ }
94
+ if (/api key/i.test(text)) return { ...base(engine, binary), state: "warning", usable: true, billing: "api-key", detail: "Signed in with an API key, which bills per use.", fix: "Sign in with your ChatGPT account instead: run `codex logout`, then `codex login`." };
95
+ return { ...base(engine, binary), state: "warning", usable: false, detail: "Not signed in.", fix: "Run `codex login` in a terminal; you get a link and a code to finish on any device." };
96
+ }
97
+
98
+ /** Gemini CLI keeps its Google sign-in in a credentials file; present means signed in. */
99
+ export function geminiStatus({ env = process.env, home = os.homedir() } = {}) {
100
+ const engine = ENGINES[2];
101
+ const binary = findBinary(engine.binary, { env, home });
102
+ if (!binary) return missing(engine);
103
+ if (fs.existsSync(path.join(home, ".gemini", "oauth_creds.json"))) return { ...base(engine, binary), state: "ok", usable: true, billing: "plan", account: { email: "", plan: "Google" }, detail: "Google account", fix: "" };
104
+ return { ...base(engine, binary), state: "warning", usable: false, detail: "Not signed in.", fix: "Run `gemini` in a terminal and sign in with Google." };
105
+ }
106
+
107
+ /** Every engine tapp knows, as found on this machine. */
108
+ export function detectEngines(options = {}) {
109
+ return [claudeStatus(options), codexStatus(options), geminiStatus(options)];
110
+ }
111
+
112
+ /** The MCP server the agent gets: this very package, on this machine, sharing TAPP_HOME. */
113
+ export function tappMcpConfig({ packageRoot, env = process.env, node = process.execPath }) {
114
+ const serverEnv = {};
115
+ if (env.TAPP_HOME) serverEnv.TAPP_HOME = env.TAPP_HOME;
116
+ return JSON.stringify({ mcpServers: { tapp: { command: node, args: [path.join(packageRoot, "bin", "tapp.js"), "mcp"], ...(Object.keys(serverEnv).length ? { env: serverEnv } : {}) } } });
117
+ }
118
+
119
+ /**
120
+ * How Claude Code is run for one chat turn. Non-interactive, streaming its events as JSON lines,
121
+ * with tapp's tools and the project to read — and the tools that would touch this machine ruled
122
+ * out by name, not only left unlisted. A thread continues with `--resume`.
123
+ */
124
+ export function claudeArguments({ prompt, resume = "", mcpConfig, systemPromptFile = "", model = "" }) {
125
+ const args = ["-p", String(prompt), "--output-format", "stream-json", "--verbose", "--permission-mode", "default",
126
+ "--allowedTools", AGENT_ALLOWED_TOOLS, "--disallowedTools", AGENT_DISALLOWED_TOOLS];
127
+ if (mcpConfig) args.push("--mcp-config", mcpConfig);
128
+ if (systemPromptFile) args.push("--append-system-prompt-file", systemPromptFile);
129
+ if (model) args.push("--model", model);
130
+ if (resume) args.push("--resume", resume);
131
+ return args;
132
+ }
133
+
134
+ const TOOL_PREFIX = /^mcp__tapp__/;
135
+ const textOf = (content) => Array.isArray(content) ? content.map((b) => (typeof b === "string" ? b : b?.text || "")).join(" ") : String(content ?? "");
136
+ function summarizeInput(input) {
137
+ if (!input || typeof input !== "object") return "";
138
+ for (const key of ["goal", "url", "target", "action", "name", "id", "text", "query", "capture", "platform", "projectDir"]) {
139
+ if (typeof input[key] === "string" && input[key].trim()) return `${key}: ${input[key].trim().slice(0, 80)}`;
140
+ }
141
+ return "";
142
+ }
143
+
144
+ /**
145
+ * One Claude Code event → the chat lines a person should see. Thinking and partial deltas are
146
+ * not shown; tool calls are named in tapp's own words; a tool error is a warning; the final
147
+ * answer is the result. Returns an array, since one assistant message can carry several blocks.
148
+ */
149
+ export function agentLines(event) {
150
+ if (!event || typeof event !== "object") return [];
151
+ if (event.type === "system" && event.subtype === "init") return [{ phase: "agent", text: "Claude Code is on it." }];
152
+ if (event.type === "assistant") {
153
+ const blocks = event.message?.content;
154
+ if (!Array.isArray(blocks)) return [];
155
+ const lines = [];
156
+ for (const block of blocks) {
157
+ if (block?.type === "text" && String(block.text || "").trim()) lines.push({ phase: "agent", text: String(block.text).trim().slice(0, 1200) });
158
+ if (block?.type === "tool_use") {
159
+ const name = String(block.name || "tool").replace(TOOL_PREFIX, "");
160
+ const summary = summarizeInput(block.input);
161
+ lines.push({ phase: "agent-tool", text: `${name}${summary ? ` — ${summary}` : ""}` });
162
+ }
163
+ }
164
+ return lines;
165
+ }
166
+ if (event.type === "user") {
167
+ const blocks = event.message?.content;
168
+ if (!Array.isArray(blocks)) return [];
169
+ return blocks.filter((b) => b?.type === "tool_result" && b.is_error).map((b) => ({ phase: "agent-warning", text: `Tool error: ${textOf(b.content).trim().slice(0, 300)}` }));
170
+ }
171
+ if (event.type === "result") {
172
+ const text = String(event.result || "").trim().slice(0, 1200);
173
+ if (event.is_error) return [{ phase: "agent-warning", text: text || "Claude Code stopped with an error." }];
174
+ return text ? [{ phase: "agent-done", text }] : [];
175
+ }
176
+ return [];
177
+ }
178
+
179
+ /**
180
+ * Run Claude Code for one turn. Resolves with the result event's facts once the process ends;
181
+ * rejects when it ends with no result. `stop()` ends the turn the way Ctrl-C would.
182
+ */
183
+ export function runClaude({ binary, args, cwd, env = process.env, onEvent = () => {} }) {
184
+ const child = spawn(binary, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
185
+ let result = null;
186
+ let stderrTail = "";
187
+ let stdoutTail = "";
188
+ child.stderr.on("data", (chunk) => { stderrTail = (stderrTail + chunk).slice(-2000); });
189
+ const lines = readline.createInterface({ input: child.stdout });
190
+ lines.on("line", (line) => {
191
+ if (!line.trim()) return;
192
+ let event;
193
+ try { event = JSON.parse(line); } catch { stdoutTail = (stdoutTail + line).slice(-2000); return; }
194
+ if (event?.type === "result") result = event;
195
+ try { onEvent(event); } catch { /* a listener's problem is not the run's */ }
196
+ });
197
+ const done = new Promise((resolve, reject) => {
198
+ child.on("error", (error) => reject(new Error(`Could not start Claude Code: ${error.message}`)));
199
+ child.on("close", (code, signal) => {
200
+ // The stream can still be draining when the process closes; let it finish.
201
+ setImmediate(() => {
202
+ if (result) {
203
+ resolve({ sessionId: String(result.session_id || ""), text: String(result.result || ""), turns: Number(result.num_turns) || 0, costUsd: Number(result.total_cost_usd) || 0, isError: result.is_error === true, stopped: signal === "SIGINT" });
204
+ return;
205
+ }
206
+ const reason = (stderrTail || stdoutTail).trim().split("\n").filter(Boolean).slice(-3).join(" · ");
207
+ reject(new Error(signal ? `Claude Code was stopped (${signal})` : `Claude Code ended (exit ${code}) without a result${reason ? `: ${reason}` : ""}`));
208
+ });
209
+ });
210
+ });
211
+ return { child, done, stop: () => { try { child.kill("SIGINT"); } catch { /* already gone */ } } };
212
+ }
@@ -49,6 +49,8 @@ export const FLOW_ACTIONS = Object.freeze([
49
49
  { action: "drag", target: "{from, by: [dx, dy]} or {from, to}", passes: "the control was dragged in steps, so listeners watching movement fire; web only — typing into a range input sets its value without the handle moving. This says the gesture was made, not that the page reacted: assert after it" },
50
50
  { action: "screenshot", target: "a name for the picture", passes: "a viewport-sized picture was saved beside the run's evidence; web only" },
51
51
  { action: "back", target: "(none)", passes: "the platform back navigation was performed" },
52
+ { action: "open_url", target: "a URL or deep link (myapp://claim?t=$TOKEN; $NAME substitutes like any other step)", passes: "the link was opened and the app under test came to the front (iOS/Android); on web, the page navigated there. Not supported on macOS" },
53
+ { action: "upload", target: "{field, file} — file is a local path, resolved relative to the Flow file", passes: "the file was chosen for that <input type=file>, including one hidden behind a styled label, and the page's change handler ran; web only" },
52
54
  { action: "wait", target: "milliseconds (fixed pause; prefer wait_for)", passes: "always" },
53
55
  { action: "wait_for", target: "label / text (+ per-step timeoutMs/timeout; flow-level timeoutMs sets the default)", passes: "the element appeared before the timeout" },
54
56
  { action: "assert_screen", target: "the detected SCREEN TITLE (navigation bar / heading), not arbitrary text", passes: "the current screen's title equals the target" },
@@ -103,12 +105,15 @@ export function validateFlowSteps(flow, platform = inferFlowPlatform(flow)) {
103
105
  if (step.action === "tap" && /^\s*-?\d+(\.\d+)?\s*,\s*-?\d+(\.\d+)?\s*$/.test(step.target)) {
104
106
  errors.push(`step ${n}: tap target '${step.target.trim()}' is a coordinate; Flow taps are label-only on ${platform} (use tapp_session_act tap {x,y} to learn the label, then record it)`);
105
107
  }
106
- if (["tap", "wait_for", "assert_screen", "assert_exists", "assert_absent"].includes(step.action) && !step.target.trim()) {
108
+ if (["tap", "wait_for", "assert_screen", "assert_exists", "assert_absent", "open_url"].includes(step.action) && !step.target.trim()) {
107
109
  errors.push(`step ${n}: ${step.action} needs a target`);
108
110
  }
109
111
  if (step.action === "type" && (!step.target.trim() || !("value" in (step.params || {})))) {
110
112
  errors.push(`step ${n}: type needs {field, value}`);
111
113
  }
114
+ if (step.action === "upload" && (!step.target.trim() || !String(step.params.file ?? "").trim())) {
115
+ errors.push(`step ${n}: upload needs {field, file}`);
116
+ }
112
117
  if (step.action === "assert_text" && (!step.target.trim() || !step.value)) {
113
118
  errors.push(`step ${n}: assert_text needs {of, contains}`);
114
119
  }
@@ -174,7 +179,11 @@ export function loadFlowFile(flowPath, options = {}) {
174
179
  if (parsed.status !== 0) {
175
180
  throw new Error((parsed.stderr || parsed.stdout || "Could not parse Flow").trim());
176
181
  }
177
- return compileFlowTasksFromRepository({ flow: JSON.parse(parsed.stdout), sourcePath: flowPath, ...options });
182
+ const compiled = compileFlowTasksFromRepository({ flow: JSON.parse(parsed.stdout), sourcePath: flowPath, ...options });
183
+ // TM-1077: an `upload:` step's file path is relative to the Flow file, not the
184
+ // process's cwd — carried on the flow object itself so every runner (web today;
185
+ // the vocabulary is shared) can resolve it without its own sourcePath parameter.
186
+ return { ...compiled, sourcePath: flowPath };
178
187
  }
179
188
 
180
189
  export class FlowLog {
@@ -32,9 +32,10 @@ const scriptsDir = path.join(repoRoot, "scripts");
32
32
  import { writeCaptureProvenance, readCaptureProvenance, captureBelongsToProject, provenanceLabel } from "./capture-provenance.js";
33
33
  import { chooseSignInSubmit, findSignInSubmit } from "./sign-in.js";
34
34
  // TAPP_HOME (set by the `tapp` CLI when installed) redirects writable output to a user directory.
35
- // The old alias remains a read-only fallback; unset repository development stays local.
35
+ // Unset (a source checkout), evidence still goes to ~/.tapp/captures (TM-651): never into the
36
+ // repository, where the evidence clearing-out never looks.
36
37
  const tappHome = (process.env.TAPP_HOME || "").trim();
37
- const capturesDir = tappHome ? path.join(tappHome, "captures") : path.join(repoRoot, "captures");
38
+ const capturesDir = path.join(tappHome || path.join(os.homedir(), ".tapp"), "captures");
38
39
  const MAX_OUTPUT_CHARS = 60_000;
39
40
  const requiredAuthToken = (process.env.TAPP_MCP_TOKEN || "").trim();
40
41
 
@@ -935,9 +936,9 @@ async function startWebSession(url, { testEmail = "", testPassword = "", device
935
936
  try {
936
937
  const parsed = new URL(String(url || ""));
937
938
  if (!/^https?:$/.test(parsed.protocol)) return { error:"Web session URL must be http(s)" };
938
- const { loadPlaywright, webContextOptions, webBrowserLaunchOptions } = await import("./web-explorer.js");
939
+ const { loadPlaywright, webContextOptions, webBrowserLaunchOptions, launchWebBrowser } = await import("./web-explorer.js");
939
940
  const { chromium, devices } = await loadPlaywright();
940
- browser = await chromium.launch(webBrowserLaunchOptions());
941
+ browser = await launchWebBrowser(chromium, webBrowserLaunchOptions());
941
942
  const context = await browser.newContext({ ...webContextOptions({ device, viewport, devices }), ...(recordVideoDir ? {recordVideo:{dir:recordVideoDir}} : {}) });
942
943
  const page = await context.newPage();
943
944
  await page.goto(parsed.href, { waitUntil:"domcontentloaded", timeout:30_000 });
@@ -163,7 +163,7 @@ export class JourneyStore {
163
163
  }
164
164
 
165
165
  forget(slug) {
166
- try { fs.rmSync(this.flowPath(slug), { force: true }); fs.rmSync(this.statusPath(slug), { force: true }); return true; } catch { return false; }
166
+ try { fs.rmSync(this.flowPath(slug), { force: true }); fs.rmSync(this.statusPath(slug), { force: true }); fs.rmSync(this.reportedPath(slug), { force: true }); return true; } catch { return false; }
167
167
  }
168
168
 
169
169
  statusPath(slug) {
@@ -183,10 +183,38 @@ export class JourneyStore {
183
183
  }
184
184
 
185
185
  /** Every journey here, with its last result. Names only; never the file contents. */
186
+ // A journey that runs somewhere else — the owner's own machine, against staging or
187
+ // localhost — and reports how it went (ADR-0011 §4). Only the name and the result arrive:
188
+ // never the journey, a credential or a screenshot. The cloud cannot run it, so there is no
189
+ // flow file, and it is never due for a daily check.
190
+ reportedPath(slug) {
191
+ return path.join(this.root, ".reported", `${slugify(slug)}.json`);
192
+ }
193
+
194
+ report({ name, platform = "web", url = "", steps = 0, machine = "", passed, executed = 0, total = 0, failed = 0, at = null }) {
195
+ const slug = slugify(name);
196
+ const file = this.reportedPath(slug);
197
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
198
+ const status = { passed: !!passed, at: at || new Date().toISOString(), captureId: null, executed, total, failed };
199
+ const record = { name, slug, platform, url, steps, machine, status, reportedAt: new Date().toISOString() };
200
+ fs.writeFileSync(file, JSON.stringify(record), { mode: 0o600 });
201
+ return record;
202
+ }
203
+
204
+ reported(slug) {
205
+ try { return JSON.parse(fs.readFileSync(this.reportedPath(slug), "utf8")); } catch { return null; }
206
+ }
207
+
186
208
  list() {
187
209
  let entries = [];
188
210
  try { entries = fs.readdirSync(this.root, { withFileTypes: true }); } catch { return []; }
189
211
  const out = [];
212
+ let reported = [];
213
+ try { reported = fs.readdirSync(path.join(this.root, ".reported")).filter((name) => name.endsWith(".json")); } catch { /* none */ }
214
+ for (const name of reported.sort()) {
215
+ const record = this.reported(name.replace(/\.json$/, ""));
216
+ if (record) out.push({ name: record.name, slug: record.slug, platform: record.platform || "web", url: record.url || "", actor: "", steps: record.steps || 0, status: record.status, source: "reported", machine: record.machine || "" });
217
+ }
190
218
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
191
219
  if (!entry.isFile() || !/\.ya?ml$/i.test(entry.name)) continue;
192
220
  const slug = entry.name.replace(/\.ya?ml$/i, "");
@@ -128,6 +128,8 @@ export async function runMacosFlow({ flow, appPath, logPath, screenshotDir, driv
128
128
  } else if (action === "assert_ai") {
129
129
  status = "skip";
130
130
  detail = "AI assertions are advisory and are not part of deterministic macOS replay";
131
+ } else if (action === "open_url") {
132
+ throw new Error("open_url is not supported on macOS — a desktop app has no system-level link handoff to replay");
131
133
  } else {
132
134
  throw new Error(`unknown action ‘${action}’`);
133
135
  }
@@ -84,6 +84,18 @@ export function hostToolchain({ env = process.env, platform = process.platform }
84
84
  };
85
85
  }
86
86
 
87
+ // What to install on THIS machine when it is the right kind and lacks the one thing. Returns
88
+ // null when the machine is the wrong kind, so the general "needs a Mac" answer stands.
89
+ const MISSING_ON_THIS_MACHINE = {
90
+ ios: (platform) => platform === "darwin"
91
+ ? { summary: "This Mac has no Xcode yet.", how: "Install Xcode from the App Store and open it once to finish its setup. tapp then builds and boots a simulator itself; give it a repository, a simulator .app or a bundle id." }
92
+ : null,
93
+ macos: (platform) => platform === "darwin"
94
+ ? { summary: "This Mac has not given tapp the Accessibility permission.", how: "System Settings → Privacy & Security → Accessibility: allow the app that runs tapp (your terminal, or Node). Then give it a .app." }
95
+ : null,
96
+ android: () => ({ summary: "The Android SDK is not on this machine, or adb cannot be found.", how: "Install Android Studio (or the command-line tools) so adb exists — set ANDROID_HOME if tapp still cannot find it — then plug in a phone with USB debugging allowed, or start an emulator, and give it an .apk." }),
97
+ };
98
+
87
99
  /** The command that opens this same Studio on a machine that can do the work. */
88
100
  export const SELF_HOST_COMMAND = "npx -y @aarwitz/tapp@latest app";
89
101
 
@@ -122,16 +134,19 @@ export function platformStates({ hosted = false, env = process.env, platform = p
122
134
  };
123
135
  }
124
136
  const because = has[target.id] && !exposed ? "not-exposed" : "no-toolchain";
137
+ // The right machine, missing one thing, is a different sentence from the wrong machine: a
138
+ // Mac without Xcode is told to install Xcode, not to find a Mac (ADR-0012's setup flow).
139
+ const missing = because === "no-toolchain" && !hosted ? MISSING_ON_THIS_MACHINE[target.id]?.(platform) : null;
125
140
  return {
126
141
  ...target,
127
142
  state: "needs-machine", because,
128
143
  summary: because === "not-exposed"
129
144
  ? `tapp drives ${target.subject}, and this machine could — but a public Studio only starts website runs.`
130
- : `tapp drives ${target.subject}, but this Studio is not on ${target.machine}.`,
145
+ : missing ? missing.summary : `tapp drives ${target.subject}, but this Studio is not on ${target.machine}.`,
131
146
  // Two ways out, always both: self-host is the same product without the hosting (ADR-0006),
132
147
  // 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.`,
134
- command: SELF_HOST_COMMAND,
148
+ how: missing ? missing.how : `Run this Studio on ${target.machine} and give it ${lower(target.give)} there — or have tapp run it for you.`,
149
+ command: missing ? "" : SELF_HOST_COMMAND,
135
150
  };
136
151
  });
137
152
  }
@@ -8,6 +8,10 @@
8
8
  // Configuration is two values, from flags or the environment:
9
9
  // TAPP_STUDIO https://app.runtapp.com
10
10
  // TAPP_TOKEN tapp_…
11
+ import fs from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+
11
15
  const POLL_MS = 1500;
12
16
  const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
13
17
 
@@ -74,10 +78,52 @@ export async function runStudioJourney(config, name, { onProgress = () => {}, ti
74
78
  }
75
79
  }
76
80
 
81
+ /**
82
+ * The account this machine reports to (ADR-0011 §4): the link the Studio wrote under TAPP_HOME,
83
+ * or TAPP_STUDIO + TAPP_TOKEN in the environment, which win so one shell can report elsewhere.
84
+ * Null when neither is set — reporting is then simply not on.
85
+ */
86
+ export function studioLinkFor(env = process.env) {
87
+ if (env.TAPP_STUDIO && env.TAPP_TOKEN) {
88
+ try { const config = studioConfig({}, env); return config ? { ...config, email: "" } : null; } catch { return null; }
89
+ }
90
+ const home = (env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp");
91
+ try {
92
+ const link = JSON.parse(fs.readFileSync(path.join(home, "studio-link.json"), "utf8"));
93
+ return link && typeof link.origin === "string" && typeof link.token === "string" ? { origin: link.origin, token: link.token, email: link.email || "" } : null;
94
+ } catch { return null; }
95
+ }
96
+
97
+ /** The runner's own verdict, from the log every platform's runner writes: the last result line. */
98
+ export function flowResultFromLog(text) {
99
+ let found = null;
100
+ for (const line of String(text || "").split("\n")) {
101
+ const m = line.match(/^OCQA_FLOW_RESULT:(\{.*\})\s*$/);
102
+ if (m) { try { found = JSON.parse(m[1]); } catch { /* a partial line */ } }
103
+ }
104
+ return found;
105
+ }
106
+
107
+ /** Who this token belongs to. Used once, when a machine is linked, so the link can say whose it is. */
108
+ export async function verifyStudioToken(config) {
109
+ const session = await call(config, "/api/session");
110
+ if (session.access !== "account" || !session.email) throw new Error("That token did not sign in to an account on the Studio");
111
+ return { email: session.email };
112
+ }
113
+
114
+ /**
115
+ * Tell the Studio how a journey run somewhere else went (ADR-0011 §4). The name and the result
116
+ * travel; the journey itself, credentials and screenshots stay where the run happened.
117
+ */
118
+ export async function reportStudioJourney(config, { name, platform = "web", url = "", steps = 0, machine = "", passed, executed = 0, total = 0, failed = 0, at = null }) {
119
+ return call(config, "/api/journeys/report", { method: "POST", body: { name, platform, url, steps, machine, passed: !!passed, executed, total, failed, at } });
120
+ }
121
+
77
122
  /** One line per journey, for a terminal or an agent's transcript. */
78
123
  export function formatJourneyStatus(journey) {
79
124
  const status = journey.status;
80
125
  const state = !status ? "never run" : status.passed ? "passing" : "FAILING";
81
126
  const when = status?.at ? ` · ${new Date(status.at).toISOString().replace("T", " ").slice(0, 16)}` : "";
82
- return `${state === "FAILING" ? "✗" : state === "passing" ? "✓" : "·"} ${journey.name} — ${journey.steps || 0} steps · ${state}${when}`;
127
+ const where = journey.source === "reported" && journey.machine ? ` · runs on ${journey.machine}` : "";
128
+ return `${state === "FAILING" ? "✗" : state === "passing" ? "✓" : "·"} ${journey.name} — ${journey.steps || 0} steps · ${state}${when}${where}`;
83
129
  }
@@ -13,7 +13,7 @@ import fs from "fs";
13
13
  import path from "path";
14
14
  import { createRequire } from "module";
15
15
  import {
16
- NAV_TIMEOUT_MS, loadPlaywright, webBrowserLaunchOptions, webContextOptions, installWebListenerTracking,
16
+ NAV_TIMEOUT_MS, loadPlaywright, webBrowserLaunchOptions, launchWebBrowser, webContextOptions, installWebListenerTracking,
17
17
  waitForWebStability, captureElementEvidence, shouldReportWebRequestFailure, auditStructuralControls,
18
18
  auditFindingsFromControls, slug, detectBlockingOverlay, chooseOverlayDismissal,
19
19
  } from "./web-explorer.js";
@@ -406,7 +406,7 @@ export async function auditWebSite({
406
406
  const maxPages = Math.max(1, Math.min(200, Number(pages) || 1));
407
407
 
408
408
  const { chromium, devices } = await loadPlaywright();
409
- const browser = await chromium.launch(webBrowserLaunchOptions(process.env, {}));
409
+ const browser = await launchWebBrowser(chromium, webBrowserLaunchOptions(process.env, {}));
410
410
  const capture = capturesDir ? openCapture(capturesDir, captureId || auditCaptureId()) : null;
411
411
  const provenance = capture ? writeCaptureProvenance(capture.dir, { kind: "audit", platform: "web", target: start.href }) : null;
412
412
  try {
@@ -536,13 +536,72 @@ export function webTransitionOrigin(pendingNavigation, currentScreen) {
536
536
  return pendingNavigation?.fromScreen || currentScreen || null;
537
537
  }
538
538
 
539
+ // Playwright reports a browser that dies at startup as "Target page, context or browser has been
540
+ // closed" and keeps the real reason in its debug log (DEBUG=pw:browser). Capture the browser's own
541
+ // stderr through a logger so the reason reaches the ordinary error, without launch arguments
542
+ // ("<launching>"), env, or unrelated protocol chatter.
543
+ export function browserStartupReason(lines) {
544
+ const reasons = [];
545
+ for (const raw of lines) {
546
+ for (const part of String(raw).split("\n")) {
547
+ const line = part.replace(/^\[\d+:\d+:\d+\/\d+\.\d+:/, "[").trim();
548
+ if (!line || /^<(launching|launched|gracefully|kill)/i.test(line) || /^<\w+ pid=/.test(line)) continue;
549
+ if (/\b(error|fail(ed)?|denied|fatal|cannot|can't|unable|sandbox|missing|not found|no such)\b/i.test(line) && !reasons.includes(line)) reasons.push(line.slice(0, 300));
550
+ }
551
+ }
552
+ return reasons.slice(0, 5);
553
+ }
554
+
555
+ // An approved browser environment for runs where the browser tapp would start itself is not allowed
556
+ // to start (a restricted macOS runner kills Chromium with SIGTRAP at its Mach-port check-in).
557
+ // TAPP_BROWSER_ENDPOINT http(s)/ws URL on this machine of a Chromium that something outside the
558
+ // restriction already started with --remote-debugging-port; tapp attaches.
559
+ // TAPP_BROWSER_EXECUTABLE path of an approved Chromium/Chrome binary tapp starts instead of its own.
560
+ export function approvedBrowserEndpoint(environment = process.env) {
561
+ const raw = String(environment.TAPP_BROWSER_ENDPOINT || "").trim();
562
+ if (!raw) return null;
563
+ let url;
564
+ try { url = new URL(raw); } catch { throw new Error("TAPP_BROWSER_ENDPOINT is not a URL"); }
565
+ if (!/^(https?|wss?):$/.test(url.protocol) || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)) {
566
+ throw new Error("TAPP_BROWSER_ENDPOINT must be a http or ws URL on this machine (127.0.0.1 or localhost)");
567
+ }
568
+ if (environment.TAPP_ENFORCE_PUBLIC_EGRESS === "1") {
569
+ throw new Error("TAPP_BROWSER_ENDPOINT cannot be used under the public egress policy: tapp cannot enforce the proxy on a browser it did not start");
570
+ }
571
+ return raw;
572
+ }
573
+
574
+ export async function launchWebBrowser(chromium, options, environment = process.env) {
575
+ const endpoint = approvedBrowserEndpoint(environment);
576
+ if (endpoint) return await chromium.connectOverCDP(endpoint);
577
+ const lines = [];
578
+ const logger = {
579
+ isEnabled: (name) => name === "browser",
580
+ log: (name, _severity, message) => { if (name === "browser") lines.push(String(message)); },
581
+ };
582
+ try {
583
+ return await chromium.launch({ ...options, logger });
584
+ } catch (error) {
585
+ const reasons = browserStartupReason(lines);
586
+ if (reasons.length) {
587
+ const first = String(error?.message || error).split("\n")[0];
588
+ const wrapped = new Error(`${first}\nBrowser startup reason: ${reasons.join(" | ")}`);
589
+ wrapped.cause = error;
590
+ throw wrapped;
591
+ }
592
+ throw error;
593
+ }
594
+ }
595
+
539
596
  export function webBrowserLaunchOptions(environment = process.env, { watch = false } = {}) {
540
597
  const browserProxy = String(environment.TAPP_BROWSER_PROXY_SERVER || "").trim();
541
598
  if (environment.TAPP_ENFORCE_PUBLIC_EGRESS === "1" && !/^http:\/\/127\.0\.0\.1:\d+$/.test(browserProxy)) {
542
599
  throw new Error("public egress policy proxy is required");
543
600
  }
601
+ const executable = String(environment.TAPP_BROWSER_EXECUTABLE || "").trim();
544
602
  return {
545
603
  headless: !watch,
604
+ ...(executable ? { executablePath: executable } : {}),
546
605
  ...(watch ? { slowMo: 200 } : {}),
547
606
  ...(browserProxy ? { proxy: { server: browserProxy, bypass: "<-loopback>" } } : {}),
548
607
  args: browserProxy ? [
@@ -696,7 +755,7 @@ export async function inspectWebPage({ url, timeoutMs = NAV_TIMEOUT_MS, screensh
696
755
  if (!/^https?:$/.test(target.protocol)) throw new Error("Web inspection needs a valid http(s) URL");
697
756
 
698
757
  const { chromium, devices } = await loadPlaywright();
699
- const browser = await chromium.launch(webBrowserLaunchOptions());
758
+ const browser = await launchWebBrowser(chromium, webBrowserLaunchOptions());
700
759
  try {
701
760
  const context = await browser.newContext(webContextOptions({ device, viewport, devices }));
702
761
  const page = await context.newPage();
@@ -872,7 +931,7 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
872
931
  };
873
932
 
874
933
  const { chromium, devices } = await loadPlaywright();
875
- const browser = await chromium.launch(webBrowserLaunchOptions(process.env, { watch }));
934
+ const browser = await launchWebBrowser(chromium, webBrowserLaunchOptions(process.env, { watch }));
876
935
  const captureProfile = webContextOptions({ device, viewport, devices });
877
936
  // Evidence is only comparable when the capture conditions are on record: a desktop run and a
878
937
  // phone run legitimately disagree about which nav links exist, and a baseline diff across