@aarwitz/tapp 0.35.6 → 0.35.8

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.
@@ -25,6 +25,24 @@ export function parseFlowSteps(logText) {
25
25
  return steps;
26
26
  }
27
27
 
28
+ /**
29
+ * When the flow's steps actually began, on the wall clock, or null.
30
+ *
31
+ * The CLI cannot use its own "now": on iOS it spawns xcodebuild, which builds and launches the
32
+ * harness before a single step runs — most of a minute in which the recorder is already rolling.
33
+ * The runner says when it really started, and this reads it back.
34
+ */
35
+ export function flowStartedAtEpochMs(logText) {
36
+ for (const line of String(logText || "").split("\n")) {
37
+ if (!line.startsWith("OCQA_FLOW_CLOCK:")) continue;
38
+ try {
39
+ const value = Number(JSON.parse(line.slice("OCQA_FLOW_CLOCK:".length)).startedAtEpochMs);
40
+ if (Number.isFinite(value) && value > 0) return value;
41
+ } catch { /* a truncated line */ }
42
+ }
43
+ return null;
44
+ }
45
+
28
46
  /**
29
47
  * The same steps expressed in the recording's seconds.
30
48
  *
@@ -55,13 +73,19 @@ export function sidecarPath(videoPath) {
55
73
  return path.join(parsed.dir, `${parsed.name}.steps.json`);
56
74
  }
57
75
 
58
- export function writeStepsSidecar(videoPath, steps, { flowStartedAtMs, recordingStartedAtMs, holdMs = 0, name = "" } = {}) {
76
+ export function writeStepsSidecar(videoPath, steps, { flowStartedAtMs, recordingStartedAtMs, holdMs = 0, name = "", videoDurationMs = null } = {}) {
59
77
  const inVideoTime = stepsInVideoTime(steps, { flowStartedAtMs, recordingStartedAtMs });
78
+ // What a cut must not run past. Prefer the finished file's own duration: the tail is produced by
79
+ // re-encoding, which lands within about a second of what was asked for, and a sidecar that
80
+ // claims more than the file holds sends an editor past the end.
81
+ const computedEnd = inVideoTime.length ? inVideoTime[inVideoTime.length - 1].end + holdMs / 1000 : 0;
82
+ const endsAt = Number.isFinite(videoDurationMs) && videoDurationMs > 0
83
+ ? Math.min(computedEnd, videoDurationMs / 1000)
84
+ : computedEnd;
60
85
  const out = {
61
86
  video: path.basename(String(videoPath)),
62
87
  name,
63
- // What a cut should not run past: the last step's end plus whatever hold was asked for.
64
- endsAt: inVideoTime.length ? Number((inVideoTime[inVideoTime.length - 1].end + holdMs / 1000).toFixed(3)) : 0,
88
+ endsAt: Number(endsAt.toFixed(3)),
65
89
  holdSeconds: holdMs / 1000,
66
90
  steps: inVideoTime,
67
91
  };
@@ -44,8 +44,12 @@ export const FLOW_ACTIONS = Object.freeze([
44
44
  { action: "tap", target: "a visible label / accessibility id", passes: "the control was found and tapped; coordinates are not accepted — use the session's tap-by-point to learn the label" },
45
45
  { action: "type", target: "{field, value}", passes: "the field was found and now holds the value ($TEST_EMAIL/$TEST_PASSWORD substitute)" },
46
46
  { action: "login", target: "{email, password} (defaults to $TEST_EMAIL/$TEST_PASSWORD)", passes: "credentials were entered and submitted and the login form went away" },
47
- { action: "swipe", target: "up | down | left | right", passes: "the gesture was performed" },
47
+ { action: "swipe", target: "up | down | left | right (web: + {within} to scroll a drawer or modal)", passes: "the gesture was performed, and on web the thing actually moved" },
48
+ { action: "press", target: "a key (`press: ArrowRight`), or {key, target} to focus a control first (+ {times}); not `on:`, which YAML reads as true", passes: "the key was pressed; web only — this is what drives a slider or a shortcut" },
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
+ { action: "screenshot", target: "a name for the picture", passes: "a viewport-sized picture was saved beside the run's evidence; web only" },
48
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" },
49
53
  { action: "wait", target: "milliseconds (fixed pause; prefer wait_for)", passes: "always" },
50
54
  { action: "wait_for", target: "label / text (+ per-step timeoutMs/timeout; flow-level timeoutMs sets the default)", passes: "the element appeared before the timeout" },
51
55
  { action: "assert_screen", target: "the detected SCREEN TITLE (navigation bar / heading), not arbitrary text", passes: "the current screen's title equals the target" },
@@ -75,8 +79,18 @@ export function isOptionalStep(step) {
75
79
  return Boolean(step?.params?.optional === true || step?.params?.optional === "true");
76
80
  }
77
81
 
82
+ /** What `alerts:` may say. Anything else is a typo that would silently do nothing (TM-497). */
83
+ export const ALERT_MODES = Object.freeze(["allow", "dismiss"]);
84
+
78
85
  export function validateFlowSteps(flow, platform = inferFlowPlatform(flow)) {
79
86
  const errors = [];
87
+ const alerts = String(flow?.alerts ?? "").trim();
88
+ if (alerts && !ALERT_MODES.includes(alerts.toLowerCase())) {
89
+ errors.push(`alerts: '${alerts}' is not a setting — use ${ALERT_MODES.map((m) => `alerts: ${m}`).join(" or ")}`);
90
+ }
91
+ if (alerts && platform !== "ios") {
92
+ errors.push(`alerts: applies to iOS flows, where a system alert belongs to the operating system rather than the app (this flow is ${platform})`);
93
+ }
80
94
  const steps = Array.isArray(flow?.steps) ? flow.steps : [];
81
95
  steps.forEach((raw, i) => {
82
96
  const step = normalizeFlowStep(raw);
@@ -90,7 +104,7 @@ export function validateFlowSteps(flow, platform = inferFlowPlatform(flow)) {
90
104
  if (step.action === "tap" && /^\s*-?\d+(\.\d+)?\s*,\s*-?\d+(\.\d+)?\s*$/.test(step.target)) {
91
105
  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)`);
92
106
  }
93
- if (["tap", "wait_for", "assert_screen", "assert_exists", "assert_absent"].includes(step.action) && !step.target.trim()) {
107
+ if (["tap", "wait_for", "assert_screen", "assert_exists", "assert_absent", "open_url"].includes(step.action) && !step.target.trim()) {
94
108
  errors.push(`step ${n}: ${step.action} needs a target`);
95
109
  }
96
110
  if (step.action === "type" && (!step.target.trim() || !("value" in (step.params || {})))) {
@@ -182,6 +196,10 @@ export class FlowLog {
182
196
  this.criticality = flow.releaseContract?.criticality || "";
183
197
  this.kind = this.contract ? "release-contract" : flow.kind || "flow";
184
198
  this.emit(`OCQA_FLOW_RESULT:started total=${flow.steps.length} name=${flow.name || "flow"} kind=${this.kind}${this.contract ? ` contract=${this.contract}` : ""}`);
199
+ // When the steps actually began, on the wall clock (TM-497). Step times are relative to this,
200
+ // and a recorder started by the CLI knows nothing else about it: on iOS the CLI's own "now" is
201
+ // most of a minute earlier, because building and launching the harness happens in between.
202
+ this.emit(`OCQA_FLOW_CLOCK:${JSON.stringify({ startedAtEpochMs: Date.now() })}`);
185
203
  }
186
204
 
187
205
  emit(line) {
@@ -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
  }
@@ -0,0 +1,273 @@
1
+ // tapp owning the screen recording, instead of a wrapper script starting `simctl` by hand (TM-497).
2
+ //
3
+ // Making the 11/7 demo videos cost more on the recording side than on the app side: eight takes,
4
+ // three re-recorded because of one-time system alerts, one because the simulator had shut itself
5
+ // down and left a file with no moov atom, and every take ending on a final screen about one frame
6
+ // long. The step times came from the wrapper's own clock, which ran ahead of the picture by a
7
+ // varying amount.
8
+ //
9
+ // WHAT MEASUREMENT SHOWED, and why this is not a few lines in the CLI (2026-11-13, iPhone 17 Pro):
10
+ //
11
+ // • `simctl io recordVideo` RECORDS CHANGES, NOT FRAMES. A still screen produces almost nothing:
12
+ // a take over a motionless Settings screen with two status-bar changes in it came out as five
13
+ // frames — one at 0, two at each change — over 8.1 seconds. A take over an animating map came
14
+ // out as 345. So the file's DURATION ENDS AT THE LAST VISUAL CHANGE, not when the recorder was
15
+ // stopped. That is the real reason a demo's final screen is one frame long, and it also means
16
+ // `stoppedAt - duration` is wrong by however long the last screen was still.
17
+ //
18
+ // • NOTHING IS WRITTEN UNTIL THE END. The file appears 134 ms after spawning and stays at zero
19
+ // bytes until the recorder exits, so watching it grow cannot time the first frame either.
20
+ //
21
+ // • THE START LAG IS REAL AND VARIES: 1.4 s, 2.0 s and 3.9 s across three takes on one machine.
22
+ // It cannot be assumed, which is exactly what the old wrapper did.
23
+ //
24
+ // So the first frame is timed by putting a mark in the recording at a known instant: before the
25
+ // flow starts, while the screen is still, tapp changes the status bar. That forces a frame. The
26
+ // opening cluster of changes is therefore the mark, its position is read straight out of the
27
+ // container with ffprobe — no picture analysis — and everything else is arithmetic.
28
+
29
+ import fs from "node:fs";
30
+ import path from "node:path";
31
+ import { spawn, spawnSync } from "node:child_process";
32
+
33
+ /** How long to wait for the recorder to finalise the file after it is asked to stop. */
34
+ const FINALISE_TIMEOUT_MS = 15_000;
35
+
36
+ /** Let the recorder actually begin before marking it; the mark is useless if it lands first. */
37
+ const MARK_AFTER_MS = 1200;
38
+
39
+ /**
40
+ * The mark is TWO status-bar changes, not one, and the second is the one timed against.
41
+ *
42
+ * One was not enough: the second recorded flow of the day put every step 19 seconds late because
43
+ * the status bar already read 9:41 from the run before, so setting it to 9:41 changed nothing, no
44
+ * frame was written, and the first change in the file was the app launching instead. Setting a
45
+ * second, different value right after is guaranteed to change something whatever was there.
46
+ */
47
+ const MARK_TIMES = ["9:41", "9:42"];
48
+ const MARK_GAP_MS = 500;
49
+
50
+ /** Frames this close to the first mark belong to the mark, not to anything the app did. */
51
+ const MARK_CLUSTER_S = 1.0;
52
+
53
+ const sh = (cmd, args, timeout = 20_000) => spawnSync(cmd, args, { encoding: "utf8", timeout });
54
+
55
+ /** Is ffprobe here? `--record` needs it to read where the mark landed; say so rather than guess. */
56
+ export function recorderToolingError({ run = sh } = {}) {
57
+ const probe = run("ffprobe", ["-version"], 5_000);
58
+ if (probe.status === 0) return "";
59
+ return "--record needs ffprobe (part of ffmpeg) to time the recording against the flow: brew install ffmpeg";
60
+ }
61
+
62
+ /**
63
+ * The status-bar time override currently in force, or "" when there is none.
64
+ *
65
+ * The mark changes the clock, so whatever was there has to be put back: 9:41 is the clock people
66
+ * set deliberately for screenshots, and clearing it after every take quietly undid that (Linux's
67
+ * check of 10f0a79). Overriding the time alone leaves the other fields — cell bars, operator —
68
+ * exactly as they were, so only the time needs remembering.
69
+ */
70
+ export function statusBarTime(udid, { run = sh } = {}) {
71
+ const listed = run("xcrun", ["simctl", "status_bar", udid, "list"]);
72
+ const match = /^\s*Time:\s*(.+?)\s*$/m.exec(String(listed.stdout || ""));
73
+ return match ? match[1] : "";
74
+ }
75
+
76
+ /** Put the clock back the way the mark found it: the author's override, or none at all. */
77
+ export function restoreStatusBar(udid, previousTime, { run = sh } = {}) {
78
+ if (previousTime) run("xcrun", ["simctl", "status_bar", udid, "override", "--time", previousTime]);
79
+ else run("xcrun", ["simctl", "status_bar", udid, "clear"]);
80
+ }
81
+
82
+ /** Every frame's position in the finished file, in seconds, in order. */
83
+ export function framePositions(file, { run = sh } = {}) {
84
+ const probe = run("ffprobe", ["-v", "error", "-select_streams", "v", "-show_entries", "packet=pts_time", "-of", "csv=p=0", String(file)]);
85
+ return String(probe.stdout || "")
86
+ .split("\n")
87
+ // A blank line is not a frame at zero: Number("") is 0, which would add a phantom opening
88
+ // frame to every take and shift the mark.
89
+ .map((line) => line.trim()).filter(Boolean)
90
+ .map(Number).filter((value) => Number.isFinite(value))
91
+ .sort((a, b) => a - b);
92
+ }
93
+
94
+ /**
95
+ * The duration ffprobe reports, in milliseconds, or null.
96
+ *
97
+ * null means "do not claim to know": a file with no readable duration is the broken case — a
98
+ * recording killed before its moov atom was written — and inventing a number for it would put
99
+ * every step in the sidecar at the wrong second.
100
+ */
101
+ export function videoDurationMs(file, { run = sh } = {}) {
102
+ const probe = run("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", String(file)]);
103
+ const seconds = Number(String(probe.stdout || "").trim());
104
+ return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1000) : null;
105
+ }
106
+
107
+ /**
108
+ * When the recorder's first frame was captured, on the caller's clock.
109
+ *
110
+ * `markAtMs` is when tapp forced the screen to change; `frames` are the positions ffprobe reports.
111
+ * The opening frame sits at 0 and the next one is the mark, so the first frame was that many
112
+ * seconds before the mark. Returns null when there is no second frame to read — a take where
113
+ * nothing ever changed — rather than guessing.
114
+ */
115
+ export function firstFrameAtMs(frames, markAtMs) {
116
+ const changes = frames.filter((position) => position > 0.001);
117
+ if (!changes.length || !Number.isFinite(markAtMs)) return null;
118
+ // The mark is two changes a known moment apart, and `markAtMs` is the second. Either both wrote
119
+ // a frame or only the second did, so the mark is the last frame of the opening cluster.
120
+ const cluster = changes.filter((position) => position <= changes[0] + MARK_CLUSTER_S);
121
+ return Math.round(markAtMs - cluster[cluster.length - 1] * 1000);
122
+ }
123
+
124
+ /**
125
+ * Hold the last screen for `holdMs` by extending the finished file, and give it a steady frame
126
+ * rate while doing so.
127
+ *
128
+ * Keeping the recorder running longer does NOT do this: the recorder writes a frame when the
129
+ * screen changes, so a still final screen produces nothing and the file still ends at the last
130
+ * change. Measured on a take that ran four seconds past its last change: duration 7.500 s, last
131
+ * frame 7.497 s. The tail has to be added to the file afterwards.
132
+ *
133
+ * Cloning the last frame is also what makes the result ordinary to edit: what simctl writes is
134
+ * variable-rate — five frames over eight seconds on a still screen — which editors scrub badly.
135
+ *
136
+ * It is also what makes the step map land inside the file at all. A flow whose last step sat on a
137
+ * motionless screen left the recording ending eleven seconds before the flow did, so the sidecar
138
+ * correctly placed that step past the end of the video. `tailMsFor` works out what is missing.
139
+ */
140
+ export function tailMsFor({ durationMs, lastStepEndMs, holdMs = 0 }) {
141
+ const missing = Number.isFinite(lastStepEndMs) ? Math.max(0, Math.round(lastStepEndMs - durationMs)) : 0;
142
+ return missing + Math.max(0, Math.round(holdMs));
143
+ }
144
+
145
+ export function padTail(file, addMs, { run = sh } = {}) {
146
+ if (!(addMs > 0)) return { ok: true, padded: false, durationMs: videoDurationMs(file, { run }), error: "" };
147
+ const target = path.resolve(file);
148
+ const before = videoDurationMs(target, { run });
149
+ if (before === null) return { ok: false, padded: false, durationMs: null, error: `cannot hold the last screen of ${target}: its duration is unreadable` };
150
+ const totalSeconds = (before + addMs) / 1000;
151
+ const temp = `${target}.padded.mp4`;
152
+ const result = run("ffmpeg", [
153
+ "-y", "-v", "error", "-i", target,
154
+ // stop_duration is generous and `-t` makes the cut: asking tpad alone for the exact amount
155
+ // came out short on a variable-rate input (22.97s where 28.6s was asked for), because what
156
+ // ffmpeg takes the input's duration to be is not what the container reports.
157
+ // `fps=30` BEFORE tpad, and never `-r 30`. As an output option `-r` renumbers the frames it is
158
+ // given at a fixed rate, which on a variable-rate input throws the real timing away: a 36.9s
159
+ // capture of 534 frames came out as 17.8s of picture, and every step in the map then pointed
160
+ // at the wrong screen. The `fps` filter resamples against the timestamps instead, so a still
161
+ // stretch is filled with repeats and the clock survives.
162
+ "-vf", `fps=30,tpad=stop_mode=clone:stop_duration=${(addMs / 1000 + 5).toFixed(3)}`,
163
+ "-t", totalSeconds.toFixed(3),
164
+ "-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p", temp,
165
+ ], 300_000);
166
+ if (result.status !== 0 || !fs.existsSync(temp)) {
167
+ try { fs.unlinkSync(temp); } catch { /* nothing to clean up */ }
168
+ return { ok: false, padded: false, durationMs: before, error: `could not hold the last screen: ${String(result.stderr || "").trim().split("\n")[0] || "ffmpeg failed"}` };
169
+ }
170
+ fs.renameSync(temp, target);
171
+ // Report what the file actually came out as, never what was asked for.
172
+ return { ok: true, padded: true, durationMs: videoDurationMs(target, { run }), error: "" };
173
+ }
174
+
175
+ /**
176
+ * Put the simulator and the host recorder into a state a recording can start from.
177
+ *
178
+ * Returns what it had to repair, so the run can say so in one line — silently fixing something
179
+ * that cost three re-records is how it stays invisible the next time.
180
+ */
181
+ export function prepareRecorder(udid, { run = sh } = {}) {
182
+ const repaired = [];
183
+
184
+ // A device that shut itself down since the last run: the recorder attaches and produces a file
185
+ // no player will open. This was one of the 11/7 re-records.
186
+ const list = run("xcrun", ["simctl", "list", "devices", "-j"]);
187
+ let booted = false;
188
+ try {
189
+ const devices = JSON.parse(list.stdout || "{}").devices || {};
190
+ booted = Object.values(devices).flat().some((d) => d.udid === udid && d.state === "Booted");
191
+ } catch { /* fall through to the boot attempt */ }
192
+ if (!booted) {
193
+ const boot = run("xcrun", ["simctl", "boot", udid], 120_000);
194
+ const already = /current state: Booted/i.test(`${boot.stdout}${boot.stderr}`);
195
+ if (boot.status !== 0 && !already) {
196
+ return { ok: false, repaired, error: `the simulator ${udid} is not booted and would not boot: ${String(boot.stderr || "").trim().split("\n")[0]}` };
197
+ }
198
+ if (!already) repaired.push("booted the simulator, which had shut itself down");
199
+ run("xcrun", ["simctl", "bootstatus", udid], 180_000);
200
+ }
201
+
202
+ // "Host recording is already in progress": a recorder from a killed run still holds the device.
203
+ const probe = run("xcrun", ["simctl", "io", udid, "recordVideo", "--help"]);
204
+ if (/already in progress/i.test(`${probe.stdout}${probe.stderr}`)) {
205
+ run("pkill", ["-INT", "-f", `simctl io ${udid} recordVideo`]);
206
+ repaired.push("stopped a recorder left running by an earlier run");
207
+ }
208
+ return { ok: true, repaired, error: "" };
209
+ }
210
+
211
+ /**
212
+ * Start recording the simulator's screen. The returned handle stops it and says when its first
213
+ * frame was captured, on the caller's clock.
214
+ *
215
+ * The mark is placed on a still screen before the flow starts, which is why `startRecording` is
216
+ * called before the app is driven and not after.
217
+ */
218
+ export function startRecording({ udid, out, holdMs = 0, now = () => Date.now(), spawnFn = spawn, run = sh }) {
219
+ const file = path.resolve(out);
220
+ fs.mkdirSync(path.dirname(file), { recursive: true });
221
+ // --force: the caller named this path, and refusing to overwrite leaves a half-finished take
222
+ // where the one just recorded should be.
223
+ const child = spawnFn("xcrun", ["simctl", "io", udid, "recordVideo", "--codec", "h264", "--force", file], { stdio: ["ignore", "pipe", "pipe"] });
224
+ let stderr = "";
225
+ child.stderr?.on("data", (chunk) => { stderr += String(chunk); });
226
+ const exited = new Promise((resolve) => child.once("exit", () => resolve()));
227
+
228
+ // Remembered before the mark touches it, restored after the take.
229
+ const previousTime = statusBarTime(udid, { run });
230
+
231
+ // The mark: status-bar changes at a known instant, on a still screen, so the first change in
232
+ // the finished file is this and nothing else.
233
+ const marked = new Promise((resolve) => setTimeout(() => {
234
+ run("xcrun", ["simctl", "status_bar", udid, "override", "--time", MARK_TIMES[0]]);
235
+ setTimeout(() => {
236
+ run("xcrun", ["simctl", "status_bar", udid, "override", "--time", MARK_TIMES[1]]);
237
+ resolve(now());
238
+ }, MARK_GAP_MS);
239
+ }, MARK_AFTER_MS));
240
+
241
+ return {
242
+ file,
243
+ /** Wait until the recording has been marked; the flow must not start before that. */
244
+ ready: () => marked,
245
+ async stop() {
246
+ const markAtMs = await marked;
247
+ child.kill("SIGINT");
248
+ // Put the clock back the way it was: the mark is tapp's doing, not the simulator's state.
249
+ // Restored rather than cleared, because clearing wipes a 9:41 somebody set for screenshots.
250
+ // Done after the recorder stops, so it is not in the picture.
251
+ restoreStatusBar(udid, previousTime, { run });
252
+ await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, FINALISE_TIMEOUT_MS))]);
253
+ const durationMs = videoDurationMs(file, { run });
254
+ if (durationMs === null) {
255
+ return {
256
+ file, ok: false, durationMs: null, startedAtMs: null, frames: 0,
257
+ error: `the recording at ${file} has no readable duration — it was cut off before it could be finished${stderr.trim() ? `: ${stderr.trim().split("\n")[0]}` : ""}`,
258
+ };
259
+ }
260
+ const frames = framePositions(file, { run });
261
+ const startedAtMs = firstFrameAtMs(frames, markAtMs);
262
+ if (startedAtMs === null) {
263
+ return {
264
+ file, ok: false, durationMs, startedAtMs: null, frames: frames.length,
265
+ error: "the recording never changed after it started, so there is no mark to time it against — the screen may have been frozen",
266
+ };
267
+ }
268
+ // Padding is the caller's to do: how much tail is missing depends on when the flow's last
269
+ // step ended, which only the caller knows. See `padTail`.
270
+ return { file, ok: true, durationMs, startedAtMs, frames: frames.length, error: "" };
271
+ },
272
+ };
273
+ }
@@ -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 {
@@ -317,7 +317,19 @@ async function tapWebText(page, text, timeoutMs) {
317
317
  return true;
318
318
  } catch {}
319
319
  }
320
- throw new Error(`Could not tap visible text “${requested}”`);
320
+ // TM-593: a journey's `tap` takes an id, so `tapp look --tap open-filters` failed on a target a
321
+ // flow presses happily — two ways to name the same control, one of which only looked at visible
322
+ // text. Fall back to the flow's own matcher, which also knows ids, test ids, labels and
323
+ // same-origin frames. Imported lazily because web-flow.js imports this module.
324
+ try {
325
+ const { locateWebElement } = await import("./web-flow.js");
326
+ const el = await locateWebElement(page, requested);
327
+ if (el) {
328
+ await el.click({ timeout: Math.min(timeoutMs, 5_000) });
329
+ return true;
330
+ }
331
+ } catch { /* fall through to the honest error below */ }
332
+ throw new Error(`Could not tap “${requested}”: no visible text, id or label matched`);
321
333
  }
322
334
 
323
335
  // npx installs Tapp into its own cache, so a plain import("playwright") only resolves
@@ -524,6 +536,42 @@ export function webTransitionOrigin(pendingNavigation, currentScreen) {
524
536
  return pendingNavigation?.fromScreen || currentScreen || null;
525
537
  }
526
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
+ export async function launchWebBrowser(chromium, options) {
556
+ const lines = [];
557
+ const logger = {
558
+ isEnabled: (name) => name === "browser",
559
+ log: (name, _severity, message) => { if (name === "browser") lines.push(String(message)); },
560
+ };
561
+ try {
562
+ return await chromium.launch({ ...options, logger });
563
+ } catch (error) {
564
+ const reasons = browserStartupReason(lines);
565
+ if (reasons.length) {
566
+ const first = String(error?.message || error).split("\n")[0];
567
+ const wrapped = new Error(`${first}\nBrowser startup reason: ${reasons.join(" | ")}`);
568
+ wrapped.cause = error;
569
+ throw wrapped;
570
+ }
571
+ throw error;
572
+ }
573
+ }
574
+
527
575
  export function webBrowserLaunchOptions(environment = process.env, { watch = false } = {}) {
528
576
  const browserProxy = String(environment.TAPP_BROWSER_PROXY_SERVER || "").trim();
529
577
  if (environment.TAPP_ENFORCE_PUBLIC_EGRESS === "1" && !/^http:\/\/127\.0\.0\.1:\d+$/.test(browserProxy)) {
@@ -684,7 +732,7 @@ export async function inspectWebPage({ url, timeoutMs = NAV_TIMEOUT_MS, screensh
684
732
  if (!/^https?:$/.test(target.protocol)) throw new Error("Web inspection needs a valid http(s) URL");
685
733
 
686
734
  const { chromium, devices } = await loadPlaywright();
687
- const browser = await chromium.launch(webBrowserLaunchOptions());
735
+ const browser = await launchWebBrowser(chromium, webBrowserLaunchOptions());
688
736
  try {
689
737
  const context = await browser.newContext(webContextOptions({ device, viewport, devices }));
690
738
  const page = await context.newPage();
@@ -860,7 +908,7 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
860
908
  };
861
909
 
862
910
  const { chromium, devices } = await loadPlaywright();
863
- const browser = await chromium.launch(webBrowserLaunchOptions(process.env, { watch }));
911
+ const browser = await launchWebBrowser(chromium, webBrowserLaunchOptions(process.env, { watch }));
864
912
  const captureProfile = webContextOptions({ device, viewport, devices });
865
913
  // Evidence is only comparable when the capture conditions are on record: a desktop run and a
866
914
  // phone run legitimately disagree about which nav links exist, and a baseline diff across