@flowspec-qa/runner-core 0.5.2 → 0.5.5

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.
@@ -165,6 +165,53 @@ export declare const discoveryEngine: {
165
165
  stderr: string;
166
166
  };
167
167
  /** Smart navigation back to parent screen */
168
+ /**
169
+ * After a tester prompt, confirm the app still shows the form. If the session
170
+ * expired (login screen) or the app moved, go back: log in with the observed
171
+ * login fields and tap the element that opened the form. Never types into a
172
+ * screen that is not the form.
173
+ */
174
+ _returnToForm(ctx: {
175
+ appId: string;
176
+ maestroEnv: NodeJS.ProcessEnv;
177
+ deviceId?: string;
178
+ isIos: boolean;
179
+ formUI: UIElement[];
180
+ parentUI: UIElement[];
181
+ launchUI: UIElement[];
182
+ loginForm: {
183
+ usernameId: string;
184
+ passwordId: string;
185
+ submitId: string;
186
+ } | null;
187
+ username: string;
188
+ password: string;
189
+ openFormElementId: string;
190
+ screenName: string;
191
+ }): Promise<boolean>;
192
+ /**
193
+ * Make sure `elementId` (observed on `parentName`) is on screen before the
194
+ * BFS taps it. Tries: look now → back to parent → relaunch + login with the
195
+ * observed login fields. Saves the hierarchy when it fails, for diagnosis.
196
+ */
197
+ _ensureElementOnScreen(ctx: {
198
+ appId: string;
199
+ maestroEnv: NodeJS.ProcessEnv;
200
+ deviceId?: string;
201
+ isIos: boolean;
202
+ elementId: string;
203
+ parentName: string;
204
+ parentUI: UIElement[];
205
+ launchUI: UIElement[];
206
+ loginForm: {
207
+ usernameId: string;
208
+ passwordId: string;
209
+ submitId: string;
210
+ } | null;
211
+ username: string;
212
+ password: string;
213
+ outputDir: string;
214
+ }): Promise<boolean>;
168
215
  _smartBack(appId: string, maestroEnv: NodeJS.ProcessEnv, deviceId: string | undefined, parentUI: UIElement[], launchUI: UIElement[], loginForm: any, parentName: string): Promise<boolean>;
