@aarwitz/tapp 0.35.5 → 0.35.7

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,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
+ }
@@ -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
@@ -2,7 +2,7 @@
2
2
  // driver; Tapp owns the shared Flow semantics and OCQA evidence protocol.
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
- import { FlowLog, flowVariables, normalizeFlowStep, substituteFlowValue } from "./flow-runtime.js";
5
+ import { FlowLog, flowVariables, normalizeFlowStep, substituteFlowValue, isOptionalStep } from "./flow-runtime.js";
6
6
  import { loadPlaywright, webContextOptions } from "./web-explorer.js";
7
7
  import { findSignInSubmit } from "./sign-in.js";
8
8
 
@@ -203,7 +203,7 @@ export function distillPlaywrightFailure(message) {
203
203
  return `${firstLine} — ${reason}`;
204
204
  }
205
205
 
206
- export async function executeWebFlowStep({ page, step, vars = {}, defaultTimeout = DEFAULT_TIMEOUT }) {
206
+ export async function executeWebFlowStep({ page, step, vars = {}, defaultTimeout = DEFAULT_TIMEOUT, stepScreenshotDir = "" }) {
207
207
  const raw = normalizeFlowStep(step);
208
208
  const action = raw.action;
209
209
  const target = substituteFlowValue(raw.target, vars);
@@ -236,9 +236,117 @@ export async function executeWebFlowStep({ page, step, vars = {}, defaultTimeout
236
236
  await submit.locator.click();
237
237
  await page.waitForTimeout(400);
238
238
  if (await password.isVisible().catch(() => false)) throw new Error("submit left the app on the login screen");
239
+ } else if (action === "press") {
240
+ // TM-593: a journey could not press a key, so anything a keyboard drives — a slider, a
241
+ // shortcut, a combobox — was unreachable. `press: ArrowRight` or
242
+ // `press: { key: ArrowRight, on: <target>, times: 5 }`.
243
+ const key = String(raw.params.key ?? value ?? target ?? "").trim();
244
+ if (!key) throw new Error("press needs a key, e.g. `press: ArrowRight`");
245
+ // `on:` is unusable as a key here: YAML 1.1 reads a bare `on` as the boolean true, so
246
+ // `on: price-max` arrives as {"true": "price-max"} and the target silently vanishes. Say so
247
+ // rather than pressing into the void and passing, which is what this step did first.
248
+ if (raw.params.true !== undefined) {
249
+ throw new Error("press takes `target:`, not `on:` — YAML reads a bare `on` as true, so the target is lost");
250
+ }
251
+ // Only the object form can name a control to focus. In the string form — `press: ArrowRight`,
252
+ // which is the form the story and the reporter both asked for — normalizeFlowStep puts the
253
+ // key in `target` as well, so reading a focus target from there looked for a control called
254
+ // "ArrowRight" and the step failed (Linux's check of 6d8d531). A bare key presses wherever
255
+ // the focus already is, which is what a shortcut means.
256
+ const onTarget = "key" in raw.params
257
+ ? substituteFlowValue(String(raw.target || raw.params.onTarget || ""), vars)
258
+ : "";
259
+ const times = Math.max(1, Math.min(50, Number(raw.params.times) || 1));
260
+ const el = onTarget ? await locateWebElement(page, onTarget) : null;
261
+ if (onTarget && !el) throw new Error(`could not find ‘${onTarget}’ to press ${key} on`);
262
+ if (el) await el.focus();
263
+ for (let i = 0; i < times; i += 1) {
264
+ if (el) await el.press(key);
265
+ else await page.keyboard.press(key);
266
+ }
267
+ } else if (action === "drag") {
268
+ // TM-593: `type` on a range input calls fill(), which sets the value without the handle
269
+ // ever moving, so nothing the page listens for fires and the step proves nothing. A drag
270
+ // moves it the way a person does. `drag: { from: <target>, by: [dx, dy] }` or `{ from, to }`.
271
+ const from = substituteFlowValue(String(raw.params.from ?? target ?? ""), vars);
272
+ if (!from) throw new Error("drag needs `from`, e.g. `drag: { from: price-min, by: [60, 0] }`");
273
+ const handle = await locateWebElement(page, from);
274
+ if (!handle) throw new Error(`could not find ‘${from}’ to drag`);
275
+ // Playwright's own click() scrolls a control into view first; raw mouse moves do not, so a
276
+ // handle below the fold would be "dragged" at coordinates pointing somewhere else entirely —
277
+ // passing, and moving nothing.
278
+ await handle.scrollIntoViewIfNeeded().catch(() => {});
279
+ const start = await handle.boundingBox();
280
+ if (!start) throw new Error(`‘${from}’ is not on screen, so it cannot be dragged`);
281
+ const startX = start.x + start.width / 2;
282
+ const startY = start.y + start.height / 2;
283
+ let endX;
284
+ let endY;
285
+ const to = substituteFlowValue(String(raw.params.to ?? ""), vars);
286
+ if (to) {
287
+ const dest = await locateWebElement(page, to);
288
+ if (dest) await dest.scrollIntoViewIfNeeded().catch(() => {});
289
+ const box = dest && await dest.boundingBox();
290
+ if (!box) throw new Error(`could not find ‘${to}’ to drag onto`);
291
+ endX = box.x + box.width / 2;
292
+ endY = box.y + box.height / 2;
293
+ } else {
294
+ const by = Array.isArray(raw.params.by) ? raw.params.by : [Number(raw.params.by) || 0, 0];
295
+ endX = startX + (Number(by[0]) || 0);
296
+ endY = startY + (Number(by[1]) || 0);
297
+ }
298
+ await page.mouse.move(startX, startY);
299
+ await page.mouse.down();
300
+ // In steps, because a single jump is not a drag to a listener watching movement.
301
+ const steps = 12;
302
+ for (let i = 1; i <= steps; i += 1) {
303
+ await page.mouse.move(startX + ((endX - startX) * i) / steps, startY + ((endY - startY) * i) / steps);
304
+ }
305
+ await page.mouse.up();
239
306
  } else if (action === "swipe") {
307
+ // TM-593: this only ever scrolled the window, so content inside a drawer or modal could not
308
+ // be brought into view and the step passed having moved nothing. With a target it scrolls
309
+ // that container, and either way it fails when nothing actually moved.
240
310
  const dy = target.toLowerCase() === "down" ? -600 : 600;
241
- await page.evaluate((y) => window.scrollBy({ top: y, behavior: "instant" }), dy);
311
+ const within = substituteFlowValue(String(raw.params.within ?? raw.params.in ?? ""), vars);
312
+ if (within) {
313
+ const box = await locateWebElement(page, within);
314
+ if (!box) throw new Error(`could not find ‘${within}’ to scroll`);
315
+ const moved = await box.evaluate((node, y) => {
316
+ const before = node.scrollTop;
317
+ node.scrollBy({ top: y, behavior: "instant" });
318
+ return { before, after: node.scrollTop, canScroll: node.scrollHeight > node.clientHeight };
319
+ }, dy);
320
+ if (!moved.canScroll) throw new Error(`‘${within}’ has nothing to scroll`);
321
+ if (moved.before === moved.after) {
322
+ throw new Error(`‘${within}’ did not move: it is already at the ${dy > 0 ? "bottom" : "top"}`);
323
+ }
324
+ } else {
325
+ const moved = await page.evaluate((y) => {
326
+ const before = window.scrollY;
327
+ window.scrollBy({ top: y, behavior: "instant" });
328
+ return { before, after: window.scrollY };
329
+ }, dy);
330
+ if (moved.before === moved.after) {
331
+ throw new Error(`the page did not scroll: it is already at the ${dy > 0 ? "bottom" : "top"}`);
332
+ }
333
+ }
334
+ } else if (action === "screenshot") {
335
+ // TM-593: evidence was one full-page shot at the end, in which a fixed overlay cannot be
336
+ // located at all — the reporter could not find an open drawer in a 1170x18972 capture. A
337
+ // named shot at the moment that matters, viewport-sized, so it shows what a person sees.
338
+ const name = String(raw.params.name ?? target ?? value ?? "").trim() || "step";
339
+ const safe = name.replace(/[^a-zA-Z0-9._-]+/g, "-").slice(0, 60);
340
+ if (stepScreenshotDir) {
341
+ fs.mkdirSync(stepScreenshotDir, { recursive: true });
342
+ await page.screenshot({ path: path.join(stepScreenshotDir, `flow-${safe}.png`) });
343
+ detail = `saved flow-${safe}.png`;
344
+ } else {
345
+ // The step's promise is a picture. Passing green with nothing written is the same empty
346
+ // success this story exists to remove, so say which it was (Linux's check of 6d8d531).
347
+ status = "skip";
348
+ detail = "not saved: this run has no evidence folder";
349
+ }
242
350
  } else if (action === "back") {
243
351
  await page.goBack({ waitUntil: "domcontentloaded" });
244
352
  } else if (action === "wait_for") {
@@ -274,8 +382,14 @@ export async function executeWebFlowStep({ page, step, vars = {}, defaultTimeout
274
382
  }
275
383
  await settle(page);
276
384
  } catch (error) {
277
- status = "fail";
278
- detail = distillPlaywrightFailure(error.message || String(error));
385
+ // A step the author marked optional reports what it did not find, and the run carries on.
386
+ if (isOptionalStep(raw)) {
387
+ status = "skip";
388
+ detail = `optional — ${distillPlaywrightFailure(error.message || String(error))}`;
389
+ } else {
390
+ status = "fail";
391
+ detail = distillPlaywrightFailure(error.message || String(error));
392
+ }
279
393
  }
280
394
  return { action, target: action === "login" ? "sign-in form" : target || value, status, detail, task: raw.task };
281
395
  }
@@ -356,7 +470,7 @@ export async function runWebFlow({ flow, url, logPath, screenshotDir, recordVide
356
470
  emit({action:"origin",target:"connected app",status:"fail",detail:"The workflow left the connected app origin. Authorize a supported sign-in route before continuing."});
357
471
  break;
358
472
  }
359
- const outcome = await executeWebFlowStep({ page, step, vars, defaultTimeout: timeout });
473
+ const outcome = await executeWebFlowStep({ page, step, vars, defaultTimeout: timeout, stepScreenshotDir: screenshotDir });
360
474
  emit(outcome);
361
475
  if (outcome.status === "fail" && screenshotDir) {
362
476
  fs.mkdirSync(screenshotDir, { recursive: true });
@@ -368,6 +482,9 @@ export async function runWebFlow({ flow, url, logPath, screenshotDir, recordVide
368
482
  if (screenshotDir) {
369
483
  fs.mkdirSync(screenshotDir, { recursive: true });
370
484
  await page.screenshot({ path: path.join(screenshotDir, "flow-final.png"), fullPage: true }).catch(() => {});
485
+ // Beside it, what the person actually sees: a fixed header, an open drawer or a toast is
486
+ // placeable here and invisible in a full-page capture (TM-593).
487
+ await page.screenshot({ path: path.join(screenshotDir, "flow-final-screen.png") }).catch(() => {});
371
488
  }
372
489
  } finally {
373
490
  await requestPhase(teardown);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aarwitz/tapp",
3
- "version": "0.35.5",
3
+ "version": "0.35.7",
4
4
  "mcpName": "io.github.aarwitz/tapp",
5
5
  "description": "Let coding agents verify UI changes on real iOS, Android, and web surfaces, then enforce reviewed proof in deterministic CI.",
6
6
  "license": "MIT",
@@ -98,7 +98,7 @@
98
98
  "mobile"
99
99
  ],
100
100
  "scripts": {
101
- "test": "node --test tests/report.test.js tests/regression.test.js tests/engine.test.js tests/project-config.test.js tests/application-model.test.js tests/ui-map.test.js tests/focused-navigation.test.js tests/task-runtime.test.js tests/release-contract.test.js tests/pr-selection.test.js tests/flow-runtime.test.js tests/flow-variables.test.js tests/feedback.test.js tests/web-explorer.test.js tests/web-session.test.js tests/web-link-audit.test.js tests/web-overlay.test.js tests/web-audit.test.js tests/page-observations.test.js tests/capture-provenance.test.js tests/capture-frames.test.js tests/actor-store.test.js tests/account-store.test.js tests/alerts.test.js tests/access-jwt.test.js tests/oauth.test.js tests/studio-client.test.js tests/journeys.test.js tests/ios-crash-attribution.test.js tests/ios-simulator-selection.test.js tests/ios-recording-stop.test.js tests/web-flow.test.js tests/sign-in.test.js tests/scenario-runtime.test.js tests/android-driver.test.js tests/android-explorer.test.js tests/android-flow.test.js tests/macos-driver.test.js tests/android-primitives-protocol.test.js tests/managed-web.test.js tests/product-operations.test.js tests/job-lanes.test.js tests/browser-product.test.js tests/browser-chat-narration.test.js tests/browser-onboarding.test.js tests/managed-operation.test.js tests/ci-setup.test.js tests/ci-install.test.js tests/cli.test.js tests/mcp-workspace.test.js tests/action.test.js tests/package-surface.test.js tests/agent-surface.test.js tests/platforms.test.js tests/presentation-contract.test.js tests/landing-brand.test.js tests/ci-gate.test.js tests/ci-report.test.js tests/desktop-protocol.test.js tests/ios-flow-protocol.test.js tests/feedback-triage-0919.test.js vscode-extension/test/bridge.test.js",
101
+ "test": "node --test tests/report.test.js tests/regression.test.js tests/engine.test.js tests/project-config.test.js tests/application-model.test.js tests/ui-map.test.js tests/focused-navigation.test.js tests/task-runtime.test.js tests/release-contract.test.js tests/pr-selection.test.js tests/flow-runtime.test.js tests/flow-variables.test.js tests/flow-recording.test.js tests/sim-recorder.test.js tests/feedback.test.js tests/web-explorer.test.js tests/web-session.test.js tests/web-link-audit.test.js tests/web-overlay.test.js tests/web-audit.test.js tests/page-observations.test.js tests/capture-provenance.test.js tests/capture-frames.test.js tests/actor-store.test.js tests/account-store.test.js tests/alerts.test.js tests/access-jwt.test.js tests/oauth.test.js tests/studio-client.test.js tests/journeys.test.js tests/ios-crash-attribution.test.js tests/ios-simulator-selection.test.js tests/ios-recording-stop.test.js tests/web-flow.test.js tests/sign-in.test.js tests/signin-honesty.test.js tests/scenario-runtime.test.js tests/android-driver.test.js tests/android-explorer.test.js tests/evidence-retention.test.js tests/android-flow.test.js tests/macos-driver.test.js tests/android-primitives-protocol.test.js tests/managed-web.test.js tests/product-operations.test.js tests/job-lanes.test.js tests/browser-product.test.js tests/browser-chat-narration.test.js tests/browser-run-reading.test.js tests/browser-onboarding.test.js tests/managed-operation.test.js tests/ci-setup.test.js tests/ci-install.test.js tests/cli.test.js tests/mcp-workspace.test.js tests/action.test.js tests/package-surface.test.js tests/agent-surface.test.js tests/platforms.test.js tests/presentation-contract.test.js tests/landing-brand.test.js tests/ci-gate.test.js tests/ci-report.test.js tests/desktop-protocol.test.js tests/ios-flow-protocol.test.js tests/feedback-triage-0919.test.js vscode-extension/test/bridge.test.js",
102
102
  "test:browser-journey": "node --test tests/browser-journey.test.js",
103
103
  "test:browser-native": "TAPP_RUN_NATIVE_BROWSER=1 node --test tests/browser-native-journey.test.js"
104
104
  }
@@ -63,7 +63,10 @@ def to_json(path):
63
63
  }
64
64
  # Multi-actor Scenarios deliberately reuse the Flow step language and marker
65
65
  # protocol, while preserving actor/session and lifecycle orchestration.
66
- for key in ("actors", "setup", "teardown", "timeoutMs", "taskPlan", "releaseContract"):
66
+ # `alerts: allow|dismiss` says what to do with a one-time system alert (TM-497). It is a
67
+ # flow-level setting rather than a step because the alerts it covers appear on some runs and
68
+ # not others, so there is no step to attach it to.
69
+ for key in ("actors", "setup", "teardown", "timeoutMs", "taskPlan", "releaseContract", "alerts"):
67
70
  if key in flow:
68
71
  out[key] = flow[key]
69
72
  print(json.dumps(out))
@@ -23,8 +23,12 @@ screen or journey works from source inspection alone.
23
23
  | Decide whether a merge passes policy | `ci`; exploration never decides this |
24
24
 
25
25
  Prefer connected `tapp_*` MCP tools when available: they keep interactive sessions alive and return
26
- screenshots inline. Otherwise run `npx -y @aarwitz/tapp@latest` from the app repository. Do not require MCP,
27
- an account, an API key, or a global install for the core workflow.
26
+ screenshots inline. Otherwise run Tapp from the app repository. Do not require MCP, an account, an
27
+ API key, or a global install for the core workflow.
28
+
29
+ **Use the version the project pins.** Where `.tapp/version` exists it is this project's engine, may
30
+ be enforced, and a result from any other engine is not evidence about it — substitute it everywhere:
31
+ `npx -y @aarwitz/tapp@$(cat .tapp/version)`. `@latest` below applies only when nothing is pinned.
28
32
 
29
33
  ## Start source-connected
30
34