@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.
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { AndroidDriver, findAndroidElement, isAndroidAppSnapshot } from "./android-driver.js";
4
- import { FlowLog, flowVariables, normalizeFlowStep, substituteFlowValue } from "./flow-runtime.js";
4
+ import { FlowLog, flowVariables, normalizeFlowStep, substituteFlowValue, isOptionalStep } from "./flow-runtime.js";
5
5
  import { chooseSignInSubmit } from "./sign-in.js";
6
6
 
7
7
  const DEFAULT_TIMEOUT = 6000;
@@ -60,18 +60,49 @@ export async function runAndroidFlow({ flow, appId, apkPath, serial, logPath, sc
60
60
  // Same rule as the web runner: rule out "Forgot password" and "Continue with Google" by
61
61
  // name, prefer a sign-in name, and otherwise take the first clickable control after the
62
62
  // password field — Android apps name that button after the product too.
63
- const passwordIndex = snap.elements.indexOf(passwordField);
63
+ //
64
+ // TM-554: `settle()` returns a fresh snapshot, so the pre-typing `passwordField` object is
65
+ // not in `snap.elements` and `indexOf` returned -1. Every control then counted as "after
66
+ // the password", and a submit named for the product (outside SIGN_IN_NAME) fell through to
67
+ // the position rule, which picked the first clickable element — the email field. Tapping a
68
+ // text field succeeds, so the step passed with the form still on screen. Find the field
69
+ // again by key, and never offer a text field as the thing that signs you in.
70
+ const passwordKey = passwordField.id || passwordField.description || passwordField.label;
71
+ const passwordNow = findAndroidElement(snap.elements, passwordKey) || passwordField;
72
+ const passwordIndex = snap.elements.indexOf(passwordNow);
64
73
  const choice = chooseSignInSubmit(snap.elements.map((element, index) => ({
65
74
  index,
66
75
  name: `${element.text || ""} ${element.label || ""}`.replace(/\s+/g, " ").trim() || String(element.id || ""),
67
- visible: Boolean(element.clickable),
76
+ visible: Boolean(element.clickable) && !/EditText/i.test(element.type || ""),
68
77
  disabled: element.enabled === false,
69
- after: index > passwordIndex,
78
+ after: passwordIndex >= 0 && index > passwordIndex,
70
79
  })));
71
80
  const submit = choice ? snap.elements[choice.index] : null;
72
81
  if (!submit) throw new Error("could not identify a sign-in control");
73
- const submitResult = await d.tap(submit.id || submit.description || submit.text, snap);
74
- if (submitResult.status !== "ok") throw new Error(submitResult.detail || "could not submit the login form");
82
+ const submitKey = submit.id || submit.description || submit.text;
83
+ const submitName = submit.text || submit.label || submit.id;
84
+ const press = async () => {
85
+ const r = await d.tap(submitKey, snap);
86
+ if (r.status !== "ok") throw new Error(r.detail || "could not submit the login form");
87
+ snap = await d.settle();
88
+ return !findAndroidElement(snap.elements, passwordKey);
89
+ };
90
+ const stillOnForm = `login did not leave the sign-in form: ‘${submitName}’ was pressed but the password field is still on screen`;
91
+ // A login step may only pass when the form is actually gone (TM-554). `adb shell input
92
+ // tap` reports success whatever it lands on, so a press the keyboard swallowed looks
93
+ // exactly like signing in.
94
+ if (!(await press())) {
95
+ // Only Back out of a keyboard that is actually up. Back with no IME means "leave this
96
+ // screen", which would pop the sign-in activity — and then the password field is gone
97
+ // for the wrong reason, which the check above would have read as a successful sign-in.
98
+ if (!(d.imeShowing && (await d.imeShowing()))) throw new Error(stillOnForm);
99
+ await d.back();
100
+ snap = await d.settle();
101
+ if (!findAndroidElement(snap.elements, passwordKey)) {
102
+ throw new Error(`login did not sign in: dismissing the keyboard also left the sign-in screen, so ‘${submitName}’ was never accepted`);
103
+ }
104
+ if (!(await press())) throw new Error(stillOnForm);
105
+ }
75
106
  } else if (action === "swipe") {
76
107
  await d.swipe(target || "up");
77
108
  } else if (action === "back") {
@@ -106,9 +137,15 @@ export async function runAndroidFlow({ flow, appId, apkPath, serial, logPath, sc
106
137
  if (!["wait_for", "assert_screen", "assert_exists", "assert_absent", "assert_text", "assert_ai"].includes(action)) snap = await d.settle();
107
138
  if (action !== "assert_ai" && !isAndroidAppSnapshot(snap, targetApp)) throw new Error(`app left the foreground during ‘${action}’`);
108
139
  } catch (error) {
109
- status = "fail";
110
- detail = error.message || String(error);
111
- if (screenshotDir) await d.screenshot(path.join(screenshotDir, `flow-failure-${i + 1}.png`)).catch(() => {});
140
+ // A step the author marked optional reports what it did not find, and the run carries on.
141
+ if (isOptionalStep(raw)) {
142
+ status = "skip";
143
+ detail = `optional — ${error.message || String(error)}`;
144
+ } else {
145
+ status = "fail";
146
+ detail = error.message || String(error);
147
+ if (screenshotDir) await d.screenshot(path.join(screenshotDir, `flow-failure-${i + 1}.png`)).catch(() => {});
148
+ }
112
149
  }
113
150
  log.step({ index: i + 1, action, target: action === "login" ? "sign-in form" : target || value, status, detail, task: raw.task });
114
151
  if (status === "fail" && !flow.continueOnFailure) break;
@@ -13,6 +13,32 @@ import { createRequire } from "module";
13
13
  const require = createRequire(import.meta.url);
14
14
  const VERSION = (() => { try { return require("../../package.json").version; } catch { return "0.0.0"; } })();
15
15
 
16
+ // Which tapp actually produced this run (TM-670).
17
+ //
18
+ // The version string alone cannot answer that. package.json reads 0.35.5 both in the published
19
+ // package and in this repository for the whole time 0.35.5 is being developed, so evidence from an
20
+ // unreleased working tree — eleven commits past the release when this was written — claimed a
21
+ // released version and no checker could tell. Contract v6 asks each job to carry "exact tapp
22
+ // version plus verified package integrity"; a number everyone shares is neither.
23
+ //
24
+ // An installed package has no `.git`; a source checkout does. That is the whole discriminator.
25
+ // Resolved once per process, like VERSION: a run must never pay for this twice, and must never
26
+ // fail because of it.
27
+ const BUILD = (() => {
28
+ const root = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..");
29
+ const git = (args) => execFileSync("git", ["-C", root, ...args], {
30
+ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000,
31
+ }).trim();
32
+ try {
33
+ if (!fs.existsSync(path.join(root, ".git"))) return { build: "package" };
34
+ return { build: "source", commit: git(["rev-parse", "--short", "HEAD"]), dirty: git(["status", "--porcelain"]).length > 0 };
35
+ } catch {
36
+ // A checkout we cannot interrogate is still not a published package, and saying so is more
37
+ // honest than implying one.
38
+ return { build: "source" };
39
+ }
40
+ })();
41
+
16
42
  export const PROVENANCE_FILE = "provenance.json";
17
43
 
18
44
  function realpath(dir) {
@@ -42,7 +68,7 @@ export function writeCaptureProvenance(captureDir, { kind, platform, target = ""
42
68
  platform: String(platform || ""),
43
69
  target: String(target || ""),
44
70
  project: describeProject(projectDir),
45
- tool: { name: "tapp", version: VERSION },
71
+ tool: { name: "tapp", version: VERSION, ...BUILD },
46
72
  createdAt: new Date().toISOString(),
47
73
  ...extra,
48
74
  };
@@ -0,0 +1,215 @@
1
+ // Evidence does not live for ever (TM-630).
2
+ //
3
+ // Every run writes a directory under `TAPP_HOME/captures` and nothing ever removed one. On the
4
+ // machine that prompted this story that was 853 runs and 3.4 GB going back three months, on a disk
5
+ // at 93% — and `tapp doctor` reported the free space without mentioning that Tapp itself was
6
+ // holding the missing GiB. Anyone who uses Tapp for a few months gets the same.
7
+ //
8
+ // Two rules decide everything here:
9
+ //
10
+ // • Only ever inside `captures/`. Retained campaigns (`TAPP_HOME/validation/`), accounts, actors
11
+ // and app builds are siblings of that directory, so confining the walk is what protects them —
12
+ // not a list of exceptions that someone has to remember to extend.
13
+ // • Deleting evidence someone is relying on is far worse than keeping bytes. So a run is removed
14
+ // only when every reason to keep it is absent, and anything unrecognised is kept.
15
+
16
+ import fs from "node:fs";
17
+ import os from "node:os";
18
+ import path from "node:path";
19
+
20
+ /** Evidence older than this is removed once a run finishes. */
21
+ export const DEFAULT_KEEP_DAYS = 14;
22
+
23
+ /** A run that says "keep me" is never pruned, whatever its age. */
24
+ export const KEEP_MARKER = ".tapp-keep";
25
+
26
+ // A directory touched this recently is treated as live even if its name looks old: a run still
27
+ // writing to it, or a second tapp process alongside this one, must not have its evidence removed
28
+ // underneath it.
29
+ const ACTIVE_GRACE_MS = 60 * 60 * 1000;
30
+
31
+ export function captureRootFor(env = process.env) {
32
+ return path.join((env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp"), "captures");
33
+ }
34
+
35
+ /**
36
+ * How long evidence is kept, from `TAPP_KEEP_EVIDENCE_DAYS`.
37
+ * `0`, `off`, `never` or `infinite` switch pruning off entirely; anything unparseable falls back to
38
+ * the default rather than guessing a number that deletes more than the author meant.
39
+ */
40
+ export function keepDays(env = process.env) {
41
+ const raw = String(env.TAPP_KEEP_EVIDENCE_DAYS ?? "").trim().toLowerCase();
42
+ if (!raw) return DEFAULT_KEEP_DAYS;
43
+ if (["0", "off", "never", "infinite", "forever"].includes(raw)) return 0;
44
+ const value = Number(raw);
45
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_KEEP_DAYS;
46
+ }
47
+
48
+ /** "3 days ago", for a person reading `tapp doctor` rather than a timestamp. */
49
+ export function formatAge(ms) {
50
+ const days = Math.floor(Number(ms || 0) / (24 * 60 * 60 * 1000));
51
+ if (days >= 1) return `${days} day${days === 1 ? "" : "s"} ago`;
52
+ const hours = Math.floor(Number(ms || 0) / (60 * 60 * 1000));
53
+ if (hours >= 1) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
54
+ return "just now";
55
+ }
56
+
57
+ function directorySize(dir) {
58
+ let total = 0;
59
+ let entries;
60
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return 0; }
61
+ for (const entry of entries) {
62
+ const full = path.join(dir, entry.name);
63
+ try {
64
+ if (entry.isDirectory()) total += directorySize(full);
65
+ else if (entry.isFile()) total += fs.statSync(full).size;
66
+ } catch { /* vanished mid-walk: it is not occupying space we can report on */ }
67
+ }
68
+ return total;
69
+ }
70
+
71
+ /**
72
+ * Why this run must be kept, or null when it may be removed.
73
+ * Exported so the decision can be tested one reason at a time, and so a caller can explain itself.
74
+ */
75
+ export function keepReason(dir, { now = Date.now(), cutoffMs } = {}) {
76
+ let stats;
77
+ try { stats = fs.statSync(dir); } catch { return "unreadable"; }
78
+ if (!stats.isDirectory()) return "not a run directory";
79
+ if (fs.existsSync(path.join(dir, KEEP_MARKER))) return "marked to keep";
80
+ if (now - stats.mtimeMs < ACTIVE_GRACE_MS) return "still active";
81
+ if (!(stats.mtimeMs < cutoffMs)) return "within the window";
82
+ return null;
83
+ }
84
+
85
+ /**
86
+ * Report what Tapp is holding: how many runs, how much, and the oldest.
87
+ * `tapp doctor` prints this beside the free-space line it already has, so the tool accounts for its
88
+ * own disk use instead of only the machine's.
89
+ */
90
+ export function evidenceUsage({ env = process.env, root = null } = {}) {
91
+ const dir = root || captureRootFor(env);
92
+ let entries;
93
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch {
94
+ return { root: dir, runs: 0, bytes: 0, oldestMs: null };
95
+ }
96
+ let runs = 0;
97
+ let bytes = 0;
98
+ let oldestMs = null;
99
+ for (const entry of entries) {
100
+ if (!entry.isDirectory()) continue;
101
+ const full = path.join(dir, entry.name);
102
+ runs += 1;
103
+ bytes += directorySize(full);
104
+ try {
105
+ const { mtimeMs } = fs.statSync(full);
106
+ if (oldestMs === null || mtimeMs < oldestMs) oldestMs = mtimeMs;
107
+ } catch { /* ignore */ }
108
+ }
109
+ return { root: dir, runs, bytes, oldestMs };
110
+ }
111
+
112
+ /**
113
+ * Remove evidence past the retention window. Called as part of a run's own teardown, so it costs
114
+ * nothing extra and needs no new command (ADR-0007 keeps the verb list fixed).
115
+ *
116
+ * Never throws: a run must not be reported as failed because tidying up afterwards did not work.
117
+ */
118
+ export function pruneEvidence({ env = process.env, root = null, now = Date.now(), dryRun = false } = {}) {
119
+ const days = keepDays(env);
120
+ const dir = root || captureRootFor(env);
121
+ const result = { root: dir, enabled: days > 0, keepDays: days, removed: [], freedBytes: 0, kept: 0, errors: [] };
122
+ if (days <= 0) return result;
123
+
124
+ let entries;
125
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return result; }
126
+
127
+ const cutoffMs = now - days * 24 * 60 * 60 * 1000;
128
+ for (const entry of entries) {
129
+ if (!entry.isDirectory()) continue;
130
+ const full = path.join(dir, entry.name);
131
+ const reason = keepReason(full, { now, cutoffMs });
132
+ if (reason) { result.kept += 1; continue; }
133
+ const size = directorySize(full);
134
+ if (dryRun) { result.removed.push(entry.name); result.freedBytes += size; continue; }
135
+ try {
136
+ fs.rmSync(full, { recursive: true, force: true });
137
+ result.removed.push(entry.name);
138
+ result.freedBytes += size;
139
+ } catch (error) {
140
+ result.errors.push(`${entry.name}: ${error.message || String(error)}`);
141
+ }
142
+ }
143
+ return result;
144
+ }
145
+
146
+ /**
147
+ * Mark a run as one to keep, for ever (TM-630).
148
+ *
149
+ * Honouring `.tapp-keep` was not enough: nothing wrote it, so a run someone was relying on aged
150
+ * out like any other (Linux's review of 2f69800). Tapp writes the mark itself at every point where
151
+ * it knows a run is being relied on — a report the author saved, a capture cited in filed feedback
152
+ * — and `keepHint()` tells a person how to mark one where Tapp cannot know, such as a path quoted
153
+ * in a note somewhere else.
154
+ *
155
+ * Refuses anything outside the captures root, so a bad caller cannot drop files into a repository
156
+ * or a home directory. Never throws: marking is a courtesy, not the point of the run.
157
+ */
158
+ export function markKeep(target, reason = "", { env = process.env, root = null } = {}) {
159
+ const captures = root || captureRootFor(env);
160
+ const raw = String(target || "").trim();
161
+ if (!raw) return { kept: false, why: "no run given" };
162
+ const dir = path.isAbsolute(raw) ? path.resolve(raw) : path.join(captures, raw);
163
+ // Confined the same way pruning is: inside captures/, and nowhere else.
164
+ // Must be a run INSIDE captures/, not the captures root itself (Linux's review of 6d02b68:
165
+ // marking the root wrote .tapp-keep at the top of the evidence folder).
166
+ if (!dir.startsWith(`${captures}${path.sep}`)) {
167
+ return { kept: false, why: `not a run inside the evidence folder: ${dir}` };
168
+ }
169
+ try {
170
+ if (!fs.statSync(dir).isDirectory()) return { kept: false, why: "not a run directory" };
171
+ fs.writeFileSync(
172
+ path.join(dir, KEEP_MARKER),
173
+ `${reason || "kept"}\n${new Date().toISOString()}\n`
174
+ );
175
+ return { kept: true, dir, reason };
176
+ } catch (error) {
177
+ return { kept: false, why: error.message || String(error) };
178
+ }
179
+ }
180
+
181
+ /**
182
+ * The run directory a finished report came from, or "" when it carries none.
183
+ *
184
+ * Exploration publishes `capture` as an OBJECT — `{ id, path, relativePath, provenance }` — at
185
+ * every producer (index.js web/android/macos/ios, browser-product.js journeys). My first version
186
+ * read `capture` as a string, so it never matched a real report and the mark was never written;
187
+ * the test passed only because it fed a shape tapp does not produce (Linux's review of 6d02b68).
188
+ * Flow runs are the other shape: they carry `evidenceDir`.
189
+ */
190
+ export function runDirOf(structured) {
191
+ if (!structured || typeof structured !== "object") return "";
192
+ const capture = structured.capture;
193
+ if (capture && typeof capture === "object") {
194
+ if (typeof capture.path === "string" && capture.path) return capture.path;
195
+ // Some error paths carry only the id; it resolves under the captures root.
196
+ if (typeof capture.id === "string" && capture.id) return capture.id;
197
+ return "";
198
+ }
199
+ for (const value of [structured.evidenceDir, structured.captureDir, capture]) {
200
+ if (typeof value === "string" && value) return value;
201
+ }
202
+ return "";
203
+ }
204
+
205
+ /** Mark the run a finished report came from, whichever shape that report is. */
206
+ export function keepRunFor(structured, reason = "", options = {}) {
207
+ const candidate = runDirOf(structured);
208
+ if (!candidate) return { kept: false, why: "no run directory on the report" };
209
+ return markKeep(candidate, reason, options);
210
+ }
211
+
212
+ /** How to keep a run by hand, for the cases Tapp cannot know about. */
213
+ export function keepHint(dir) {
214
+ return `To keep this run when old evidence is cleared out: touch ${path.join(dir || "<run>", KEEP_MARKER)}`;
215
+ }
@@ -0,0 +1,106 @@
1
+ // Cutting a recording by step name instead of by eye.
2
+ //
3
+ // Making a narrated demo used to mean starting `simctl io recordVideo` by hand, running the
4
+ // flow, stopping the recorder, then building contact sheets and guessing where each step began.
5
+ // The wrapper's own step times came from its own clock, which runs ahead of the picture by a
6
+ // varying amount: the recorder takes a moment to start, and the simulator's file timestamps
7
+ // drift. So the times never quite matched the frames (TM-497).
8
+ //
9
+ // The fix is to put the two clocks in the same frame of reference once, here: the flow reports
10
+ // each step's window against its own start, and the recording reports when its first frame was
11
+ // captured relative to that same start. Everything after is arithmetic.
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+
15
+ /** The step windows a finished flow log carries, in the flow's own milliseconds. */
16
+ export function parseFlowSteps(logText) {
17
+ const steps = [];
18
+ for (const line of String(logText || "").split("\n")) {
19
+ if (!line.startsWith("OCQA_FLOW_STEP:")) continue;
20
+ try {
21
+ const step = JSON.parse(line.slice("OCQA_FLOW_STEP:".length));
22
+ if (Number.isFinite(step.startMs) && Number.isFinite(step.endMs)) steps.push(step);
23
+ } catch { /* a truncated final line */ }
24
+ }
25
+ return steps;
26
+ }
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
+
46
+ /**
47
+ * The same steps expressed in the recording's seconds.
48
+ *
49
+ * `recordingStartedAtMs` is when the recorder's first frame was captured, on the same clock the
50
+ * flow used for its own start. A recorder that began AFTER the flow gives a negative offset for
51
+ * the earliest steps; they are clamped to zero rather than dropped, because a step that happened
52
+ * just before the first frame still belongs at the top of the video.
53
+ */
54
+ export function stepsInVideoTime(steps, { flowStartedAtMs, recordingStartedAtMs }) {
55
+ const offsetMs = Number(flowStartedAtMs) - Number(recordingStartedAtMs);
56
+ const seconds = (ms) => Math.max(0, Math.round((ms + offsetMs)) / 1000);
57
+ return steps.map((step) => ({
58
+ index: step.index,
59
+ action: step.action,
60
+ target: step.target,
61
+ status: step.status,
62
+ start: seconds(step.startMs),
63
+ end: seconds(step.endMs),
64
+ }));
65
+ }
66
+
67
+ /**
68
+ * The sidecar an editor reads: the video's name, how long the run took, and every step in the
69
+ * video's own seconds. Written next to the recording as `<name>.steps.json`.
70
+ */
71
+ export function sidecarPath(videoPath) {
72
+ const parsed = path.parse(String(videoPath));
73
+ return path.join(parsed.dir, `${parsed.name}.steps.json`);
74
+ }
75
+
76
+ export function writeStepsSidecar(videoPath, steps, { flowStartedAtMs, recordingStartedAtMs, holdMs = 0, name = "", videoDurationMs = null } = {}) {
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;
85
+ const out = {
86
+ video: path.basename(String(videoPath)),
87
+ name,
88
+ endsAt: Number(endsAt.toFixed(3)),
89
+ holdSeconds: holdMs / 1000,
90
+ steps: inVideoTime,
91
+ };
92
+ const target = sidecarPath(videoPath);
93
+ fs.mkdirSync(path.dirname(target), { recursive: true });
94
+ fs.writeFileSync(target, `${JSON.stringify(out, null, 2)}\n`);
95
+ return { path: target, ...out };
96
+ }
97
+
98
+ /** "3s", "1500ms", "2" → milliseconds. The flag is for people, so accept what they will type. */
99
+ export function parseHold(value) {
100
+ const text = String(value ?? "").trim().toLowerCase();
101
+ if (!text) return 0;
102
+ const match = /^(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?)?$/.exec(text);
103
+ if (!match) throw new Error(`--hold expects a duration like 3s or 1500ms (got '${value}')`);
104
+ const amount = Number(match[1]);
105
+ return match[2] === "ms" ? Math.round(amount) : Math.round(amount * 1000);
106
+ }
@@ -44,7 +44,10 @@ 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" },
49
52
  { action: "wait", target: "milliseconds (fixed pause; prefer wait_for)", passes: "always" },
50
53
  { action: "wait_for", target: "label / text (+ per-step timeoutMs/timeout; flow-level timeoutMs sets the default)", passes: "the element appeared before the timeout" },
@@ -59,8 +62,34 @@ const ALIASES = { click: "tap", press: "tap", fill: "type", input: "type", sleep
59
62
 
60
63
  // Static checks a Flow must pass before any runtime is launched. Returns human-readable errors;
61
64
  // an empty array means every step is in the vocabulary and shaped so a driver can execute it.
65
+ /**
66
+ * A step marked `optional: true` passes whether or not its target is there.
67
+ *
68
+ * Some screens only appear sometimes. The iOS "Save Password?" sheet shows up after a sign-in on
69
+ * some runs and not others, with the same account and the same flow, so a flow that taps it
70
+ * fails on the runs without it and a flow that ignores it fails on the runs with it. There was
71
+ * no way to write one that passed both times, which means the journey could not be kept and
72
+ * re-checked at all (TM-497, public issue 33).
73
+ *
74
+ * An optional step that fails is reported as skipped, with the reason, rather than passing
75
+ * silently — a run should still say what it did not find.
76
+ */
77
+ export function isOptionalStep(step) {
78
+ return Boolean(step?.params?.optional === true || step?.params?.optional === "true");
79
+ }
80
+
81
+ /** What `alerts:` may say. Anything else is a typo that would silently do nothing (TM-497). */
82
+ export const ALERT_MODES = Object.freeze(["allow", "dismiss"]);
83
+
62
84
  export function validateFlowSteps(flow, platform = inferFlowPlatform(flow)) {
63
85
  const errors = [];
86
+ const alerts = String(flow?.alerts ?? "").trim();
87
+ if (alerts && !ALERT_MODES.includes(alerts.toLowerCase())) {
88
+ errors.push(`alerts: '${alerts}' is not a setting — use ${ALERT_MODES.map((m) => `alerts: ${m}`).join(" or ")}`);
89
+ }
90
+ if (alerts && platform !== "ios") {
91
+ errors.push(`alerts: applies to iOS flows, where a system alert belongs to the operating system rather than the app (this flow is ${platform})`);
92
+ }
64
93
  const steps = Array.isArray(flow?.steps) ? flow.steps : [];
65
94
  steps.forEach((raw, i) => {
66
95
  const step = normalizeFlowStep(raw);
@@ -149,16 +178,27 @@ export function loadFlowFile(flowPath, options = {}) {
149
178
  }
150
179
 
151
180
  export class FlowLog {
152
- constructor({ logPath, flow }) {
181
+ constructor({ logPath, flow, now = () => Date.now() }) {
153
182
  this.logPath = logPath;
154
183
  this.flow = flow;
155
184
  this.lines = [];
156
185
  this.failed = 0;
157
186
  this.executed = 0;
187
+ // When each step happened, so a recording of the run can be cut by step name instead of by
188
+ // eye. A step is reported once it has finished, so its start is the moment the previous one
189
+ // ended — which is what you want for cutting: the segment carries the step's own settling
190
+ // and waiting, not just the instant it acted (TM-497).
191
+ this.now = now;
192
+ this.startedAtMs = now();
193
+ this.cursorMs = this.startedAtMs;
158
194
  this.contract = flow.releaseContract?.name || "";
159
195
  this.criticality = flow.releaseContract?.criticality || "";
160
196
  this.kind = this.contract ? "release-contract" : flow.kind || "flow";
161
197
  this.emit(`OCQA_FLOW_RESULT:started total=${flow.steps.length} name=${flow.name || "flow"} kind=${this.kind}${this.contract ? ` contract=${this.contract}` : ""}`);
198
+ // When the steps actually began, on the wall clock (TM-497). Step times are relative to this,
199
+ // and a recorder started by the CLI knows nothing else about it: on iOS the CLI's own "now" is
200
+ // most of a minute earlier, because building and launching the harness happens in between.
201
+ this.emit(`OCQA_FLOW_CLOCK:${JSON.stringify({ startedAtEpochMs: Date.now() })}`);
162
202
  }
163
203
 
164
204
  emit(line) {
@@ -172,7 +212,10 @@ export class FlowLog {
172
212
  step({ index, action, target, status, detail = "", actor = "", task = "" }) {
173
213
  this.executed += 1;
174
214
  if (status === "fail") this.failed += 1;
175
- this.emit(`OCQA_FLOW_STEP:${JSON.stringify({ index, action, target, assert: action.startsWith("assert_"), status, detail, ...(actor ? { actor } : {}), ...(task ? { task } : {}), ...(this.contract ? { contract: this.contract } : {}) })}`);
215
+ const startMs = this.cursorMs - this.startedAtMs;
216
+ const endMs = this.now() - this.startedAtMs;
217
+ this.cursorMs = this.startedAtMs + endMs;
218
+ this.emit(`OCQA_FLOW_STEP:${JSON.stringify({ index, action, target, assert: action.startsWith("assert_"), status, detail, startMs, endMs, ...(actor ? { actor } : {}), ...(task ? { task } : {}), ...(this.contract ? { contract: this.contract } : {}) })}`);
176
219
  if (status === "fail") {
177
220
  this.emit(`OCQA_ISSUE:${JSON.stringify({
178
221
  type: "flow_assertion_failed",
@@ -187,6 +230,7 @@ export class FlowLog {
187
230
 
188
231
  finish(extra = {}) {
189
232
  const passed = this.failed === 0 && this.executed > 0;
233
+ extra = { startedAt: new Date(this.startedAtMs).toISOString(), durationMs: this.now() - this.startedAtMs, ...extra };
190
234
  // Keep `passed` first for marker consumers that stream-match the payload. `extra` carries
191
235
  // run context worth diagnosing from the log alone (e.g. the URL the flow actually opened —
192
236
  // field issue #15 was six flows silently replayed against the wrong page).
@@ -30,7 +30,7 @@ const workspaceRoot = (() => {
30
30
  })();
31
31
  const scriptsDir = path.join(repoRoot, "scripts");
32
32
  import { writeCaptureProvenance, readCaptureProvenance, captureBelongsToProject, provenanceLabel } from "./capture-provenance.js";
33
- import { findSignInSubmit } from "./sign-in.js";
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
35
  // The old alias remains a read-only fallback; unset repository development stays local.
36
36
  const tappHome = (process.env.TAPP_HOME || "").trim();
@@ -1212,14 +1212,32 @@ async function sessionAct(cmd) {
1212
1212
  s.latestTree = await s.driver.settle(2200, s.latestTree);
1213
1213
  const pr = await s.driver.type(passwordField.id || passwordField.label, cmd.password || s.creds.password || "", s.latestTree);
1214
1214
  s.latestTree = await s.driver.settle(2200, s.latestTree);
1215
- const submit = s.latestTree.elements.find((e) => e.clickable && /sign in|log in|login|continue/i.test(`${e.text} ${e.label} ${e.id}`));
1215
+ // One rule for choosing the control that signs you in (TM-618). This used to be its own
1216
+ // `/sign in|log in|login|continue/i` with no exclusion list, so "Continue with Google"
1217
+ // matched — handing a third-party identity provider a session, which a machine must
1218
+ // never do on someone's behalf — and it took whichever such button came first in the
1219
+ // tree. chooseSignInSubmit is the same rule the flow runners use.
1220
+ const passwordNow = s.latestTree.elements.find((e) => (e.id && passwordField.id && e.id === passwordField.id)
1221
+ || (e.label && passwordField.label && e.label === passwordField.label)) || passwordField;
1222
+ const passwordIndex = s.latestTree.elements.indexOf(passwordNow);
1223
+ const choice = chooseSignInSubmit(s.latestTree.elements.map((e, index) => ({
1224
+ index,
1225
+ name: `${e.text || ""} ${e.label || ""}`.replace(/\s+/g, " ").trim() || String(e.id || ""),
1226
+ visible: Boolean(e.clickable) && !/EditText/i.test(e.type || ""),
1227
+ disabled: e.enabled === false,
1228
+ after: passwordIndex >= 0 && index > passwordIndex,
1229
+ })));
1230
+ const submit = choice ? s.latestTree.elements[choice.index] : null;
1216
1231
  if (er.status !== "ok" || pr.status !== "ok" || !submit) {
1217
1232
  status = "not_found"; detail = "Could not fill or submit the login form";
1218
1233
  } else {
1219
- const before = s.latestTree.screenTitle;
1220
1234
  await s.driver.tap(submit.id || submit.description || submit.text, s.latestTree);
1221
1235
  s.latestTree = await s.driver.settle(2200, s.latestTree);
1222
- if (s.latestTree.screenTitle === before) { status = "still_on_login"; detail = "Submit left the app on the login screen"; }
1236
+ // Judge by the form, not the title: an app whose sign-in and landing screens share a
1237
+ // title reported a sign-in that never happened (TM-618).
1238
+ const stillOnForm = s.latestTree.elements.some((e) => (e.id && passwordNow.id && e.id === passwordNow.id)
1239
+ || (e.secure && /EditText/i.test(e.type || "")));
1240
+ if (stillOnForm) { status = "still_on_login"; detail = "Submit left the app on the login screen"; }
1223
1241
  }
1224
1242
  }
1225
1243
  }
@@ -8,7 +8,7 @@ import fs from "node:fs";
8
8
  import path from "node:path";
9
9
 
10
10
  import { MacosDriver } from "./macos-driver.js";
11
- import { FlowLog, flowVariables, normalizeFlowStep, substituteFlowValue } from "./flow-runtime.js";
11
+ import { FlowLog, flowVariables, normalizeFlowStep, substituteFlowValue, isOptionalStep } from "./flow-runtime.js";
12
12
  import { chooseSignInSubmit } from "./sign-in.js";
13
13
 
14
14
  const DEFAULT_TIMEOUT = 6000;
@@ -83,6 +83,16 @@ export async function runMacosFlow({ flow, appPath, logPath, screenshotDir, driv
83
83
  if (!submit) throw new Error("could not identify a sign-in control");
84
84
  const pressed = d.tap(submit.label || submit.id, snap);
85
85
  if (pressed.status !== "ok") throw new Error(pressed.detail || "could not submit the sign-in form");
86
+ // A sign-in step may only pass once the password field has gone (TM-618). Pressing a
87
+ // control always "succeeds"; without this, a dead or mis-chosen button is indistinguishable
88
+ // from signing in — the same lie TM-554 removed from Android. There is no keyboard to
89
+ // dismiss on macOS, so this needs no retry, only the truth.
90
+ snap = d.settle();
91
+ const stillSecure = snap.elements.find((element) => element.secure
92
+ || /password|passcode/i.test(`${element.id} ${element.label}`));
93
+ if (stillSecure) {
94
+ throw new Error(`sign-in did not leave the form: ‘${submit.label || submit.id}’ was pressed but the password field is still on screen`);
95
+ }
86
96
  } else if (action === "back") {
87
97
  d.key("escape");
88
98
  } else if (action === "wait_for") {
@@ -126,9 +136,15 @@ export async function runMacosFlow({ flow, appPath, logPath, screenshotDir, driv
126
136
  snap = d.settle();
127
137
  }
128
138
  } catch (error) {
129
- status = "fail";
130
- detail = error.message || String(error);
131
- if (screenshotDir) d.screenshot(path.join(screenshotDir, `flow-failure-${index + 1}.png`), snap);
139
+ // A step the author marked optional reports what it did not find, and the run carries on.
140
+ if (isOptionalStep(raw)) {
141
+ status = "skip";
142
+ detail = `optional — ${error.message || String(error)}`;
143
+ } else {
144
+ status = "fail";
145
+ detail = error.message || String(error);
146
+ if (screenshotDir) d.screenshot(path.join(screenshotDir, `flow-failure-${index + 1}.png`), snap);
147
+ }
132
148
  }
133
149
  log.step({ index: index + 1, action, target: action === "login" ? "sign-in form" : stepTarget || value, status, detail, task: raw.task });
134
150
  if (status === "fail" && !flow.continueOnFailure) break;