169
216
  /**
170
217
  * Extracts ALL visible text strings from a Maestro hierarchy JSON.
@@ -1 +1 @@
1
- {"version":3,"file":"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,MAAM,CAAC;QACnB,gBAAgB,EAAE,MAAM,CAAC;QACzB,cAAc,EAAE,MAAM,CAAC;QACvB,cAAc,EAAE,OAAO,CAAC;KACzB,CAAC;4BA4D4B,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC;sBAksCjD,GAAG,YAAY,MAAM,YAAY,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;yBAkCvD,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC;IAsGtE;;;OAGG;sCAC+B,cAAc,EAAE,UAAU,cAAc,GAAG,MAAM;IAiBnF,6CAA6C;yBACxB,MAAM,OAAO,MAAM,YAAY,GAAG,EAAE,GAAG,MAAM;IA8BlE;;;;OAIG;+BACwB,iBAAiB,GAAG,iBAAiB,EAAE;IAuElE;;;OAGG;2BACoB,MAAM,SAAS;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,oBAAkB,MAAM,EAAE;IA6BtG;;;;OAIG;oCAEa,MAAM,YACV,iBAAiB,SACpB;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,SACtC,MAAM,cACD,MAAM,CAAC,UAAU,oBAE5B,OAAO,CAAC,OAAO,CAAC;IAkCnB;;;;;;;;;OASG;4BAEQ,iBAAiB,WACjB,gBAAgB,YACf,iBAAiB,WAClB,cAAc,GACtB,OAAO,CAAC,cAAc,EAAE,CAAC;IAmR5B;;;;OAIG;oCAC6B,iBAAiB,SAAS,MAAM,GAAG,MAAM;kCA2F3C,GAAG,GAAG,GAAG,EAAE;CAoF1C,CAAC"}
package/dist/discovery.js CHANGED
@@ -4,9 +4,11 @@ import os from 'os';
4
4
  import path from 'path';
5
5
  import chalk from 'chalk';
6
6
  import { FlowSpecQAApi } from './api-client.js';
7
+ import { reportsDir } from './workspace.js';
7
8
  import { exploreWeb } from './web-explorer.js';
8
9
  import { normalizeResultType, } from './evidence-types.js';
9
10
  import { addRecord, buildRecord, corpusSummary, createCorpus, detectForm, detectLoginForm, detectScreenChange, finalizeCorpus, findBaselineForFingerprint, inferScreenName, isSameScreen, legacyElementsToUIElements, looksLikeButton, rankNavigableButtons, shouldCapture, } from './evidence-corpus.js';
11
+ import { elementPresent, formResultName, guardInterruption, hasImeNodes, locateScreen, loginSteps, stripImeNodes, writePartialSnapshot } from './mobile-discovery-guards.js';
10
12
  const sleep = (ms) => new Promise(r => setTimeout(r, ms));
11
13
  // ─── ADB path resolution (mirrors devices.ts) ───────────────────────────────
12
14
  const ADB_COMMON_PATHS = [
@@ -301,7 +303,12 @@ export const discoveryEngine = {
301
303
  }
302
304
  }
303
305
  const jsonStr = end !== -1 ? rawOutput.slice(start, end + 1) : rawOutput.slice(start);
304
- return JSON.parse(jsonStr);
306
+ // The on-screen keyboard is not part of the app: its keys ("ES(US)", ".com")
307
+ // must never be recorded as elements or validation texts.
308
+ const parsed = JSON.parse(jsonStr);
309
+ const appIdForIme = this._mobileAppId || '';
310
+ this._keyboardVisible = hasImeNodes(parsed, appIdForIme);
311
+ return stripImeNodes(parsed, appIdForIme);
305
312
  },
306
313
  /** Execute a Maestro YAML flow (written to a temp file) */
307
314
  _runMaestroFlow(appId, steps, env) {
@@ -355,6 +362,101 @@ export const discoveryEngine = {
355
362
  }
356
363
  },
357
364
  /** Smart navigation back to parent screen */
