blastproof 0.35.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ ActionError,
3
4
  FIELD_ROLES,
4
5
  allowedOriginsFor,
5
6
  bindTarget,
@@ -11,7 +12,7 @@ import {
11
12
  snapshotFields,
12
13
  submitControlOf,
13
14
  withoutRefs
14
- } from "./chunk-7UQT6SVD.js";
15
+ } from "./chunk-VBWOSSGY.js";
15
16
 
16
17
  // src/cli.ts
17
18
  import { Command, InvalidArgumentError } from "commander";
@@ -703,11 +704,13 @@ var StepRecovery = class {
703
704
  return this.history.length > 0;
704
705
  }
705
706
  /** Records an action that was actually performed and succeeded. */
706
- record(action, description, result, activates) {
707
+ record(action, description, result, activates, answers) {
707
708
  const commit = commitIdentity(action, activates);
708
- this.performed.add(identity(action));
709
- this.performed.add(commit);
710
- if (isCommit(action)) this.commitPages.set(commit, this.lastObserved);
709
+ if (answers === void 0) {
710
+ this.performed.add(identity(action));
711
+ this.performed.add(commit);
712
+ if (isCommit(action)) this.commitPages.set(commit, this.lastObserved);
713
+ }
711
714
  const named = activatedControl(action, activates) !== void 0;
712
715
  this.lastSuccess = { commit, own: identity(action), named, page: this.lastObserved, action };
713
716
  this.history.push({ action: description, result });
@@ -729,8 +732,12 @@ var StepRecovery = class {
729
732
  * allowed duplicate commit costs a silent extra row in someone's database,
730
733
  * and #28 has now produced one on three applications.
731
734
  */
732
- refusalFor(action, activates) {
733
- return this.verificationRefusal(action) ?? this.repeatedCommitRefusal(action, activates) ?? this.redactionLabelRefusal(action) ?? this.unsourcedValueRefusal(action);
735
+ refusalFor(action, activates, answers) {
736
+ return (
737
+ // A check may answer an alert, which has one button and decides nothing
738
+ // (design answer-native-dialogs, D6); no other dialog.
739
+ (answers === "alert" ? void 0 : this.verificationRefusal(action)) ?? (answers === void 0 ? this.repeatedCommitRefusal(action, activates) : void 0) ?? this.redactionLabelRefusal(action) ?? this.unsourcedValueRefusal(action)
740
+ );
734
741
  }
735
742
  /**
736
743
  * Refuses a typed value containing a redaction label (design
@@ -862,6 +869,352 @@ var StepRecovery = class {
862
869
  }
863
870
  };
864
871
 
872
+ // src/runner/dialog.ts
873
+ var FrameMap = class {
874
+ frames = /* @__PURE__ */ new Map();
875
+ load(tree, parent) {
876
+ this.frames.set(tree.frame.id, { parent, url: tree.frame.url });
877
+ for (const child of tree.childFrames ?? []) this.load(child, tree.frame.id);
878
+ }
879
+ attached(id, parent) {
880
+ const known = this.frames.get(id);
881
+ this.frames.set(id, { ...known, parent });
882
+ }
883
+ navigated(id, parent, url) {
884
+ this.frames.set(id, { parent, url });
885
+ }
886
+ detached(id) {
887
+ this.frames.delete(id);
888
+ }
889
+ /**
890
+ * The URL a frame's origin is judged by: its own, or for an `about:` frame,
891
+ * or one created and not yet navigated, the first ancestor's that is not
892
+ * `about:`. Such a frame inherits the origin of the page that made it, so a
893
+ * frame of another origin could otherwise open a dialog from a child it
894
+ * created and be judged as `about:blank`. `undefined` for an unknown frame.
895
+ */
896
+ urlFor(id) {
897
+ const seen = /* @__PURE__ */ new Set();
898
+ let at = id;
899
+ while (at !== void 0 && !seen.has(at)) {
900
+ seen.add(at);
901
+ const frame = this.frames.get(at);
902
+ if (!frame) return void 0;
903
+ if (frame.url !== void 0 && !frame.url.startsWith("about:")) return frame.url;
904
+ if (frame.parent === void 0) return frame.url;
905
+ at = frame.parent;
906
+ }
907
+ return void 0;
908
+ }
909
+ };
910
+ var DIALOG_ATTRIBUTION_MS = 1e3;
911
+ var BEFOREUNLOAD_NAME = "This page asks you to confirm that you want to leave";
912
+ var KINDS = /* @__PURE__ */ new Set(["alert", "confirm", "prompt", "beforeunload"]);
913
+ var DIALOG_REF = /^d\d+b\d+$/;
914
+ function isDialogRef(ref) {
915
+ if (ref === void 0) return false;
916
+ return DIALOG_REF.test(ref.trim().replace(/^\[/, "").replace(/^ref=/, "").replace(/\]$/, ""));
917
+ }
918
+ function isDialogSnapshot(snapshot) {
919
+ const first = snapshot.split("\n", 1)[0] ?? "";
920
+ return /^- alertdialog ".*" \[native .+\]:$/.test(first);
921
+ }
922
+ function quoted(text) {
923
+ return `"${text.replace(/\s*\n\s*/g, " ").replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
924
+ }
925
+ function controlsOf(open) {
926
+ const ref = (n) => `d${open.seq}b${n}`;
927
+ switch (open.kind) {
928
+ case "alert":
929
+ return [{ ref: ref(1), role: "button", name: "OK", answer: "accept" }];
930
+ case "confirm":
931
+ return [
932
+ { ref: ref(1), role: "button", name: "OK", answer: "accept" },
933
+ { ref: ref(2), role: "button", name: "Cancel", answer: "dismiss" }
934
+ ];
935
+ case "prompt":
936
+ return [
937
+ { ref: ref(1), role: "textbox", name: open.message },
938
+ { ref: ref(2), role: "button", name: "OK", answer: "accept" },
939
+ { ref: ref(3), role: "button", name: "Cancel", answer: "dismiss" }
940
+ ];
941
+ case "beforeunload":
942
+ return [
943
+ { ref: ref(1), role: "button", name: "Leave", answer: "accept" },
944
+ { ref: ref(2), role: "button", name: "Stay", answer: "dismiss" }
945
+ ];
946
+ }
947
+ }
948
+ function nameOf(open) {
949
+ return open.kind === "beforeunload" ? BEFOREUNLOAD_NAME : open.message;
950
+ }
951
+ var DialogWatch = class {
952
+ constructor(allowed, onHidden, attributionMs = DIALOG_ATTRIBUTION_MS, resolveFrame) {
953
+ this.allowed = allowed;
954
+ this.onHidden = onHidden;
955
+ this.attributionMs = attributionMs;
956
+ this.resolveFrame = resolveFrame;
957
+ }
958
+ allowed;
959
+ onHidden;
960
+ attributionMs;
961
+ resolveFrame;
962
+ open;
963
+ seq = 0;
964
+ openers = /* @__PURE__ */ new Set();
965
+ sources = [];
966
+ /** Dialogs still being attributed, so a dismissal can wait for them (finding 6). */
967
+ attributing = /* @__PURE__ */ new Set();
968
+ closed = false;
969
+ sourceWaiters = /* @__PURE__ */ new Set();
970
+ /** The rest of each action a dialog interrupted (D4), settled after the answer. */
971
+ pending = [];
972
+ closers = [];
973
+ get isOpen() {
974
+ return this.open !== void 0;
975
+ }
976
+ /** Records the frame Chromium says opened a dialog (D5). */
977
+ noteSource(source) {
978
+ this.sources.push({ ...source, at: Date.now() });
979
+ for (const wake of this.sourceWaiters) wake();
980
+ }
981
+ /** Playwright's `dialog` event: hold it, or dismiss it unseen (D5). */
982
+ receive(dialog) {
983
+ const receiving = this.hold(dialog);
984
+ this.attributing.add(receiving);
985
+ void receiving.finally(() => this.attributing.delete(receiving));
986
+ return receiving;
987
+ }
988
+ async hold(dialog) {
989
+ const kind = dialog.type();
990
+ const url = await this.sourceOf(dialog);
991
+ if (this.closed) {
992
+ await dialog.dismiss().catch(() => void 0);
993
+ return;
994
+ }
995
+ if (!KINDS.has(kind) || url === void 0 || !isOriginAllowed(url, this.allowed)) {
996
+ this.onHidden?.(url === void 0 ? void 0 : originOf(url));
997
+ await dialog.dismiss().catch(() => void 0);
998
+ return;
999
+ }
1000
+ const previous = this.open;
1001
+ this.seq++;
1002
+ this.open = { dialog, kind, message: dialog.message(), seq: this.seq, value: dialog.defaultValue() };
1003
+ if (previous) await previous.dialog.dismiss().catch(() => void 0);
1004
+ for (const wake of this.openers) wake();
1005
+ }
1006
+ async sourceOf(dialog) {
1007
+ const deadline = Date.now() + this.attributionMs;
1008
+ while (true) {
1009
+ const stale = Date.now() - 2 * this.attributionMs;
1010
+ this.sources = this.sources.filter((source) => source.at >= stale);
1011
+ const at = this.sources.findIndex((source) => source.type === dialog.type() && source.message === dialog.message());
1012
+ if (at >= 0) {
1013
+ const source = this.sources.splice(at, 1)[0];
1014
+ if (!source.url.startsWith("about:")) return source.url;
1015
+ if (source.frameId === void 0 || this.resolveFrame === void 0) return void 0;
1016
+ return this.resolveFrame(source.frameId);
1017
+ }
1018
+ const left = deadline - Date.now();
1019
+ if (left <= 0) return void 0;
1020
+ await new Promise((resolve) => {
1021
+ const wake = () => {
1022
+ clearTimeout(timer);
1023
+ this.sourceWaiters.delete(wake);
1024
+ resolve();
1025
+ };
1026
+ const timer = setTimeout(wake, left);
1027
+ this.sourceWaiters.add(wake);
1028
+ });
1029
+ }
1030
+ }
1031
+ /**
1032
+ * Waits for `work`, or for a dialog to open, whichever comes first (D4). When
1033
+ * a dialog opens, `work` is left running and handed back as `rest`: it
1034
+ * settles once the dialog is answered.
1035
+ */
1036
+ async race(work) {
1037
+ if (this.open) {
1038
+ work.catch(() => void 0);
1039
+ return { opened: true, rest: work };
1040
+ }
1041
+ let wake = () => void 0;
1042
+ const opened = new Promise((resolve) => {
1043
+ wake = () => resolve("opened");
1044
+ this.openers.add(wake);
1045
+ });
1046
+ try {
1047
+ const first = await Promise.race([work.then((value) => ({ value })), opened]);
1048
+ if (first === "opened") {
1049
+ work.catch(() => void 0);
1050
+ return { opened: true, rest: work };
1051
+ }
1052
+ return { opened: false, value: first.value };
1053
+ } finally {
1054
+ this.openers.delete(wake);
1055
+ }
1056
+ }
1057
+ /** Keeps the rest of an interrupted action, to settle after the answer (D4). */
1058
+ keep(rest) {
1059
+ this.pending.push(
1060
+ rest.then(
1061
+ () => void 0,
1062
+ (error) => error instanceof Error ? error.message : String(error)
1063
+ )
1064
+ );
1065
+ }
1066
+ /**
1067
+ * Settles the rest of every interrupted action, unless another dialog opens
1068
+ * first, and returns what any of them failed with. Called after an answer and
1069
+ * before every wait for the page, so nothing of an action is still running
1070
+ * when the page is read (D4).
1071
+ */
1072
+ async drain() {
1073
+ if (this.pending.length === 0 || this.open) return void 0;
1074
+ const waiting = this.pending;
1075
+ const raced = await this.race(Promise.all(waiting));
1076
+ if (raced.opened) return void 0;
1077
+ this.pending = this.pending.filter((entry) => !waiting.includes(entry));
1078
+ const errors = raced.value.filter((error) => error !== void 0);
1079
+ return errors.length === 0 ? void 0 : errors.join("; ");
1080
+ }
1081
+ /** The open dialog as snapshot lines, or `undefined` when none is open (D2). */
1082
+ lines() {
1083
+ const open = this.open;
1084
+ if (!open) return void 0;
1085
+ const out = [
1086
+ `- alertdialog ${quoted(nameOf(open))} [native ${open.kind}]:`,
1087
+ // Context for every model. Not the guarantee: a claim about the page passed
1088
+ // on it (#218), so `judge()` fails one by rule (`isDialogSnapshot`,
1089
+ // `behindTheDialog`).
1090
+ " - text: The page behind this dialog cannot be seen until the dialog is answered."
1091
+ ];
1092
+ for (const control of controlsOf(open)) {
1093
+ const value = control.role === "textbox" && open.value !== "" ? `: ${open.value.replace(/\s*\n\s*/g, " ")}` : "";
1094
+ out.push(` - ${control.role} ${quoted(control.name)} [ref=${control.ref}]${value}`);
1095
+ }
1096
+ return out.join("\n");
1097
+ }
1098
+ /** The open dialog's name, as its line shows it. */
1099
+ name() {
1100
+ return this.open ? nameOf(this.open) : void 0;
1101
+ }
1102
+ /** The kind of the open dialog. */
1103
+ kind() {
1104
+ return this.open?.kind;
1105
+ }
1106
+ /** The open dialog, as an action's result names it. */
1107
+ describe() {
1108
+ const open = this.open;
1109
+ return open ? `a native ${open.kind} dialog ${quoted(nameOf(open))}` : "a native dialog";
1110
+ }
1111
+ /**
1112
+ * How the step's rules treat `action` (D6): `'alert'` or `'dialog'` when it
1113
+ * answers the open dialog, `undefined` when it acts on the page.
1114
+ */
1115
+ answering(action) {
1116
+ if (!isDialogRef(action.target?.ref)) return void 0;
1117
+ return this.open?.kind === "alert" ? "alert" : "dialog";
1118
+ }
1119
+ /**
1120
+ * Performs an action on the open dialog (D3): a click on a button answers it,
1121
+ * a fill of a prompt's textbox sets the value its OK will send. `value` is
1122
+ * already resolved from its placeholder.
1123
+ */
1124
+ async perform(action, value) {
1125
+ const open = this.open;
1126
+ const ref = action.target?.ref?.trim().replace(/^\[/, "").replace(/^ref=/, "").replace(/\]$/, "");
1127
+ const control = open ? controlsOf(open).find((candidate) => candidate.ref === ref) : void 0;
1128
+ if (!open || !control) {
1129
+ throw new ActionError(
1130
+ `Element not found: ref ${ref ?? "(none)"} belonged to a native dialog that is no longer open. Choose the element again from the fresh snapshot.`
1131
+ );
1132
+ }
1133
+ if (action.action === "fill" && control.role === "textbox") {
1134
+ open.value = value ?? "";
1135
+ return `ok: filled the textbox of ${this.describe()}`;
1136
+ }
1137
+ if (action.action === "click" && control.answer !== void 0) {
1138
+ const described = this.describe();
1139
+ this.open = void 0;
1140
+ if (control.answer === "accept") {
1141
+ await open.dialog.accept(open.kind === "prompt" ? open.value : void 0);
1142
+ return `ok: accepted ${described} (clicked "${control.name}")`;
1143
+ }
1144
+ await open.dialog.dismiss();
1145
+ return `ok: dismissed ${described} (clicked "${control.name}")`;
1146
+ }
1147
+ throw new ActionError(
1148
+ `${action.action} cannot act on ${control.role} "${control.name}" of ${this.describe()}: a native dialog is answered by clicking one of its buttons${open.kind === "prompt" ? ", after filling its textbox if the step gives a value" : ""}.`
1149
+ );
1150
+ }
1151
+ /** Dismisses a dialog still open, so the page can close or be captured (D8). */
1152
+ async dismissOpen() {
1153
+ await Promise.all([...this.attributing]);
1154
+ const open = this.open;
1155
+ if (!open) return;
1156
+ this.open = void 0;
1157
+ await open.dialog.dismiss().catch(() => void 0);
1158
+ }
1159
+ /** Dismisses what is open and stops listening (D8). */
1160
+ async close() {
1161
+ this.closed = true;
1162
+ await this.dismissOpen();
1163
+ for (const closer of this.closers.splice(0)) {
1164
+ try {
1165
+ await closer();
1166
+ } catch {
1167
+ }
1168
+ }
1169
+ }
1170
+ /** Registers what {@link close} undoes. */
1171
+ onClose(closer) {
1172
+ this.closers.push(closer);
1173
+ }
1174
+ };
1175
+ function originOf(url) {
1176
+ try {
1177
+ const origin = new URL(url).origin;
1178
+ return origin === "null" ? void 0 : origin;
1179
+ } catch {
1180
+ return void 0;
1181
+ }
1182
+ }
1183
+ async function watchDialogs(page, allowed, onHidden, attributionMs = DIALOG_ATTRIBUTION_MS) {
1184
+ const target = page;
1185
+ if (typeof target.on !== "function") return new DialogWatch(allowed, onHidden, attributionMs);
1186
+ let session;
1187
+ try {
1188
+ session = await target.context().newCDPSession(page);
1189
+ } catch {
1190
+ }
1191
+ const frames = new FrameMap();
1192
+ const watch = new DialogWatch(allowed, onHidden, attributionMs, session ? (id) => frames.urlFor(id) : void 0);
1193
+ if (session) {
1194
+ watch.onClose(() => session.detach());
1195
+ try {
1196
+ session.on("Page.javascriptDialogOpening", (source) => watch.noteSource(source));
1197
+ session.on(
1198
+ "Page.frameAttached",
1199
+ (event) => frames.attached(event.frameId, event.parentFrameId)
1200
+ );
1201
+ session.on(
1202
+ "Page.frameNavigated",
1203
+ (event) => frames.navigated(event.frame.id, event.frame.parentId, event.frame.url)
1204
+ );
1205
+ session.on("Page.frameDetached", (event) => frames.detached(event.frameId));
1206
+ await session.send("Page.enable");
1207
+ const { frameTree } = await session.send("Page.getFrameTree");
1208
+ frames.load(frameTree);
1209
+ } catch {
1210
+ }
1211
+ }
1212
+ const listener = (dialog) => void watch.receive(dialog);
1213
+ target.on("dialog", listener);
1214
+ watch.onClose(() => target.off?.("dialog", listener));
1215
+ return watch;
1216
+ }
1217
+
865
1218
  // src/runner/replay.ts
866
1219
  import { createHash } from "crypto";
867
1220
  import { mkdir as mkdir2, readFile, rename, writeFile as writeFile2 } from "fs/promises";
@@ -884,11 +1237,13 @@ function refOf(saved, refs) {
884
1237
  return found;
885
1238
  }
886
1239
  var REPLAYED = "replayed from the last passing run";
887
- function replayedDecision(entry, at, refs) {
1240
+ function replayedDecision(entry, at, refs, openDialog) {
888
1241
  const saved = entry.actions[at];
889
1242
  if (saved === void 0) {
890
1243
  return entry.close.by === "done" ? { action: "done", reasoning: REPLAYED } : { action: "assert", expectation: entry.close.claim, reasoning: REPLAYED };
891
1244
  }
1245
+ if (saved.dialog === void 0 !== (openDialog === void 0)) return void 0;
1246
+ if (saved.dialog !== void 0 && normalise2(saved.dialog) !== normalise2(openDialog)) return void 0;
892
1247
  const action = saved.action;
893
1248
  if (saved.role === void 0) return { action, value: saved.value, reasoning: REPLAYED };
894
1249
  const ref = refOf(saved, refs);
@@ -915,7 +1270,7 @@ var optionalString = (value) => value === void 0 || typeof value === "string";
915
1270
  function isSavedAction(value) {
916
1271
  if (typeof value !== "object" || value === null) return false;
917
1272
  const action = value;
918
- return typeof action.action === "string" && PERFORMED_ACTIONS.has(action.action) && typeof action.changed === "boolean" && optionalString(action.role) && optionalString(action.name) && optionalString(action.value);
1273
+ return typeof action.action === "string" && PERFORMED_ACTIONS.has(action.action) && typeof action.changed === "boolean" && optionalString(action.role) && optionalString(action.name) && optionalString(action.value) && optionalString(action.dialog);
919
1274
  }
920
1275
  function isSavedStep(value) {
921
1276
  if (typeof value !== "object" || value === null) return false;
@@ -973,7 +1328,7 @@ async function waitForSettled(page) {
973
1328
  }
974
1329
  }
975
1330
  async function defaultSnapshot(page, maxLines, frames) {
976
- const { captureSnapshot } = await import("./snapshot-6C7FIWW7.js");
1331
+ const { captureSnapshot } = await import("./snapshot-RHSNLK3X.js");
977
1332
  return captureSnapshot(page, { maxLines, frames });
978
1333
  }
979
1334
  function slugify(text) {
@@ -1008,6 +1363,11 @@ function pageChangeNote(before, after) {
1008
1363
  const lines = [...removed.map((line) => `- ${line.trim()}`), ...added.map((line) => `+ ${line.trim()}`)];
1009
1364
  return ` (after it, the only change on the page: ${lines.join("; ")})`;
1010
1365
  }
1366
+ function dialogAnswerNote(before, after) {
1367
+ const unfocused = (page) => page.replace(/ \[active\]/g, "");
1368
+ const note = pageChangeNote(unfocused(before), unfocused(after));
1369
+ return note === " (after it, the page did not change at all)" ? " (the dialog is closed, and the page behind it is as it was before the dialog opened)" : note?.replace(" (after it, the only change on the page:", " (the dialog is closed; the only change on the page since before it opened:");
1370
+ }
1011
1371
  function pageDiffers(before, after) {
1012
1372
  const lines = (page) => new Set(page.replace(/ \[active\]/g, "").split("\n"));
1013
1373
  const a = lines(before);
@@ -1017,6 +1377,18 @@ function pageDiffers(before, after) {
1017
1377
  return false;
1018
1378
  }
1019
1379
  async function executeTest(page, test, options) {
1380
+ const dialogs = await watchDialogs(
1381
+ page,
1382
+ allowedOriginsFor(options.baseUrl, options.allowedOrigins),
1383
+ options.onHiddenDialog
1384
+ );
1385
+ try {
1386
+ return await runTest(page, test, options, dialogs);
1387
+ } finally {
1388
+ await dialogs.close();
1389
+ }
1390
+ }
1391
+ async function runTest(page, test, options, dialogs) {
1020
1392
  const {
1021
1393
  brain,
1022
1394
  sessionDir,
@@ -1039,7 +1411,32 @@ async function executeTest(page, test, options) {
1039
1411
  const savedByKey = new Map((replay?.saved ?? []).map((entry) => [entry.key, entry]));
1040
1412
  const replayOutcome = { steps: [], ended: [] };
1041
1413
  const boundary = allowedOriginsFor(baseUrl, allowedOrigins);
1042
- const takeSnapshot = snapshot ?? ((page2) => defaultSnapshot(page2, maxSnapshotLines, { allowed: boundary, onHidden: onHiddenFrame }));
1414
+ const pageSnapshot = snapshot ?? ((page2) => defaultSnapshot(page2, maxSnapshotLines, { allowed: boundary, onHidden: onHiddenFrame }));
1415
+ let lastPageView;
1416
+ let pageBeforeDialog;
1417
+ const takeSnapshot = async (page2) => {
1418
+ const shown = dialogs.lines();
1419
+ if (shown !== void 0) {
1420
+ pageBeforeDialog ??= lastPageView;
1421
+ return shown;
1422
+ }
1423
+ const raced = await dialogs.race(pageSnapshot(page2));
1424
+ if (raced.opened) {
1425
+ dialogs.keep(raced.rest);
1426
+ pageBeforeDialog ??= lastPageView;
1427
+ return dialogs.lines();
1428
+ }
1429
+ lastPageView = withoutRefs(mask(raced.value));
1430
+ return raced.value;
1431
+ };
1432
+ const settle = async () => {
1433
+ const late = await dialogs.drain();
1434
+ if (!dialogs.isOpen) {
1435
+ const raced = await dialogs.race(waitForSettled(page));
1436
+ if (raced.opened) dialogs.keep(raced.rest);
1437
+ }
1438
+ return late;
1439
+ };
1043
1440
  const startedAt = Date.now();
1044
1441
  const stepResults = [];
1045
1442
  const allSteps = [
@@ -1056,7 +1453,8 @@ async function executeTest(page, test, options) {
1056
1453
  onEvent({ type: "action", index, action: maskedAction, result: mask(result) });
1057
1454
  };
1058
1455
  let failure;
1059
- await page.goto(new URL(baseUrl).toString());
1456
+ const opening = await dialogs.race(page.goto(new URL(baseUrl).toString()));
1457
+ if (opening.opened) dialogs.keep(opening.rest);
1060
1458
  const usedEarlier = /* @__PURE__ */ new Set();
1061
1459
  for (let index = 0; index < allSteps.length; index++) {
1062
1460
  const { step: written, setup } = allSteps[index];
@@ -1066,6 +1464,12 @@ async function executeTest(page, test, options) {
1066
1464
  onEvent({ type: "step-start", index, total: allSteps.length, step: mask(written), setup });
1067
1465
  let iterations = 0;
1068
1466
  let failedAttempts = 0;
1467
+ let failuresOnPage = 0;
1468
+ let firstFailure;
1469
+ const failedOnPage = (result) => {
1470
+ failuresOnPage++;
1471
+ firstFailure ??= mask(result ?? "");
1472
+ };
1069
1473
  let lastResult;
1070
1474
  let stepFailedReason;
1071
1475
  let lastSnapshot;
@@ -1073,6 +1477,7 @@ async function executeTest(page, test, options) {
1073
1477
  const recovery = new StepRecovery(written, step);
1074
1478
  const agentRecord = [];
1075
1479
  let pageActedOn;
1480
+ let answeredDialog = false;
1076
1481
  const key = stepKey(index, setup, written, step);
1077
1482
  let live = replay ? savedByKey.get(key) : void 0;
1078
1483
  const hadSaved = live !== void 0;
@@ -1093,7 +1498,14 @@ async function executeTest(page, test, options) {
1093
1498
  if (iterations >= maxIterationsPerStep) {
1094
1499
  throw new StepFailure(`step exceeded ${maxIterationsPerStep} actions without completing`);
1095
1500
  }
1096
- await waitForSettled(page);
1501
+ const late = await settle();
1502
+ if (late !== void 0 && lastResult !== void 0) {
1503
+ const failed = `; after the dialog was answered, the action that opened it failed: ${mask(late)}`;
1504
+ failedOnPage(`error: ${late}`);
1505
+ lastResult += failed;
1506
+ const acted = agentRecord[agentRecord.length - 1];
1507
+ if (acted !== void 0) acted.result += failed;
1508
+ }
1097
1509
  if (!isOriginAllowed(page.url(), boundary)) {
1098
1510
  throw new StepFailure(
1099
1511
  `The page left the application: ${page.url()} is outside ${describeBoundary(boundary)}. Add it to allowed_origins in .blastproof/config.yaml if the app legitimately spans hosts.`
@@ -1125,7 +1537,8 @@ async function executeTest(page, test, options) {
1125
1537
  lastReplayed = void 0;
1126
1538
  }
1127
1539
  if (pageActedOn !== void 0) {
1128
- const note = pageChangeNote(pageActedOn, pageSnap);
1540
+ const note = answeredDialog ? dialogs.isOpen ? void 0 : dialogAnswerNote(pageActedOn, pageSnap) : pageChangeNote(pageActedOn, pageSnap);
1541
+ answeredDialog = false;
1129
1542
  const acted = agentRecord[agentRecord.length - 1];
1130
1543
  if (note !== void 0 && acted !== void 0 && lastResult !== void 0) {
1131
1544
  acted.result += note;
@@ -1134,7 +1547,7 @@ async function executeTest(page, test, options) {
1134
1547
  pageActedOn = void 0;
1135
1548
  }
1136
1549
  let action;
1137
- const saved = live === void 0 ? void 0 : replayedDecision(live, replayAt, refs);
1550
+ const saved = live === void 0 ? void 0 : replayedDecision(live, replayAt, refs, dialogs.isOpen ? mask(dialogs.name()) : void 0);
1138
1551
  if (live !== void 0 && saved === void 0) endReplay("a saved element is not on the page exactly once");
1139
1552
  const replayed = saved !== void 0;
1140
1553
  if (saved !== void 0) action = saved;
@@ -1164,6 +1577,19 @@ async function executeTest(page, test, options) {
1164
1577
  iterations++;
1165
1578
  let judgingDone = false;
1166
1579
  const shown = () => judgingDone ? { ...action, action: "done" } : action;
1580
+ if (action.action === "done" && dialogs.isOpen && dialogs.kind() !== "alert") {
1581
+ lastResult = `refused: ${dialogs.describe()} is still open, so the step was NOT closed. If this step says how to answer it, click that button. If it does not, assert that the dialog is shown, and leave the answer to the step that names it.`;
1582
+ if (replayed) {
1583
+ endReplay("its saved close came while a dialog was open");
1584
+ lastResult = void 0;
1585
+ continue;
1586
+ }
1587
+ failedAttempts++;
1588
+ failedOnPage(lastResult);
1589
+ emitAction(index, action, lastResult);
1590
+ if (failedAttempts >= maxRetries) throw new StepFailure(lastResult);
1591
+ continue;
1592
+ }
1167
1593
  if (action.action === "done") {
1168
1594
  if (!recovery.acted || recovery.verifies) {
1169
1595
  lastResult = recovery.verifies ? VERIFICATION_DONE_REFUSAL : NOTHING_DONE_REFUSAL;
@@ -1173,6 +1599,7 @@ async function executeTest(page, test, options) {
1173
1599
  continue;
1174
1600
  }
1175
1601
  failedAttempts++;
1602
+ failedOnPage(lastResult);
1176
1603
  emitAction(index, action, lastResult);
1177
1604
  if (failedAttempts >= maxRetries) {
1178
1605
  throw new StepFailure(lastResult);
@@ -1214,7 +1641,7 @@ async function executeTest(page, test, options) {
1214
1641
  [...usedEarlier]
1215
1642
  );
1216
1643
  if (!judgment.pass) {
1217
- await waitForSettled(page);
1644
+ await settle();
1218
1645
  const freshSnap = await takeSnapshot(page);
1219
1646
  lastSnapshot = freshSnap;
1220
1647
  const maskedFresh = withoutRefs(mask(freshSnap));
@@ -1257,6 +1684,7 @@ async function executeTest(page, test, options) {
1257
1684
  continue;
1258
1685
  }
1259
1686
  failedAttempts++;
1687
+ failedOnPage(result);
1260
1688
  lastResult = result;
1261
1689
  if (failedAttempts >= maxRetries) {
1262
1690
  throw new StepFailure(judgment.reason);
@@ -1273,14 +1701,21 @@ async function executeTest(page, test, options) {
1273
1701
  continue;
1274
1702
  }
1275
1703
  failedAttempts++;
1704
+ failedOnPage(lastResult);
1276
1705
  emitAction(index, action, lastResult);
1277
1706
  if (failedAttempts >= maxRetries) {
1278
1707
  throw new StepFailure(lastResult);
1279
1708
  }
1280
1709
  continue;
1281
1710
  }
1282
- const activates = await submitControl(page, action, refs);
1283
- const refusal = recovery.refusalFor(action, activates);
1711
+ const answers = dialogs.answering(action);
1712
+ let activates;
1713
+ if (answers === void 0 && !dialogs.isOpen) {
1714
+ const looked = await dialogs.race(submitControl(page, action, refs));
1715
+ activates = looked.opened ? void 0 : looked.value;
1716
+ if (looked.opened) void looked.rest.then((control) => control?.activated());
1717
+ }
1718
+ const refusal = answers === void 0 && dialogs.isOpen ? `refused: ${dialogs.describe()} is open, and nothing on the page can be reached until it is answered, so nothing was done. Click the dialog button the step calls for.` : recovery.refusalFor(action, activates, answers);
1284
1719
  if (refusal && replayed) {
1285
1720
  void activates?.activated();
1286
1721
  endReplay(`a saved action was refused (${refusal})`);
@@ -1288,7 +1723,11 @@ async function executeTest(page, test, options) {
1288
1723
  }
1289
1724
  if (refusal) {
1290
1725
  void activates?.activated();
1291
- failedAttempts++;
1726
+ const unseenDialog = answers === void 0 && dialogs.isOpen && ![...refs.keys()].some(isDialogRef);
1727
+ if (!unseenDialog) {
1728
+ failedAttempts++;
1729
+ failedOnPage(refusal);
1730
+ }
1292
1731
  lastResult = refusal;
1293
1732
  emitAction(index, action, refusal);
1294
1733
  if (failedAttempts >= maxRetries) {
@@ -1296,25 +1735,56 @@ async function executeTest(page, test, options) {
1296
1735
  }
1297
1736
  continue;
1298
1737
  }
1738
+ const answeredName = answers === void 0 ? void 0 : dialogs.name();
1299
1739
  try {
1300
- const result = await performAction(page, action, {
1740
+ const performing = performAction(page, action, {
1301
1741
  baseUrl,
1302
1742
  allowedOrigins,
1303
1743
  resolveValue,
1304
- resolveTimeoutMs: timeoutMs
1744
+ resolveTimeoutMs: timeoutMs,
1745
+ dialogs
1305
1746
  });
1747
+ const raced = answers === void 0 ? await dialogs.race(performing) : { opened: false, value: await performing };
1748
+ let result;
1749
+ let activated;
1750
+ if (raced.opened) {
1751
+ result = `ok: ${describeAction(action)}, which opened ${dialogs.describe()}`;
1752
+ activated = activates;
1753
+ dialogs.keep(raced.rest.then(() => activates?.activated()));
1754
+ } else {
1755
+ result = raced.value;
1756
+ if (activates === void 0) {
1757
+ activated = void 0;
1758
+ } else {
1759
+ const asked = await dialogs.race(activates.activated());
1760
+ if (asked.opened) dialogs.keep(asked.rest);
1761
+ activated = asked.opened || asked.value ? activates : void 0;
1762
+ }
1763
+ }
1764
+ if (answers !== void 0) {
1765
+ const after = await dialogs.drain();
1766
+ if (after !== void 0) {
1767
+ result += `; after the answer, the action that opened it failed: ${after}`;
1768
+ failedOnPage(`error: ${after}`);
1769
+ }
1770
+ }
1306
1771
  lastResult = result;
1307
- const activated = activates !== void 0 && await activates.activated() ? activates : void 0;
1308
- recovery.record(action, mask(describeAction(action)), mask(result), activated);
1772
+ recovery.record(action, mask(describeAction(action)), mask(result), activated, answers);
1309
1773
  agentRecord.push({ action: mask(describeAction(action)), result: mask(result) });
1310
1774
  pageActedOn = pageSnap;
1775
+ if (answers !== void 0 && pageBeforeDialog !== void 0 && !dialogs.isOpen) {
1776
+ pageActedOn = pageBeforeDialog;
1777
+ pageBeforeDialog = void 0;
1778
+ answeredDialog = true;
1779
+ }
1311
1780
  emitAction(index, action, result);
1312
1781
  performed.push({
1313
1782
  action: action.action,
1314
1783
  ...action.target?.role === void 0 ? {} : { role: action.target.role },
1315
1784
  ...action.target?.name === void 0 ? {} : { name: mask(action.target.name) },
1316
1785
  ...action.value === void 0 ? {} : { value: mask(action.value) },
1317
- changed: false
1786
+ changed: false,
1787
+ ...answeredName === void 0 ? {} : { dialog: mask(answeredName) }
1318
1788
  });
1319
1789
  if (replayed && live !== void 0) {
1320
1790
  lastReplayed = live.actions[replayAt];
@@ -1329,6 +1799,7 @@ async function executeTest(page, test, options) {
1329
1799
  continue;
1330
1800
  }
1331
1801
  failedAttempts++;
1802
+ failedOnPage(lastResult);
1332
1803
  if (failedAttempts >= maxRetries) {
1333
1804
  throw new StepFailure(lastResult);
1334
1805
  }
@@ -1340,7 +1811,7 @@ async function executeTest(page, test, options) {
1340
1811
  if (step !== written && error instanceof StepFailure && recovery.acted) {
1341
1812
  const check = following.step;
1342
1813
  try {
1343
- await waitForSettled(page);
1814
+ await settle();
1344
1815
  if (isOriginAllowed(page.url(), boundary)) {
1345
1816
  const snap = await takeSnapshot(page);
1346
1817
  lastSnapshot = snap;
@@ -1356,6 +1827,7 @@ async function executeTest(page, test, options) {
1356
1827
  };
1357
1828
  if (judgment.pass) {
1358
1829
  emitAction(index, asked, `ok: the check after this step holds: ${judgment.reason}`);
1830
+ if (failuresOnPage === 0) failedOnPage(stepFailedReason);
1359
1831
  stepFailedReason = void 0;
1360
1832
  const acted = performed[performed.length - 1];
1361
1833
  if (acted !== void 0 && pageActedOn !== void 0) acted.changed = pageDiffers(pageActedOn, pageSnap);
@@ -1391,7 +1863,8 @@ async function executeTest(page, test, options) {
1391
1863
  failedAttempts,
1392
1864
  reason: stepFailedReason,
1393
1865
  durationMs: Date.now() - stepStartedAt,
1394
- ...decidedBy ? { decidedBy } : {}
1866
+ ...decidedBy ? { decidedBy } : {},
1867
+ ...status === "passed" && failuresOnPage > 0 ? { recovered: { attempts: failuresOnPage, first: firstFailure } } : {}
1395
1868
  });
1396
1869
  onEvent({ type: "step-end", index, status, reason: stepFailedReason });
1397
1870
  if (stepFailedReason) {
@@ -1401,6 +1874,7 @@ async function executeTest(page, test, options) {
1401
1874
  }
1402
1875
  let screenshot;
1403
1876
  if (failure) {
1877
+ await dialogs.dismissOpen();
1404
1878
  try {
1405
1879
  await mkdir3(sessionDir, { recursive: true });
1406
1880
  const stem = `${slugify(test.summary)}-${slugify(path3.basename(test.path))}`;
@@ -1683,7 +2157,8 @@ async function fromSteps(options) {
1683
2157
  timeoutMs,
1684
2158
  mask: (text) => mask.mask(text),
1685
2159
  snapshot: takeSnapshot,
1686
- onEvent
2160
+ onEvent,
2161
+ onHiddenDialog: options.onHiddenDialog
1687
2162
  }
1688
2163
  );
1689
2164
  if (result.status === "failed") {
@@ -2112,10 +2587,14 @@ async function getUncommittedFiles(cwd = process.cwd()) {
2112
2587
  if (from) paths.add(from.replace(/\\/g, "/"));
2113
2588
  }
2114
2589
  return [...paths].sort();
2115
- } catch {
2116
- return [];
2590
+ } catch (error) {
2591
+ const message = error instanceof Error ? error.message : String(error);
2592
+ return { unreadable: message.split(/\r?\n/).find((line) => line.trim() !== "")?.trim() ?? "git status failed" };
2117
2593
  }
2118
2594
  }
2595
+ function uncommittedPaths(files) {
2596
+ return Array.isArray(files) ? files : [];
2597
+ }
2119
2598
 
2120
2599
  // src/impact.ts
2121
2600
  import picomatch from "picomatch";
@@ -2171,16 +2650,27 @@ function hiddenFrameWarning(origin) {
2171
2650
  lines: [`Add it to allowed_origins in .blastproof/config.yaml if the agent should read and act on it.`]
2172
2651
  };
2173
2652
  }
2653
+ function hiddenDialogWarning(origin) {
2654
+ if (origin === void 0) {
2655
+ return {
2656
+ kind: "hidden-dialog",
2657
+ title: "warning: a native dialog was dismissed without being shown to the agent: the browser did not say which frame opened it.",
2658
+ lines: ["Dialogs are attributed through Chromium; a step that needed this one failed or was decided without it."]
2659
+ };
2660
+ }
2661
+ return {
2662
+ kind: "hidden-dialog",
2663
+ title: `warning: a native dialog from ${origin} was dismissed without being shown to the agent: it came from a frame not in allowed_origins.`,
2664
+ lines: ["Add it to allowed_origins in .blastproof/config.yaml if the agent should read and answer it."]
2665
+ };
2666
+ }
2174
2667
 
2175
2668
  // src/report/uncommitted.ts
2176
2669
  function printUncommitted(uncommitted, changedFiles, config, baseRef, into) {
2177
2670
  emitWarning(uncommittedWarning(uncommitted, changedFiles, config, baseRef), into);
2178
2671
  }
2179
2672
  function uncommittedWarning(uncommitted, changedFiles, config, baseRef) {
2180
- const inDiff = new Set(changedFiles.map((file) => file.replace(/\\/g, "/")));
2181
- const routes = config.routes ?? {};
2182
- const ignore = config.ignore ?? [];
2183
- const findings = uncommitted.filter((file) => !inDiff.has(file)).map((file) => ({ file, impact: mapImpact([file], routes, ignore) })).filter(({ impact }) => impact.ignoredFiles.length === 0);
2673
+ const findings = classifyUncommitted(uncommitted, changedFiles, config);
2184
2674
  if (findings.length === 0) return void 0;
2185
2675
  return {
2186
2676
  kind: "uncommitted",
@@ -2194,6 +2684,15 @@ function uncommittedWarning(uncommitted, changedFiles, config, baseRef) {
2194
2684
  spaced: true
2195
2685
  };
2196
2686
  }
2687
+ function unclassifiedUncommitted(uncommitted, changedFiles, config) {
2688
+ return classifyUncommitted(uncommitted, changedFiles, config).filter(({ impact }) => impact.unmappedFiles.length > 0).map(({ file }) => file);
2689
+ }
2690
+ function classifyUncommitted(uncommitted, changedFiles, config) {
2691
+ const inDiff = new Set(changedFiles.map((file) => file.replace(/\\/g, "/")));
2692
+ const routes = config.routes ?? {};
2693
+ const ignore = config.ignore ?? [];
2694
+ return uncommitted.filter((file) => !inDiff.has(file)).map((file) => ({ file, impact: mapImpact([file], routes, ignore) })).filter(({ impact }) => impact.ignoredFiles.length === 0);
2695
+ }
2197
2696
 
2198
2697
  // src/llm/brain.ts
2199
2698
  import { APICallError as APICallError2, generateObject, NoObjectGeneratedError, RetryError } from "ai";
@@ -2211,6 +2710,7 @@ Rules:
2211
2710
  - Placeholders like {{env.SOME_NAME}} are secrets that are filled in after you answer. Pass them through in your action exactly as written, never expanded, never guessed at.
2212
2711
  - Pick target elements exclusively from the current snapshot. Every element there carries a ref, like \`[ref=f1e25]\`: name your target by that ref, and give its role and name exactly as that same line shows them (the text after the colon when it has no quoted name). The ref decides which element is acted on, so copy it from the line of the element you mean; a role or name that does not match that line is refused. Refs change when the page changes, so always take them from the current snapshot. Never invent CSS selectors or guess elements not in the snapshot.
2213
2712
  - Use "navigate" only with a URL or path as value. Use "fill" to type into textboxes/inputs. Use "press" for keyboard keys (value e.g. "Enter"). Use "select" for dropdowns (value = option label). Use "hover" to point at an element without clicking it, when a menu, tooltip or control appears only on hover.
2713
+ - A native browser dialog (alert, confirm, prompt, or one asking to leave the page) shows as an "alertdialog" line marked [native \u2026] with its buttons, and while it is open nothing else on the page can be reached. Answer it by clicking the button the step calls for; for a prompt, fill its textbox first when the step gives a value. In a step that only looks, answer only an alert.
2214
2714
  - Use "assert" with an expectation to verify page state (visible text, counts, URLs). Assertions never modify the page.
2215
2715
  - A step that begins with "verify", "check", "confirm", "ensure", "assert", "expect", "validate", "make sure" or "see that" only looks. Never click or press in it: making the page show what the step checks would hide the very thing it checks. Assert what the page shows, navigate if what it names is on another page, or fail. It closes on a passing assertion, never on "done". This is enforced: a click, a press or "done" in such a step is refused.
2216
2716
  - Return "done" when the current step's outcome holds \u2014 including when it already held before you acted, or was achieved by your previous action. "Already true" is done, never failure. Do not return "done" for work belonging to later steps.
@@ -2261,7 +2761,7 @@ Be strict about what the step asks, not about withholding a pass you can plainly
2261
2761
 
2262
2762
  \`[redacted NAME]\` marks the value of {{env.NAME}}, deliberately withheld from you. Seeing one is expected. A field holding a label is filled, not empty, so do not fail a step on the grounds that a value was redacted. The same label is the same value, and two different labels are two different values: a step expecting \`[redacted A]\` is not satisfied by a page showing \`[redacted B]\`. This applies only to the redaction itself: everything else the step asks for must still be visibly satisfied by the snapshot, and a step you genuinely cannot check against what you were shown still fails.`;
2263
2763
  }
2264
- function assertUserPrompt(step, expectation, snapshot, stepHistory) {
2764
+ function assertUserPrompt(step, expectation, snapshot, stepHistory, dialog = false) {
2265
2765
  const parts = [`Step under test: ${step}`];
2266
2766
  if (stepHistory && stepHistory.length > 0) {
2267
2767
  parts.push(
@@ -2276,9 +2776,15 @@ function assertUserPrompt(step, expectation, snapshot, stepHistory) {
2276
2776
  "",
2277
2777
  "Page accessibility snapshot:",
2278
2778
  snapshot,
2279
- "",
2280
- "Does the snapshot establish that the step's own outcome holds?"
2779
+ ""
2281
2780
  );
2781
+ if (dialog) {
2782
+ parts.push(
2783
+ "This snapshot is a native browser dialog, and nothing else: the page behind it cannot be seen until the dialog is answered. Say where the outcome would be seen. Only the dialog itself (its message, its buttons, its field) can show anything here.",
2784
+ ""
2785
+ );
2786
+ }
2787
+ parts.push("Does the snapshot establish that the step's own outcome holds?");
2282
2788
  return parts.join("\n");
2283
2789
  }
2284
2790
  function firstJudgeQuestion() {
@@ -2595,6 +3101,14 @@ var assertJudgmentSchema = z2.object({
2595
3101
  "Whether the snapshot shows that outcome. The expectation is only a claim offered in support; it never replaces the step. False if any part of the outcome the step asks for is not shown, or cannot be assessed from this snapshot. An action the step names (click, dismiss, submit) is how its outcome is reached, not part of it: an outcome that holds passes whether or not that action was needed. An outcome that is an absence (gone, closed, dismissed, removed) is shown by the thing being absent. Where the step says the outcome appears (in the confirmation, in the list, for this order) is part of it: a value found only somewhere else on the page is false."
2596
3102
  )
2597
3103
  });
3104
+ var assertDialogJudgmentSchema = z2.object({
3105
+ outcome: assertJudgmentSchema.shape.outcome,
3106
+ seen: z2.enum(["dialog", "page"]).describe(
3107
+ 'Where that outcome would be seen. "dialog" if every part of it is shown by the native dialog itself: its message, its buttons, its field, that it is open. "page" if any part of it concerns the page behind the dialog, which cannot be seen while the dialog is open.'
3108
+ ),
3109
+ reason: assertJudgmentSchema.shape.reason,
3110
+ pass: assertJudgmentSchema.shape.pass
3111
+ });
2598
3112
  var generatedTestSchema = z2.object({
2599
3113
  summary: z2.string().min(1).describe('One line naming the user journey this test covers, e.g. "Applying a discount updates the cart total".'),
2600
3114
  steps: z2.array(z2.string().min(1)).min(1).describe(
@@ -2710,8 +3224,25 @@ function createBrain(model, generate = generateObject, budget, firstJudge) {
2710
3224
  }));
2711
3225
  const judgedStep = placeholdersAsLabels(step);
2712
3226
  const claim = placeholdersAsLabels(expectation);
2713
- const prompt = assertUserPrompt(judgedStep, claim, snapshot, asJudged);
3227
+ const dialog = isDialogSnapshot(snapshot);
3228
+ const prompt = assertUserPrompt(judgedStep, claim, snapshot, asJudged, dialog);
2714
3229
  const label = (judgment) => secretMismatch(judgedStep, snapshot, asJudged, usedEarlier ?? [], judgment);
3230
+ if (dialog) {
3231
+ const result2 = await countedGenerate(generate, budget, {
3232
+ model,
3233
+ schema: assertDialogJudgmentSchema,
3234
+ system: assertSystemPrompt(),
3235
+ prompt,
3236
+ temperature: 0
3237
+ });
3238
+ const parsed2 = assertDialogJudgmentSchema.safeParse(result2.object);
3239
+ if (!parsed2.success) {
3240
+ throw new MalformedModelOutputError(
3241
+ `Model returned an invalid assert judgment: ${parsed2.error.issues[0]?.message ?? "unknown"}`
3242
+ );
3243
+ }
3244
+ return label(behindTheDialog(parsed2.data));
3245
+ }
2715
3246
  if (firstJudge) {
2716
3247
  const decided = await firstJudgment(firstJudge, budget, { step: judgedStep, claim, snapshot, prompt }, label);
2717
3248
  if (decided) return decided;
@@ -2733,6 +3264,11 @@ function createBrain(model, generate = generateObject, budget, firstJudge) {
2733
3264
  }
2734
3265
  };
2735
3266
  }
3267
+ var BEHIND_THE_DIALOG = "the page behind the native dialog cannot be seen until the dialog is answered, so this step cannot be judged now";
3268
+ function behindTheDialog(judgment) {
3269
+ if (judgment.seen !== "page") return judgment;
3270
+ return { ...judgment, pass: false, reason: `${BEHIND_THE_DIALOG}. (The judge had said: ${judgment.reason})` };
3271
+ }
2736
3272
  function secretMismatch(judgedStep, snapshot, judgedRecord, usedEarlier, judgment) {
2737
3273
  if (!judgment.pass) return judgment;
2738
3274
  const onPage = labelledVariables(snapshot);
@@ -3099,6 +3635,27 @@ import path11 from "path";
3099
3635
  // src/report/html.ts
3100
3636
  import { mkdir as mkdir6, readFile as readFile5, writeFile as writeFile5 } from "fs/promises";
3101
3637
  import path9 from "path";
3638
+
3639
+ // src/report/recovered.ts
3640
+ function recoveredLines(result) {
3641
+ if (result.status !== "passed") return [];
3642
+ return result.steps.flatMap(
3643
+ (step) => step.recovered === void 0 ? [] : [
3644
+ `step passed after ${attempts(step.recovered.attempts)}: ${step.step}`,
3645
+ // Its first line: a browser error carries a call log under it,
3646
+ // which the HTML report keeps (design D2).
3647
+ `first: ${step.recovered.first.split(/\r?\n/).find((line) => line.trim() !== "") ?? ""}`
3648
+ ]
3649
+ );
3650
+ }
3651
+ function attempts(count2) {
3652
+ return `${count2} failed attempt${count2 === 1 ? "" : "s"}`;
3653
+ }
3654
+ function recoveredCount(results) {
3655
+ return results.reduce((sum, result) => sum + (result.status === "passed" ? result.steps.filter((step) => step.recovered).length : 0), 0);
3656
+ }
3657
+
3658
+ // src/report/html.ts
3102
3659
  var ESCAPES = {
3103
3660
  "&": "&amp;",
3104
3661
  "<": "&lt;",
@@ -3172,7 +3729,7 @@ function seconds(ms) {
3172
3729
  function renderSteps(steps) {
3173
3730
  if (steps.length === 0) return "";
3174
3731
  const items = steps.map(
3175
- (step) => `<li class="${step.status === "failed" ? "failed" : ""}">${escapeHtml(step.step)}${step.setup ? ' <span class="note">(setup)</span>' : ""}${step.decidedBy === "replayed" || step.decidedBy === "healed" ? ` <span class="note">(${step.decidedBy})</span>` : ""}</li>`
3732
+ (step) => `<li class="${step.status === "failed" ? "failed" : ""}">${escapeHtml(step.step)}${step.setup ? ' <span class="note">(setup)</span>' : ""}${step.decidedBy === "replayed" || step.decidedBy === "healed" ? ` <span class="note">(${step.decidedBy})</span>` : ""}${step.recovered ? ` <span class="note">(passed after ${attempts(step.recovered.attempts)}: ${escapeHtml(step.recovered.first)})</span>` : ""}</li>`
3176
3733
  ).join("\n ");
3177
3734
  return `<ol class="steps">
3178
3735
  ${items}
@@ -3343,6 +3900,9 @@ function renderJUnit(results, skipped, meta) {
3343
3900
  // Emitted as 0 too (design D2): unlike a token count nobody reported, 0 is
3344
3901
  // a true claim here, that the run printed no warning.
3345
3902
  ...replayProperties(results),
3903
+ // Always, as `warnings` (design show-a-step-that-recovered, D3): 0 is a
3904
+ // true claim.
3905
+ ` <property name="recovered_steps" value="${recoveredCount(results)}"/>`,
3346
3906
  ` <property name="warnings" value="${warnings.length}"/>`,
3347
3907
  " </properties>"
3348
3908
  ];
@@ -3357,7 +3917,14 @@ function renderJUnit(results, skipped, meta) {
3357
3917
  }
3358
3918
  const open = ` <testcase classname="${escapeXml(relative(result.file))}" name="${escapeXml(result.summary)}" time="${seconds2(result.durationMs)}"`;
3359
3919
  if (result.status === "passed") {
3360
- lines.push(`${open}/>`);
3920
+ const recovered = recoveredLines(result);
3921
+ if (recovered.length === 0) {
3922
+ lines.push(`${open}/>`);
3923
+ } else {
3924
+ lines.push(`${open}>`);
3925
+ lines.push(` <system-out>${escapeXml(recovered.join("\n"))}</system-out>`);
3926
+ lines.push(" </testcase>");
3927
+ }
3361
3928
  continue;
3362
3929
  }
3363
3930
  const reason = result.reason ?? "test failed";
@@ -3567,6 +4134,13 @@ X ${r.summary} (${r.file})`);
3567
4134
  if (r.reason) console.log(` reason: ${r.reason}`);
3568
4135
  if (r.screenshot) console.log(` screenshot: ${r.screenshot}`);
3569
4136
  }
4137
+ for (const r of passed) {
4138
+ const lines = recoveredLines(r);
4139
+ if (lines.length === 0) continue;
4140
+ console.log(`
4141
+ ~ ${r.summary} (${r.file})`);
4142
+ for (const line of lines) console.log(` ${line}`);
4143
+ }
3570
4144
  if (notRun.length > 0) {
3571
4145
  console.log(`
3572
4146
  ${notRun.length} test(s) not run (run stopped: ${notRun[0].reason}):`);
@@ -3577,7 +4151,7 @@ function deviceTag(test, config) {
3577
4151
  const device = test.device ?? config.browser.device;
3578
4152
  return device ? ` [${device}]` : "";
3579
4153
  }
3580
- async function runOne(browser, test, config, sessionDir, session, runMask, budget, write, onHiddenFrame, firstJudge, replayCwd) {
4154
+ async function runOne(browser, test, config, sessionDir, session, runMask, budget, write, onHiddenFrame, onHiddenDialog, firstJudge, replayCwd) {
3581
4155
  const brain = createBrain(createModel(config.llm).model, void 0, budget, firstJudge);
3582
4156
  let resolved;
3583
4157
  const mask = runMask;
@@ -3617,6 +4191,7 @@ async function runOne(browser, test, config, sessionDir, session, runMask, budge
3617
4191
  mask: (text) => mask.mask(text),
3618
4192
  onEvent: (event) => printEvent(event, write),
3619
4193
  onHiddenFrame,
4194
+ onHiddenDialog,
3620
4195
  ...saved ? { replay: { saved } } : {}
3621
4196
  });
3622
4197
  if (replayCwd !== void 0 && saved && result.replay) {
@@ -3680,7 +4255,7 @@ function reportNearMissedSecrets(variables, warnings) {
3680
4255
  );
3681
4256
  }
3682
4257
  }
3683
- async function finalize(results, skipped, options, sessionDir, secretsHeld, nearMissedSecrets, warnings, durationMs, impact, incomplete, spend, firstJudgeLog) {
4258
+ async function finalize(results, skipped, options, sessionDir, secretsHeld, nearMissedSecrets, warnings, durationMs, unclassified, incomplete, spend, firstJudgeLog) {
3684
4259
  if (results.length > 0) printSummary(results);
3685
4260
  reportNearMissedSecrets(nearMissedSecrets, warnings);
3686
4261
  if (spend) console.log(formatSpendLine(spend));
@@ -3725,22 +4300,32 @@ async function finalize(results, skipped, options, sessionDir, secretsHeld, near
3725
4300
  console.log(`HTML report: ${path11.relative(options.cwd, target)}`);
3726
4301
  }
3727
4302
  if (incomplete) return EXIT_FAILED;
3728
- if (reportUnclassified(options, impact)) return EXIT_FAILED;
4303
+ if (reportUnclassified(options, unclassified)) return EXIT_FAILED;
3729
4304
  if (options.minScore !== void 0) {
3730
4305
  return computeScore(results) >= options.minScore ? EXIT_OK : EXIT_FAILED;
3731
4306
  }
3732
4307
  return results.some((result) => result.status === "failed") ? EXIT_FAILED : EXIT_OK;
3733
4308
  }
3734
- function reportUnclassified(options, impact) {
3735
- const unclassified = options.failOnUnmapped ? impact?.unmappedFiles ?? [] : [];
3736
- if (unclassified.length === 0) return false;
4309
+ function reportUnclassified(options, unclassified) {
4310
+ if (!options.failOnUnmapped || !unclassified) return false;
4311
+ const unreadable = unclassified.unreadable !== void 0;
4312
+ if (unreadable) {
4313
+ console.error(`error: --fail-on-unmapped could not read the working tree: ${unclassified.unreadable}`);
4314
+ console.error("Run `git status` to see why, or run without --fail-on-unmapped.");
4315
+ }
4316
+ const { diff, uncommitted } = unclassified;
4317
+ if (diff.length + uncommitted.length === 0) return unreadable;
3737
4318
  console.error(
3738
- `error: ${unclassified.length} changed file(s) match no routes: or ignore: glob, so their blast radius is unknown:`
4319
+ `error: ${diff.length + uncommitted.length} changed file(s) match no routes: or ignore: glob, so their blast radius is unknown:`
3739
4320
  );
3740
- for (const file of unclassified) console.error(` ${file}`);
4321
+ for (const file of diff) console.error(` ${file}`);
4322
+ for (const file of uncommitted) console.error(` ${file} (uncommitted)`);
3741
4323
  console.error(
3742
4324
  "Map them in routes: if they can affect a page, or list them in ignore: if they cannot."
3743
4325
  );
4326
+ if (uncommitted.length > 0) {
4327
+ console.error("An uncommitted file that is not part of this change can be stashed or added to .gitignore.");
4328
+ }
3744
4329
  return true;
3745
4330
  }
3746
4331
  function declaredConfigRoutes(config) {
@@ -3815,6 +4400,8 @@ async function runCommand(options) {
3815
4400
  const warnings = [];
3816
4401
  const hiddenFrames = /* @__PURE__ */ new Set();
3817
4402
  const onHiddenFrame = (origin) => hiddenFrames.add(origin);
4403
+ const hiddenDialogs = /* @__PURE__ */ new Set();
4404
+ const onHiddenDialog = (origin) => hiddenDialogs.add(origin);
3818
4405
  const impacted = options.impacted ?? false;
3819
4406
  const base = options.base ?? "main";
3820
4407
  if (options.failOnUnmapped && !impacted) {
@@ -3824,6 +4411,7 @@ async function runCommand(options) {
3824
4411
  return EXIT_USAGE;
3825
4412
  }
3826
4413
  let impact;
4414
+ let unclassified;
3827
4415
  let changedCount = 0;
3828
4416
  if (impacted) {
3829
4417
  let changedFiles;
@@ -3838,7 +4426,13 @@ async function runCommand(options) {
3838
4426
  }
3839
4427
  impact = mapImpact(changedFiles, config.routes ?? {}, config.ignore ?? []);
3840
4428
  changedCount = changedFiles.length;
3841
- printUncommitted(await getUncommittedFiles(options.cwd), changedFiles, config, base, warnings);
4429
+ const uncommitted = await getUncommittedFiles(options.cwd);
4430
+ printUncommitted(uncommittedPaths(uncommitted), changedFiles, config, base, warnings);
4431
+ unclassified = {
4432
+ diff: impact.unmappedFiles,
4433
+ uncommitted: unclassifiedUncommitted(uncommittedPaths(uncommitted), changedFiles, config),
4434
+ ...Array.isArray(uncommitted) ? {} : { unreadable: uncommitted.unreadable }
4435
+ };
3842
4436
  }
3843
4437
  const testsDir = path11.join(options.cwd, TESTS_RELATIVE_DIR);
3844
4438
  let files;
@@ -3897,7 +4491,7 @@ ${results.length} test file(s) could not be parsed:`);
3897
4491
  for (const broken of results) console.error(` ${broken.file}: ${broken.reason ?? "invalid"}`);
3898
4492
  return EXIT_FAILED;
3899
4493
  }
3900
- return reportUnclassified(options, impact) ? EXIT_FAILED : EXIT_OK;
4494
+ return reportUnclassified(options, unclassified) ? EXIT_FAILED : EXIT_OK;
3901
4495
  }
3902
4496
  const sessionDir = path11.join(options.cwd, ".blastproof", "reports", sessionId());
3903
4497
  const startedAt = Date.now();
@@ -3905,7 +4499,7 @@ ${results.length} test file(s) could not be parsed:`);
3905
4499
  console.log(
3906
4500
  impact ? "No impacted tests to run." : "No tests matched the given filters."
3907
4501
  );
3908
- return finalize(results, selection.unroutedSkipped, options, sessionDir, false, [], warnings, Date.now() - startedAt, impact);
4502
+ return finalize(results, selection.unroutedSkipped, options, sessionDir, false, [], warnings, Date.now() - startedAt, unclassified);
3909
4503
  }
3910
4504
  let decide;
3911
4505
  try {
@@ -3961,7 +4555,8 @@ ${results.length} test file(s) could not be parsed:`);
3961
4555
  device: config.browser.device,
3962
4556
  mask: runMask,
3963
4557
  onEvent: printEvent,
3964
- onHiddenFrame
4558
+ onHiddenFrame,
4559
+ onHiddenDialog
3965
4560
  });
3966
4561
  } catch (error) {
3967
4562
  if (error instanceof RunStoppedError) {
@@ -3969,6 +4564,7 @@ ${results.length} test file(s) could not be parsed:`);
3969
4564
  } else if (error instanceof AuthError) {
3970
4565
  console.error(`error: ${error.message}`);
3971
4566
  for (const origin of hiddenFrames) emitWarning(hiddenFrameWarning(origin), warnings);
4567
+ for (const origin of hiddenDialogs) emitWarning(hiddenDialogWarning(origin), warnings);
3972
4568
  return EXIT_USAGE;
3973
4569
  } else {
3974
4570
  throw error;
@@ -4001,6 +4597,7 @@ ${results.length} test file(s) could not be parsed:`);
4001
4597
  budget,
4002
4598
  write,
4003
4599
  onHiddenFrame,
4600
+ onHiddenDialog,
4004
4601
  firstJudgeFor(path11.relative(options.cwd, test.path)),
4005
4602
  options.replay ?? config.replay ? options.cwd : void 0
4006
4603
  );
@@ -4028,6 +4625,7 @@ ${results.length} test file(s) could not be parsed:`);
4028
4625
  await browser.close();
4029
4626
  }
4030
4627
  for (const origin of hiddenFrames) emitWarning(hiddenFrameWarning(origin), warnings);
4628
+ for (const origin of hiddenDialogs) emitWarning(hiddenDialogWarning(origin), warnings);
4031
4629
  return finalize(
4032
4630
  results,
4033
4631
  selection.unroutedSkipped,
@@ -4037,7 +4635,7 @@ ${results.length} test file(s) could not be parsed:`);
4037
4635
  runMask.nearMissedVariables(),
4038
4636
  warnings,
4039
4637
  Date.now() - startedAt,
4040
- impact,
4638
+ unclassified,
4041
4639
  incomplete,
4042
4640
  // The command that constructed the budget is the one that reports it
4043
4641
  // (design report-what-it-spent, D2). `test` hands one budget to both of its
@@ -4086,7 +4684,7 @@ async function resolveTargets(options, config, suite) {
4086
4684
  const base = options.base ?? "main";
4087
4685
  const changedFiles = await getChangedFiles(base, options.cwd);
4088
4686
  const impact = mapImpact(changedFiles, config.routes ?? {}, config.ignore ?? []);
4089
- printUncommitted(await getUncommittedFiles(options.cwd), changedFiles, config, base);
4687
+ printUncommitted(uncommittedPaths(await getUncommittedFiles(options.cwd)), changedFiles, config, base);
4090
4688
  const filesForRoute = (route) => changedFiles.filter(
4091
4689
  (file) => mapImpact([file], config.routes ?? {}, config.ignore ?? []).affectedRoutes.includes(route)
4092
4690
  );
@@ -4380,7 +4978,7 @@ function parsePositiveNumber(flag) {
4380
4978
  };
4381
4979
  }
4382
4980
  var program = new Command();
4383
- program.name("blastproof").description("Open-source AI testing agent: plain-English YAML tests executed agentically on a real browser.").version("0.35.0");
4981
+ program.name("blastproof").description("Open-source AI testing agent: plain-English YAML tests executed agentically on a real browser.").version("0.37.0");
4384
4982
  program.command("init").description("Scaffold .blastproof/ (config, tests, sample tests) in the current directory").action(async () => {
4385
4983
  try {
4386
4984
  const result = await initProject(process.cwd());