365
+ /**
366
+ * After a tester prompt, confirm the app still shows the form. If the session
367
+ * expired (login screen) or the app moved, go back: log in with the observed
368
+ * login fields and tap the element that opened the form. Never types into a
369
+ * screen that is not the form.
370
+ */
371
+ async _returnToForm(ctx) {
372
+ const where = async () => {
373
+ const hier = await this._captureHierarchy(ctx.maestroEnv, ctx.deviceId).catch(() => null);
374
+ const ui = hier ? legacyElementsToUIElements(this.extractMaestroSelectors(hier), '__pending__') : [];
375
+ return locateScreen({
376
+ form: ui.length > 0 && isSameScreen(ui, ctx.formUI, 0.6),
377
+ login: !!ctx.loginForm && ui.length > 0 && isSameScreen(ui, ctx.launchUI, 0.7),
378
+ parent: ui.length > 0 && isSameScreen(ui, ctx.parentUI, 0.7),
379
+ });
380
+ };
381
+ const sel = (id) => buildMaestroSelector(id, ctx.isIos);
382
+ let location = await where();
383
+ if (location === 'on_form')
384
+ return true;
385
+ console.log(chalk.yellow(` ↩️ La app ya no muestra "${ctx.screenName}" (${location === 'on_login' ? 'sesión cerrada' : 'otra pantalla'}). Volviendo al formulario...`));
386
+ if (location === 'elsewhere') {
387
+ // Bring the app to the front without clearing its state, then look again.
388
+ this._runMaestroFlow(ctx.appId, [`- launchApp`, `- waitForAnimationToEnd:\n timeout: 3000`], ctx.maestroEnv);
389
+ location = await where();
390
+ if (location === 'on_form')
391
+ return true;
392
+ }
393
+ if (location === 'on_login') {
394
+ if (!ctx.loginForm || !ctx.username || !ctx.password) {
395
+ console.log(chalk.yellow(` ⚠️ Sesión cerrada y sin credenciales para volver a entrar. Flujo "${ctx.screenName}" no explorado.`));
396
+ return false;
397
+ }
398
+ this._runMaestroFlow(ctx.appId, loginSteps(ctx.loginForm, ctx.username, ctx.password, sel), ctx.maestroEnv);
399
+ await sleep(2000);
400
+ location = await where();
401
+ }
402
+ if (location === 'on_parent') {
403
+ this._runMaestroFlow(ctx.appId, [`- tapOn:\n ${sel(ctx.openFormElementId)}`, `- waitForAnimationToEnd:\n timeout: 3000`], ctx.maestroEnv);
404
+ await sleep(1500);
405
+ location = await where();
406
+ }
407
+ if (location === 'on_form') {
408
+ console.log(chalk.green(` ✅ De vuelta en "${ctx.screenName}".`));
409
+ return true;
410
+ }
411
+ console.log(chalk.yellow(` ⚠️ No se pudo volver a "${ctx.screenName}". Flujo no explorado; los datos no se escribieron en otra pantalla.`));
412
+ return false;
413
+ },
414
+ /**
415
+ * Make sure `elementId` (observed on `parentName`) is on screen before the
416
+ * BFS taps it. Tries: look now → back to parent → relaunch + login with the
417
+ * observed login fields. Saves the hierarchy when it fails, for diagnosis.
418
+ */
419
+ async _ensureElementOnScreen(ctx) {
420
+ let lastHier = null;
421
+ const present = async () => {
422
+ lastHier = await this._captureHierarchy(ctx.maestroEnv, ctx.deviceId).catch(() => null);
423
+ const ids = lastHier ? this.extractMaestroSelectors(lastHier).map((e) => e.id) : [];
424
+ return { ok: elementPresent(ids, ctx.elementId), ids };
425
+ };
426
+ let check = await present();
427
+ if (check.ok)
428
+ return true;
429
+ console.log(chalk.yellow(` ↩️ "${ctx.elementId}" no está en pantalla: la app no está en "${ctx.parentName}". Volviendo...`));
430
+ await this._smartBack(ctx.appId, ctx.maestroEnv, ctx.deviceId, ctx.parentUI, ctx.launchUI, ctx.loginForm, ctx.parentName);
431
+ check = await present();
432
+ if (check.ok)
433
+ return true;
434
+ // Relaunch without clearing state; log in again if the session closed.
435
+ this._runMaestroFlow(ctx.appId, [`- launchApp`, `- waitForAnimationToEnd:\n timeout: 3000`], ctx.maestroEnv);
436
+ check = await present();
437
+ if (!check.ok && ctx.loginForm && ctx.username && ctx.password) {
438
+ const ui = legacyElementsToUIElements(check.ids.map((id) => ({ id, type: '', text: '' })), '__pending__');
439
+ if (isSameScreen(ui, ctx.launchUI, 0.7)) {
440
+ const sel = (id) => buildMaestroSelector(id, ctx.isIos);
441
+ this._runMaestroFlow(ctx.appId, loginSteps(ctx.loginForm, ctx.username, ctx.password, sel), ctx.maestroEnv);
442
+ await sleep(2000);
443
+ check = await present();
444
+ }
445
+ }
446
+ if (check.ok) {
447
+ console.log(chalk.green(` ✅ De vuelta en "${ctx.parentName}".`));
448
+ return true;
449
+ }
450
+ try {
451
+ const dir = path.join(ctx.outputDir, 'debug');
452
+ fs.mkdirSync(dir, { recursive: true });
453
+ const file = path.join(dir, `missing_${ctx.elementId.replace(/[^\w.-]+/g, '_')}_${Date.now()}.json`);
454
+ fs.writeFileSync(file, JSON.stringify({ expected: ctx.elementId, parent: ctx.parentName, seen_ids: check.ids, hierarchy: lastHier }));
455
+ console.log(chalk.gray(` 🧾 Jerarquía guardada para diagnóstico: ${file}`));
456
+ }
457
+ catch { /* best effort */ }
458
+ return false;
459
+ },
358
460
  async _smartBack(appId, maestroEnv, deviceId, parentUI, launchUI, loginForm, parentName) {
359
461
  let returnedToParent = false;
360
462
  const BACK_BUTTON_RE = /^(cerrar|volver|atr[aá]s|cancelar|close|back|cancel|btn_back|btn_close|btn_cancel)$/i;
@@ -444,6 +546,7 @@ export const discoveryEngine = {
444
546
  }
445
547
  // ── Interactive exploration loop (mobile only) ────────────────────────
446
548
  if (options.onInteractiveLoop && result.evidence) {
549
+ const releaseLoopGuard = guardInterruption(options.outputDir || path.join(process.cwd(), 'specs'), () => ({ partial: true, ...result, framework: options.framework, url: options.url }));
447
550
  let continueLoop = true;
448
551
  while (continueLoop) {
449
552
  continueLoop = await options.onInteractiveLoop(result.evidence);
@@ -457,6 +560,7 @@ export const discoveryEngine = {
457
560
  if (result.evidence) {
458
561
  result.planContent = this.buildPlanFromEvidence(result.evidence, options.url);
459
562
  }
563
+ releaseLoopGuard();
460
564
  }
461
565
  // Persist plan locally
462
566
  const outputDir = options.outputDir || path.join(process.cwd(), 'specs');
@@ -472,11 +576,16 @@ export const discoveryEngine = {
472
576
  catch (dataErr) {
473
577
  console.log(chalk.yellow(`⚠️ discovery_data.json no guardado: ${dataErr.message}`));
474
578
  }
579
+ // A completed run supersedes the evidence saved by an earlier interruption.
580
+ try {
581
+ fs.rmSync(path.join(outputDir, 'discovery_partial.json'), { force: true });
582
+ }
583
+ catch { /* ignore */ }
475
584
  // Generate HTML evidence report
476
585
  try {
477
586
  const { generateDiscoveryReport } = await import('./discovery-report.js');
478
587
  const reportPath = generateDiscoveryReport(result, {
479
- outputDir,
588
+ outputDir: reportsDir(outputDir),
480
589
  framework: options.framework,
481
590
  url: options.url,
482
591
  });
@@ -637,6 +746,18 @@ export const discoveryEngine = {
637
746
  const navigationSteps = [];
638
747
  // ── Evidence Corpus (evidence-first Discovery) ─────────────────────────
639
748
  const corpus = createCorpus(appId);
749
+ this._mobileAppId = appId;
750
+ // Ctrl-C (or a prompt the tester closes) must not lose what was captured.
751
+ const partialDir = options.outputDir || path.join(process.cwd(), 'specs');
752
+ const partialSnapshot = () => ({
753
+ partial: true,
754
+ framework: 'maestro',
755
+ url: appId,
756
+ corpus: finalizeCorpus(corpus),
757
+ screens: allScreens,
758
+ navigationSteps,
759
+ });
760
+ const releaseInterruptGuard = guardInterruption(partialDir, partialSnapshot);
640
761
  this._progress(options, 'start', `Iniciando Discovery mobile: ${appId}`);
641
762
  console.log(chalk.gray(`📱 Discovery multi-pantalla${options.deviceId ? ` — dispositivo ${options.deviceId}` : ''}...`));
642
763
  // ── Phase 11 — Baseline fetch for incremental / recapture modes ────────
@@ -814,6 +935,7 @@ export const discoveryEngine = {
814
935
  // skip the login form detection entirely (any EditText we see now is
815
936
  // a regular form, e.g. transfer amount, not credentials).
816
937
  const loginForm = detectLoginForm(launchUI);
938
+ this._mobileLoginForm = loginForm || null;
817
939
  // Tracking state for BFS exploration
818
940
  let lastScreenName = initialScreenName;
819
941
  let lastUI = launchUI;
@@ -1157,6 +1279,18 @@ export const discoveryEngine = {
1157
1279
  this._progress(options, 'screen', `Explorando "${btnLabel}"`);
1158
1280
  console.log(chalk.gray(`\n 👆 Tap en "${btnLabel}" (${btn.elementId})...`));
1159
1281
  const bfsSelector = buildMaestroSelector(btn.elementId, isIos);
1282
+ // The previous "back" may have left us on another screen even if it
1283
+ // looked like the parent: confirm this button is really here.
1284
+ const onParent = await this._ensureElementOnScreen({
1285
+ appId, maestroEnv, deviceId: options.deviceId, isIos,
1286
+ elementId: btn.elementId, parentName, parentUI, launchUI,
1287
+ loginForm: loginForm || null, username, password,
1288
+ outputDir: options.outputDir || path.join(process.cwd(), 'specs'),
1289
+ });
1290
+ if (!onParent) {
1291
+ console.log(chalk.yellow(` ⚠️ "${btnLabel}" no está en pantalla y no se pudo volver a "${parentName}". BFS detenido.`));
1292
+ break;
1293
+ }
1160
1294
  const tapResult = this._runMaestroFlow(appId, [
1161
1295
  `- tapOn:\n ${bfsSelector}`,
1162
1296
  `- waitForAnimationToEnd:\n timeout: 3000`,
@@ -1425,7 +1559,13 @@ export const discoveryEngine = {
1425
1559
  this._progress(options, 'error_state', `Submit vacío en "${screenName}"`);
1426
1560
  console.log(chalk.gray(` 📸 Probando validación en "${screenName}" (submit vacío)...`));
1427
1561
  const emptySelector = buildMaestroSelector(screenForm.submitButtonId, isIos);
1562
+ // An open keyboard can cover the submit button (the tap then lands
1563
+ // on a key and no validation appears). Close it only when the last
1564
+ // capture actually showed it.
1565
+ await this._captureHierarchy(maestroEnv, options.deviceId).catch(() => null);
1566
+ const closeKeyboard = this._keyboardVisible ? [`- hideKeyboard`] : [];
1428
1567
  const emptyFormOk = this._runMaestroFlow(appId, [
1568
+ ...closeKeyboard,
1429
1569
  `- tapOn:\n ${emptySelector}`,
1430
1570
  `- waitForAnimationToEnd:\n timeout: 1500`,
1431
1571
  ], maestroEnv).ok;
@@ -1489,7 +1629,25 @@ export const discoveryEngine = {
1489
1629
  }
1490
1630
  else {
1491
1631
  console.log(chalk.cyan(` 📋 Form detectado en "${screenName}": ${screenForm.fields.length} campos`));
1492
- const fieldData = await options.onFormDetected(screenForm);
1632
+ let fieldData = null;
1633
+ try {
1634
+ fieldData = await options.onFormDetected(screenForm);
1635
+ }
1636
+ catch (promptErr) {
1637
+ console.log(chalk.yellow(` ⚠️ La pregunta del formulario se cerró (${promptErr?.message ?? promptErr}). Flujo "${screenName}" no explorado.`));
1638
+ }
1639
+ // The tester may take minutes to answer and banking apps close the
1640
+ // session meanwhile: make sure we are on the form before typing.
1641
+ if (fieldData) {
1642
+ const backOnForm = await this._returnToForm({
1643
+ appId, maestroEnv, deviceId: options.deviceId, isIos,
1644
+ formUI: tapUI, parentUI, launchUI,
1645
+ loginForm: loginForm || null, username, password,
1646
+ openFormElementId: btn.elementId, screenName,
1647
+ });
1648
+ if (!backOnForm)
1649
+ fieldData = null;
1650
+ }
1493
1651
  if (fieldData) {
1494
1652
  const fillSteps = [];
1495
1653
  for (const [fid, val] of Object.entries(fieldData)) {
@@ -1512,7 +1670,7 @@ export const discoveryEngine = {
1512
1670
  let resultType;
1513
1671
  let resultDescription;
1514
1672
  if (isSuccess) {
1515
- destName = inferScreenName(formTxts, [...tapTxts, ...parentTexts], `Resultado exitoso de ${screenName}`);
1673
+ destName = formResultName(screenName, isSameScreen(formUI, tapUI, 0.6), inferScreenName(formTxts, [...tapTxts, ...parentTexts], `Resultado exitoso de ${screenName}`));
1516
1674
  resultType = 'new_screen';
1517
1675
  resultDescription = `Formulario exitoso — texto detectado: "${successText}" (${formEls.length} elementos)`;
1518
1676
  console.log(chalk.green(` ✅ Form exitoso: "${destName}"`));
@@ -1574,6 +1732,7 @@ export const discoveryEngine = {
1574
1732
  }
1575
1733
  }
1576
1734
  // ── Finalize evidence corpus ───────────────────────────────────────
1735
+ releaseInterruptGuard();
1577
1736
  const finalCorpus = finalizeCorpus(corpus);
1578
1737
  console.log(chalk.dim(` 📦 ${corpusSummary(finalCorpus)}`));
1579
1738
  // Phase 11 — incremental summary
@@ -1619,9 +1778,15 @@ export const discoveryEngine = {
1619
1778
  };
1620
1779
  }
1621
1780
  catch (error) {
1781
+ releaseInterruptGuard();
1622
1782
  const msg = error.message || String(error);
1623
1783
  const isMaestroHierarchy = msg.includes('maestro') && msg.includes('hierarchy');
1624
1784
  console.log(chalk.red(`\n ❌ Error en Discovery: ${msg}`));
1785
+ try {
1786
+ const file = writePartialSnapshot(partialDir, partialSnapshot());
1787
+ console.log(chalk.yellow(` 💾 Evidencia capturada hasta el error guardada en ${file}`));
1788
+ }
1789
+ catch { /* best effort */ }
1625
1790
  if (isMaestroHierarchy) {
1626
1791
  console.log(chalk.yellow('\n 💡 Posibles causas:'));
1627
1792
  console.log(chalk.dim(' • La pantalla del dispositivo estaba apagada o bloqueada'));
@@ -1840,12 +2005,10 @@ ${elements.slice(0, 20).map((e) => {
1840
2005
  }
1841
2006
  }
1842
2007
  }
1843
- // Login/submit elements that the generic flow always handles
1844
- // (kept for legacy compat; modern flow uses detectLoginForm dynamically)
1845
- const ALWAYS_HANDLED = new Set([
1846
- 'btn_login', 'btn_confirm', 'et_username', 'et_password',
1847
- 'btn_submit', 'btn_register', 'btn_back',
1848
- ]);
2008
+ // The login fields observed in this session are handled by the login step;
2009
+ // never assume an app's ids by naming convention.
2010
+ const lf = this._mobileLoginForm;
2011
+ const ALWAYS_HANDLED = new Set(lf ? [lf.usernameId, lf.passwordId, lf.submitId] : []);
1849
2012
  const unexplored = [];
1850
2013
  const seenIds = new Set();
1851
2014
  for (const screen of evidence.screens) {
@@ -1900,18 +2063,14 @@ ${elements.slice(0, 20).map((e) => {
1900
2063
  ];
1901
2064
  }
1902
2065
  if (action === 'Login con credenciales válidas') {
2066
+ // Only the login fields observed in this session — never assumed ids.
2067
+ const lf = this._mobileLoginForm;
2068
+ if (!lf) {
2069
+ console.log(chalk.yellow(' ⚠️ No hay formulario de login observado en esta sesión; no se puede volver a iniciar sesión.'));
2070
+ return [];
2071
+ }
1903
2072
  return [
1904
- `- tapOn:\n id: "et_username"`,
1905
- `- eraseText: 50`,
1906
- `- inputText: "${creds.username}"`,
1907
- `- waitForAnimationToEnd`,
1908
- `- hideKeyboard`,
1909
- `- tapOn:\n id: "et_password"`,
1910
- `- eraseText: 50`,
1911
- `- inputText: "${creds.password}"`,
1912
- `- waitForAnimationToEnd`,
1913
- `- hideKeyboard`,
1914
- `- tapOn:\n id: "btn_login"`,
2073
+ ...loginSteps(lf, creds.username, creds.password, (id) => buildMaestroSelector(id, isIos)),
1915
2074
  `- waitForAnimationToEnd`,
1916
2075
  ];
1917
2076
  }
@@ -2103,7 +2262,23 @@ ${elements.slice(0, 20).map((e) => {
2103
2262
  const detectedForm = detectForm(newUIElements, screenName);
2104
2263
  if (detectedForm && options.onFormDetected) {
2105
2264
  console.log(chalk.cyan(`\n 📋 Formulario en "${screenName}": ${detectedForm.fields.length} campos`));
2106
- const fieldData = await options.onFormDetected(detectedForm);
2265
+ let fieldData = null;
2266
+ try {
2267
+ fieldData = await options.onFormDetected(detectedForm);
2268
+ }
2269
+ catch (promptErr) {
2270
+ console.log(chalk.yellow(` ⚠️ La pregunta del formulario se cerró (${promptErr?.message ?? promptErr}). Flujo "${screenName}" no explorado.`));
2271
+ }
2272
+ if (fieldData) {
2273
+ // Never type into another screen: the app may have closed the session
2274
+ // while the tester was answering.
2275
+ const nowHier = await this._captureHierarchy(maestroEnv, options.deviceId).catch(() => null);
2276
+ const nowUI = nowHier ? legacyElementsToUIElements(this.extractMaestroSelectors(nowHier), '__pending__') : [];
2277
+ if (!(nowUI.length > 0 && isSameScreen(nowUI, newUIElements, 0.6))) {
2278
+ console.log(chalk.yellow(` ⚠️ La app ya no muestra "${screenName}" (¿sesión cerrada?). Flujo no explorado; repite la exploración de este elemento.`));
2279
+ fieldData = null;
2280
+ }
2281
+ }
2107
2282
  if (fieldData) {
2108
2283
  const fillSteps = [];
2109
2284
  for (const [fieldId, value] of Object.entries(fieldData)) {
@@ -2160,8 +2335,10 @@ ${elements.slice(0, 20).map((e) => {
2160
2335
  }
2161
2336
  }
2162
2337
  // 5. Try to trigger error state on new screen (tap first submit-like button without filling fields)
2163
- const submitBtn = newElements.find(e => ['btn_confirm', 'btn_submit', 'btn_pay', 'btn_send', 'btn_continue', 'btn_accept'].includes(e.id) ||
2164
- (e.type === 'Button' && e.id !== element.elementId));
2338
+ // The submit observed by form detection on this screen; no assumed ids.
2339
+ const observedSubmitId = detectForm(legacyElementsToUIElements(newElements, "__pending__"), screenName)?.submitButtonId;
2340
+ const submitBtn = newElements.find(e => observedSubmitId && e.id === observedSubmitId) ||
2341
+ newElements.find(e => e.type === 'Button' && e.id !== element.elementId);
2165
2342
  if (submitBtn) {
2166
2343
  console.log(chalk.gray(` 📸 Intentando error state (${submitBtn.id})...`));
2167
2344
  const errorOk = this._runMaestroFlow(appId, [