@capagents/forgeqe 2.9.5 → 2.9.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.
Files changed (97) hide show
  1. package/HOW_TO_USE.md +130 -1
  2. package/README.md +3 -0
  3. package/dist/docs-site/docs/architecture/index.html +1 -1
  4. package/dist/docs-site/docs/containers/index.html +2 -2
  5. package/dist/docs-site/docs/cost-architecture/index.html +1 -1
  6. package/dist/docs-site/docs/custom-agents-first-run/index.html +216 -0
  7. package/dist/docs-site/docs/desktop/index.html +1 -1
  8. package/dist/docs-site/docs/desktop-ci/index.html +1 -1
  9. package/dist/docs-site/docs/evidence/index.html +992 -0
  10. package/dist/docs-site/docs/feature-test-prompts/index.html +1 -1
  11. package/dist/docs-site/docs/graphify/index.html +380 -0
  12. package/dist/docs-site/docs/guardrails/index.html +2 -2
  13. package/dist/docs-site/docs/index.html +141 -6
  14. package/dist/docs-site/docs/mobile/index.html +1 -1
  15. package/dist/docs-site/docs/model-routing/index.html +1 -1
  16. package/dist/docs-site/docs/product-graph/index.html +356 -0
  17. package/dist/docs-site/docs/product-knowledge/index.html +3 -3
  18. package/dist/docs-site/docs/product-views/index.html +431 -0
  19. package/dist/docs-site/docs/search.js +1 -1
  20. package/dist/docs-site/docs/web-app/index.html +2 -2
  21. package/dist/forgeqe.js +1866 -1664
  22. package/dist/web/assets/{Agent-BU8FKiQt.js → Agent-I5mRol1P.js} +1 -1
  23. package/dist/web/assets/{ApiTests-Bsv3NhD5.js → ApiTests--JGFKbOa.js} +1 -1
  24. package/dist/web/assets/{Browse-D-ho9bS_.js → Browse-CIcl1j4N.js} +2 -2
  25. package/dist/web/assets/Chat-Baph1nlV.js +3 -0
  26. package/dist/web/assets/{CommandPalette-CrLuxoE5.js → CommandPalette-Dd0seTKQ.js} +1 -1
  27. package/dist/web/assets/{Compare-DfHMTNGi.js → Compare-B7barE31.js} +1 -1
  28. package/dist/web/assets/{Cost-BYb3T8-c.js → Cost-CGXZTXSz.js} +1 -1
  29. package/dist/web/assets/{Data-EF_k6c_T.js → Data-DGKi3KHS.js} +1 -1
  30. package/dist/web/assets/{Desktop-DY5Q1Sd3.js → Desktop-wfNhaxat.js} +1 -1
  31. package/dist/web/assets/{DesktopReview-DFKpYor2.js → DesktopReview-Cxn3mgKO.js} +1 -1
  32. package/dist/web/assets/{Evidence-Db9H4-Nu.js → Evidence-BZ-WKU9t.js} +1 -1
  33. package/dist/web/assets/{Explore-B0EkFCFe.js → Explore-pa8l7kiC.js} +1 -1
  34. package/dist/web/assets/{Features-8jsv2A1d.js → Features-JDMSSUpb.js} +1 -1
  35. package/dist/web/assets/{Flags-DtzmOA5o.js → Flags-DcWTBteQ.js} +1 -1
  36. package/dist/web/assets/{Flaky-BCzOx7Mq.js → Flaky-DnHWlzlk.js} +1 -1
  37. package/dist/web/assets/{ForceGraph-i1zlas5l.js → ForceGraph-BLYMwmyj.js} +1 -1
  38. package/dist/web/assets/{Impact-Da9L1tDd.js → Impact-Dn5PPQ5Z.js} +1 -1
  39. package/dist/web/assets/{Jobs-CHw00lcx.js → Jobs-CNhlUenm.js} +1 -1
  40. package/dist/web/assets/{KindPage-DiOmtzVZ.js → KindPage-BPwFdxHe.js} +1 -1
  41. package/dist/web/assets/{Migration-Cu4JgOj1.js → Migration-DsGwJd40.js} +1 -1
  42. package/dist/web/assets/{Product-DmvUI7pH.js → Product-DsolJU4Y.js} +1 -1
  43. package/dist/web/assets/{Production-CLoOV4jl.js → Production-Cnh3wWiK.js} +1 -1
  44. package/dist/web/assets/{Quality-ylTg9e0c.js → Quality-W_rQ6nRf.js} +1 -1
  45. package/dist/web/assets/{Readiness-BMD5Uj8D.js → Readiness-IWAIRZwC.js} +1 -1
  46. package/dist/web/assets/Record-DOImb7O7.js +2 -0
  47. package/dist/web/assets/{Regression-D_Hy9bMt.js → Regression-DQuiIAFx.js} +1 -1
  48. package/dist/web/assets/{Reports-DXphAHAy.js → Reports-C16UVZtQ.js} +1 -1
  49. package/dist/web/assets/{Response-PDQ8zEZU.js → Response-Vh2lEWnS.js} +1 -1
  50. package/dist/web/assets/{RunDiff-C3MIKipo.js → RunDiff-CVnhT7JE.js} +1 -1
  51. package/dist/web/assets/{Runs-DSQZwCpE.js → Runs-CI8NJB1v.js} +1 -1
  52. package/dist/web/assets/{Steps-CY6WROAr.js → Steps-Bwe4WAjy.js} +1 -1
  53. package/dist/web/assets/{TestCases-BjgWdtPi.js → TestCases-D5oOzYL4.js} +1 -1
  54. package/dist/web/assets/{TestData-CDziNp2d.js → TestData-27tyi6OD.js} +1 -1
  55. package/dist/web/assets/{TestDebt-D59zFYSu.js → TestDebt-D9k3uAiS.js} +1 -1
  56. package/dist/web/assets/{Tosca-umw1O224.js → Tosca-CMmixiPy.js} +1 -1
  57. package/dist/web/assets/{WhatsNew-DqNMAytd.js → WhatsNew-CuCua9dD.js} +1 -1
  58. package/dist/web/assets/{dataParts-DGVc48Ed.js → dataParts-D06wI4i1.js} +1 -1
  59. package/dist/web/assets/{families-DlfXDoO8.js → families-B0QIuAe3.js} +1 -1
  60. package/dist/web/assets/filters-mFECJpMB.js +1 -0
  61. package/dist/web/assets/{fold-BKAl2p_2.js → fold-CeQ84ypG.js} +1 -1
  62. package/dist/web/assets/frame-BcGZt823.js +4 -0
  63. package/dist/web/assets/{index-BLUj4Sgh.js → index-CotEpFLY.js} +19 -17
  64. package/dist/web/assets/index-VgSzQGK8.css +2 -0
  65. package/dist/web/assets/{logos-J0WPxDqj.js → logos-DN9jLn4q.js} +1 -1
  66. package/dist/web/assets/{palette-DViz4KwG.js → palette-BdMPhc9j.js} +1 -1
  67. package/dist/web/assets/{parts-W2J4TR3o.js → parts-z_AE9U-M.js} +1 -1
  68. package/dist/web/assets/{productParts-_8gKGn4o.js → productParts-C4vc_bLJ.js} +1 -1
  69. package/dist/web/assets/{qualityParts-DnbSeK-G.js → qualityParts-Cfirt7dZ.js} +1 -1
  70. package/dist/web/assets/{recordTest-etYNiLQy.js → recordTest-GvGQjhR4.js} +1 -1
  71. package/dist/web/assets/{rows-CbXelp5_.js → rows-CiR4hGkv.js} +1 -1
  72. package/dist/web/assets/{segmented-B7n6eLrO.js → segmented-DANusepM.js} +1 -1
  73. package/dist/web/assets/thread-CyTIuLgk.js +5 -0
  74. package/dist/web/assets/{usePageChat-DMOtRwzT.js → usePageChat-DOTAHsIS.js} +1 -1
  75. package/dist/web/index.html +4 -4
  76. package/docs/user-guide.html +137 -2
  77. package/env.example.yaml +1 -0
  78. package/forgeqe.example.yaml +14 -0
  79. package/package.json +1 -1
  80. package/prompts/brain.md +6 -3
  81. package/prompts/doc-reader.md +49 -0
  82. package/prompts/knowledge-agent.md +64 -0
  83. package/py/forgeqe_engine/brand.py +10 -1
  84. package/py/forgeqe_engine/capture.py +28 -12
  85. package/py/forgeqe_engine/logins.py +27 -0
  86. package/py/forgeqe_engine/loops.py +9 -0
  87. package/py/forgeqe_engine/memory.py +59 -0
  88. package/py/forgeqe_engine/recordsession.py +315 -40
  89. package/py/forgeqe_engine/service.py +11 -3
  90. package/py/forgeqe_engine/webrecord.py +153 -12
  91. package/py/forgeqe_engine/webrecord_page.py +211 -45
  92. package/dist/web/assets/Chat-czaM5kUi.js +0 -3
  93. package/dist/web/assets/Record-CoCnmfqW.js +0 -2
  94. package/dist/web/assets/filters-NVjc0d8i.js +0 -1
  95. package/dist/web/assets/frame-B0nzdTfN.js +0 -4
  96. package/dist/web/assets/index-RzPHjTCW.css +0 -2
  97. package/dist/web/assets/thread-BIUxcjeu.js +0 -5
@@ -27,12 +27,12 @@ import secrets
27
27
  import time
28
28
  from pathlib import Path
29
29
  from types import SimpleNamespace
30
- from typing import Any, Callable, Dict, List, Optional
30
+ from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
31
31
 
32
32
  from .capture import capture_element, locate_check
33
- from .memory import BASE, KEPT_ATTRS, candidate_locators, confidence, looks_generated
33
+ from .memory import BASE, KEPT_ATTRS, candidate_locators, confidence, looks_generated, within_locator
34
34
  from . import dynamic
35
- from .webrecord import Target, WebRecorder, auto_name, describe, upload_path
35
+ from .webrecord import CAPTCHA_FRAMES, MAX_UPLOAD_FILES, Target, WebRecorder, auto_name, captcha_of, describe, keep_upload, upload_path
36
36
  from .webrecord_page import recorder_js
37
37
 
38
38
 
@@ -119,8 +119,16 @@ class RecordSession:
119
119
  self.usage = {"input": 0, "output": 0}
120
120
  tag = secrets.token_hex(8)
121
121
  self.world = f"forgeqe_rec_{tag}"
122
+ # The page's own world: closed shadow roots are opened as they are made (open_shadow_js), and the ones that were
123
+ # closed are kept beside this key in its closure, never on the page's window.
124
+ self.shadow_key = secrets.token_hex(12)
122
125
  self.binding = f"__fqe_{tag}"
123
126
  self.pages: Dict[str, Dict[str, Any]] = {}
127
+ # Cross-origin frames: each one Chrome runs as a target of its own (an out-of-process iframe), by its session,
128
+ # with the session it was found in (its parent) and the tab it belongs to.
129
+ self.frames: Dict[str, Dict[str, Any]] = {}
130
+ # The recorder's world in each frame: (session, execution context) → frame id, from Runtime.executionContextCreated.
131
+ self.contexts: Dict[Tuple[str, int], str] = {}
124
132
  self.active: Optional[str] = None
125
133
  self.stop_reason = ""
126
134
  # When the tester started and stopped, for how long the recording took (the Record page's Duration).
@@ -196,6 +204,7 @@ class RecordSession:
196
204
  reg.Target.attachedToTarget(self._queue("attached"))
197
205
  reg.Target.detachedFromTarget(self._queue("detached"))
198
206
  reg.Runtime.bindingCalled(self._queue("binding"))
207
+ reg.Runtime.executionContextCreated(self._queue("context"))
199
208
  reg.Page.frameNavigated(self._queue("navigated"))
200
209
  reg.Page.navigatedWithinDocument(self._queue("navigated_same"))
201
210
  reg.Page.frameRequestedNavigation(self._queue("requested"))
@@ -262,7 +271,9 @@ class RecordSession:
262
271
  except asyncio.TimeoutError:
263
272
  continue
264
273
  await self._handle(item)
265
- # Typing not yet reported (the tester stopped with the caret still in a field).
274
+ # Typing not yet reported (the tester stopped with the caret still in a field), in a frame too.
275
+ for tab in list(self.pages):
276
+ await self._frame_calls(tab, "__fqeRec.flush()")
266
277
  for sid, page in list(self.pages.items()):
267
278
  ctx = page.get("ctx")
268
279
  if ctx:
@@ -296,7 +307,14 @@ class RecordSession:
296
307
  kind, event, sid = item
297
308
  try:
298
309
  if kind == "attached":
299
- await self._attached(event)
310
+ await self._attached(event, sid)
311
+ elif kind == "context":
312
+ c = event.get("context") or {}
313
+ aux = c.get("auxData") or {}
314
+ if sid and c.get("name") == self.world and aux.get("frameId") and isinstance(c.get("id"), int):
315
+ if len(self.contexts) > 5000:
316
+ self.contexts.clear()
317
+ self.contexts[(sid, c["id"])] = str(aux["frameId"])
300
318
  elif kind == "detached":
301
319
  self._detached(event)
302
320
  elif kind == "binding":
@@ -336,12 +354,15 @@ class RecordSession:
336
354
 
337
355
  # -- pages ----------------------------------------------------------------------------------------------------
338
356
 
339
- async def _attached(self, event: Dict[str, Any]) -> None:
357
+ async def _attached(self, event: Dict[str, Any], parent: Optional[str] = None) -> None:
340
358
  sid = event.get("sessionId")
341
359
  info = event.get("targetInfo") or {}
342
360
  if not sid:
343
361
  return
344
362
  try:
363
+ if info.get("type") == "iframe" and parent and (parent in self.pages or parent in self.frames):
364
+ await self._frame_attached(sid, parent)
365
+ return
345
366
  if info.get("type") != "page":
346
367
  return
347
368
  await self.send("Page.enable", None, sid)
@@ -351,7 +372,10 @@ class RecordSession:
351
372
  # The page's own calls to its server, kept by step (only method, path and status: never a query or a body).
352
373
  await self.send("Network.enable", None, sid)
353
374
  js = recorder_js(self.binding, KEPT_ATTRS, leader=self.leader, badge=self.payload.get("panel") == "badge")
375
+ await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": open_shadow_js(self.shadow_key)}, sid)
354
376
  await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": js, "worldName": self.world}, sid)
377
+ # Its cross-origin frames are targets of their own: attached as they start, held until the script is in.
378
+ await self.send("Target.setAutoAttach", {"autoAttach": True, "waitForDebuggerOnStart": True, "flatten": True}, sid)
355
379
  tree = await self.send("Page.getFrameTree", None, sid)
356
380
  frame = ((tree.get("frameTree") or {}).get("frame") or {}).get("id")
357
381
  self.pages[sid] = {"target": info.get("targetId"), "frame": frame, "opener": bool(info.get("openerId")), "history": None}
@@ -365,8 +389,24 @@ class RecordSession:
365
389
  except Exception:
366
390
  pass
367
391
 
392
+ async def _frame_attached(self, sid: str, parent: str) -> None:
393
+ """A cross-origin frame of a recorded tab (nested in another, or not): the same page script, in the same world."""
394
+ page = parent if parent in self.pages else (self.frames.get(parent) or {}).get("page")
395
+ self.frames[sid] = {"parent": parent, "page": page}
396
+ await self.send("Page.enable", None, sid)
397
+ await self.send("Runtime.enable", None, sid)
398
+ await self.send("Runtime.addBinding", {"name": self.binding, "executionContextName": self.world}, sid)
399
+ js = recorder_js(self.binding, KEPT_ATTRS, leader=self.leader, badge=self.payload.get("panel") == "badge")
400
+ await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": open_shadow_js(self.shadow_key)}, sid)
401
+ await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": js, "worldName": self.world}, sid)
402
+ await self.send("Target.setAutoAttach", {"autoAttach": True, "waitForDebuggerOnStart": True, "flatten": True}, sid)
403
+
368
404
  def _detached(self, event: Dict[str, Any]) -> None:
369
405
  sid = event.get("sessionId")
406
+ if self.frames.pop(sid, None) is not None:
407
+ for key in [k for k in self.contexts if k[0] == sid]:
408
+ del self.contexts[key]
409
+ return
370
410
  if self.pages.pop(sid, None) is None:
371
411
  return
372
412
  if self.active == sid:
@@ -435,12 +475,21 @@ class RecordSession:
435
475
  return
436
476
  if not isinstance(data, dict):
437
477
  return
438
- if name != self.binding or sid not in self.pages or self.rec is None:
478
+ if name != self.binding or self.rec is None or not sid:
439
479
  return
440
- page = self.pages[sid]
441
480
  ctx = event.get("executionContextId")
442
- page["ctx"] = ctx
443
481
  kind = data.get("kind")
482
+ # A step in a frame: found in that frame's own context, and placed in the page by its frames (frame_chain).
483
+ framed = bool(data.get("frame")) or sid in self.frames
484
+ if framed:
485
+ tab = sid if sid in self.pages else (self.frames.get(sid) or {}).get("page")
486
+ if tab not in self.pages or kind in ("ready", "panel_ui") or not isinstance(ctx, int):
487
+ return
488
+ else:
489
+ if sid not in self.pages:
490
+ return
491
+ tab = sid
492
+ self.pages[sid]["ctx"] = ctx
444
493
  if kind == "ready":
445
494
  # A page that loaded: the panel shows the recording so far, where the tester left it.
446
495
  await self._page_call(sid, f"__fqeRec.render({json.dumps(self._state())})")
@@ -451,29 +500,55 @@ class RecordSession:
451
500
  self.ui = {"collapsed": bool(u.get("collapsed")), "x": num(u.get("x")), "y": num(u.get("y"))}
452
501
  self._render()
453
502
  return
454
- self.active = sid
503
+ self.active = tab
455
504
  rec = self.rec
505
+ chain = await self.frame_chain(sid, ctx) if framed else []
506
+ # In a CAPTCHA's frame: one step for the person solving it, never its clicks and keys.
507
+ provider = captcha_of(chain) if framed else ""
508
+ # Or on a CAPTCHA's own layer in the page, which the page script names (only a name of CAPTCHA_FRAMES).
509
+ if kind == "captcha":
510
+ named = str(data.get("provider") or "")
511
+ provider = named if named in {n for n, _ in CAPTCHA_FRAMES} else ""
512
+ if not provider:
513
+ return
514
+ if provider and kind in ("click", "dblclick", "fill", "select", "press", "captcha"):
515
+ msg = rec.on_captcha(provider)
516
+ if msg:
517
+ self._changed(msg)
518
+ return
519
+
520
+ async def target(d: Dict[str, Any]) -> Target:
521
+ t = await self._target(sid, d, ctx=ctx)
522
+ # A frame's element belongs to the page the tab shows; the frames say where in it.
523
+ if framed:
524
+ t = Target(rec.url or t.url, t.facts, t.locators, chain, closed_shadow=t.closed_shadow)
525
+ t.position = click_position(d.get("position"))
526
+ return t
527
+
456
528
  msg: Optional[str] = None
457
529
  if kind == "click":
458
- t = await self._target(sid, data)
459
- hover = await self._target(sid, data["hover"]) if isinstance(data.get("hover"), dict) else None
530
+ t = await target(data)
531
+ hover = await target(data["hover"]) if isinstance(data.get("hover"), dict) else None
460
532
  msg = rec.on_click(t, hover=hover)
461
533
  elif kind == "dblclick":
462
- msg = rec.on_dblclick(await self._target(sid, data))
534
+ msg = rec.on_dblclick(await target(data))
463
535
  elif kind == "fill":
464
- t = await self._target(sid, data)
536
+ t = await target(data)
465
537
  msg = rec.on_fill(t, None if data.get("password") else str(data.get("value") or ""), password=bool(data.get("password")))
466
538
  elif kind == "select":
467
- msg = rec.on_select(await self._target(sid, data), str(data.get("text") or ""))
539
+ msg = rec.on_select(await target(data), str(data.get("text") or ""))
468
540
  elif kind == "press":
469
541
  msg = rec.on_press(str(data.get("keys") or ""), in_field=bool(data.get("in_field")), autocomplete=bool(data.get("autocomplete")))
470
542
  elif kind == "upload":
471
- msg = await self._uploaded(sid, data)
543
+ msg = await self._uploaded(sid, data, ctx, target)
472
544
  elif kind == "unsupported":
473
545
  msg = rec.on_unsupported(str(data.get("action") or "action"), str(data.get("reason") or ""))
474
546
  elif kind == "pick":
475
- msg = await self._picked(sid, data)
547
+ # Picked here: a pick waiting in the tab's other frames (or the page) is over.
548
+ await self._cancel_picks(tab, but=(sid, ctx))
549
+ msg = await self._picked(data, target)
476
550
  elif kind == "pick_cancel":
551
+ await self._cancel_picks(tab, but=(sid, ctx))
477
552
  msg = "pick cancelled"
478
553
  elif kind == "command":
479
554
  # From the key bar or the panel: the panel's carry what they act on (a step, a kind, the chat text).
@@ -483,11 +558,68 @@ class RecordSession:
483
558
  if msg:
484
559
  self._changed(msg)
485
560
 
486
- async def _target(self, sid: str, data: Dict[str, Any]) -> Target:
487
- """The element an event names, with its facts and locators read from the live page; the page's own facts if it is gone."""
561
+ def _frame_contexts(self, tab: str) -> List[Tuple[str, int]]:
562
+ """The recorder's world in each frame of a tab (same-origin frames in its session, cross-origin ones in theirs)."""
563
+ page_frame = (self.pages.get(tab) or {}).get("frame")
564
+ return [(s, c) for (s, c), f in self.contexts.items() if (s == tab and f != page_frame) or (self.frames.get(s) or {}).get("page") == tab]
565
+
566
+ async def _frame_calls(self, tab: str, expression: str, but: Optional[Tuple[str, int]] = None) -> None:
567
+ for s, c in self._frame_contexts(tab):
568
+ if (s, c) == but:
569
+ continue
570
+ try:
571
+ await self.send("Runtime.evaluate", {"expression": f"globalThis.__fqeRec && {expression}", "contextId": c}, s)
572
+ except Exception:
573
+ pass
574
+
575
+ async def _cancel_picks(self, tab: str, but: Tuple[str, Any]) -> None:
576
+ page = self.pages.get(tab) or {}
577
+ if (tab, page.get("ctx")) != but:
578
+ await self._page_call(tab, "__fqeRec.cancelPick()")
579
+ await self._frame_calls(tab, "__fqeRec.cancelPick()", but=but)
580
+
581
+ async def frame_chain(self, sid: str, ctx: int) -> List[Dict[str, Any]]:
582
+ """
583
+ Where a frame is in its page, outermost first: each <iframe> (or <frame>) that holds it, read in the document
584
+ that holds it through the DevTools protocol (DOM.getFrameOwner), so a cross-origin frame's place is known too:
585
+ its id, name, title, address and its place among the frames there. At most MAX_FRAME_DEPTH deep.
586
+ """
587
+ fid = self.contexts.get((sid, ctx))
588
+ chain: List[Dict[str, Any]] = []
589
+ cur = sid
590
+ for _ in range(MAX_FRAME_DEPTH * 2):
591
+ if not fid or len(chain) >= MAX_FRAME_DEPTH:
592
+ break
593
+ try:
594
+ tree = (await self.send("Page.getFrameTree", None, cur)).get("frameTree") or {}
595
+ except Exception:
596
+ break
597
+ parent = _frame_parent(tree, fid)
598
+ # The top of a cross-origin frame's own target: its <iframe> is in the document of the session above.
599
+ at = cur
600
+ if parent is None and cur in self.frames:
601
+ parent = str((tree.get("frame") or {}).get("parentId") or "") if str((tree.get("frame") or {}).get("id") or "") == fid else None
602
+ at = self.frames[cur]["parent"]
603
+ if not parent:
604
+ break
605
+ try:
606
+ owner = await self.send("DOM.getFrameOwner", {"frameId": fid}, at)
607
+ facts = await _frame_facts(self, at, int(owner.get("backendNodeId") or 0))
608
+ except Exception as ex:
609
+ logger.debug("record: a frame's place was not read: %s", ex)
610
+ facts = {}
611
+ chain.insert(0, facts)
612
+ fid, cur = parent, at
613
+ return [f for f in chain if f] if all(chain) else []
614
+
615
+ async def _target(self, sid: str, data: Dict[str, Any], ctx: Optional[int] = None) -> Target:
616
+ """
617
+ The element an event names, with its facts and locators read from the live page; the page's own facts if it is
618
+ gone. `ctx`: the recorder's context it came from (a frame's), else the tab's page.
619
+ """
488
620
  url = str(data.get("url") or (self.rec.url if self.rec else ""))
489
621
  page = self.pages.get(sid) or {}
490
- ctx = page.get("ctx")
622
+ ctx = ctx if ctx is not None else page.get("ctx")
491
623
  backend = None
492
624
  if ctx is not None and isinstance(data.get("id"), int):
493
625
  try:
@@ -500,22 +632,65 @@ class RecordSession:
500
632
  logger.debug("record: element not found on the page: %s", ex)
501
633
  fallback = fallback_target(url, data.get("el") or {}, data.get("matches"))
502
634
  target = fallback
635
+ closed = await self._in_closed_shadow(sid, int(backend)) if backend else False
636
+ fallback.closed_shadow = closed
503
637
  if backend:
504
638
  captured = await capture_element(_Page(self.client, sid), int(backend))
505
639
  if captured:
506
- live = Target(url, captured["facts"], captured["locators"])
640
+ live = Target(url, captured["facts"], captured["locators"], closed_shadow=closed)
507
641
  # The page went away while its locators were being checked (a form that submits): the page script
508
642
  # counted them at the event, so its count stands in for a check that never finished.
509
643
  if not (not any(l.get("verified") for l in live.locators) and any(l.get("verified") for l in fallback.locators)):
510
644
  target = live
511
- return await self._steady(sid, target, data.get("matches") if isinstance(data.get("matches"), dict) else {})
645
+ # None of its own locators unique: the one anchored on its container (the page script counted it), where there is one.
646
+ anchored = within_locator(data.get("anchor"))
647
+ if anchored and not any(l.get("verified") and l.get("matches") == 1 and l.get("type") in STRONG_ALONE for l in target.locators):
648
+ locs = sorted(target.locators + [anchored], key=lambda l: (not l.get("verified"), -int(l.get("confidence") or 0)))
649
+ target = Target(target.url, target.facts, locs, target.frames, closed_shadow=target.closed_shadow)
650
+ return await self._steady(sid, target, data.get("matches") if isinstance(data.get("matches"), dict) else {}, ctx=ctx)
651
+
652
+ async def _in_closed_shadow(self, sid: str, backend: int) -> bool:
653
+ """
654
+ Whether an element is inside a shadow root the page asked for closed (open_shadow_js opened it): the hosts are
655
+ kept in the closure of the page's attachShadow, read through the DevTools protocol (its [[Scopes]]), so the page
656
+ finds nothing of ForgeQE on its window. False when it cannot tell (the page replaced attachShadow since).
657
+ """
658
+ try:
659
+ el = ((await self.send("DOM.resolveNode", {"backendNodeId": backend}, sid)).get("object") or {}).get("objectId")
660
+ if not el:
661
+ return False
662
+ fn = ((await self.send("Runtime.callFunctionOn", {"objectId": el, "functionDeclaration": "function() { return Element.prototype.attachShadow; }"}, sid)).get("result") or {}).get("objectId")
663
+ if not fn:
664
+ return False
665
+ props = await self.send("Runtime.getProperties", {"objectId": fn, "ownProperties": False}, sid)
666
+ scopes = next((p["value"].get("objectId") for p in props.get("internalProperties") or [] if p.get("name") == "[[Scopes]]" and p.get("value")), None)
667
+ if not scopes:
668
+ return False
669
+ closed = None
670
+ for scope in (await self.send("Runtime.getProperties", {"objectId": scopes, "ownProperties": True}, sid)).get("result") or []:
671
+ sid_obj = (scope.get("value") or {}).get("objectId")
672
+ if not sid_obj:
673
+ continue
674
+ names = {v.get("name"): v.get("value") or {} for v in (await self.send("Runtime.getProperties", {"objectId": sid_obj, "ownProperties": True}, sid)).get("result") or []}
675
+ # Ours: the closure holds this session's key and the set of closed hosts.
676
+ if (names.get("KEY") or {}).get("value") == self.shadow_key and (names.get("closed") or {}).get("className") == "WeakSet":
677
+ closed = names["closed"].get("objectId")
678
+ break
679
+ if not closed:
680
+ return False
681
+ check = "function(el) { for (let n = el, i = 0; n && i < 50; i++) { const r = n.getRootNode(); if (!(r instanceof ShadowRoot)) return false; if (this.has(r.host)) return true; n = r.host; } return false; }"
682
+ r = await self.send("Runtime.callFunctionOn", {"objectId": closed, "functionDeclaration": check, "arguments": [{"objectId": el}], "returnByValue": True}, sid)
683
+ return (r.get("result") or {}).get("value") is True
684
+ except Exception as ex:
685
+ logger.debug("record: closed shadow root not read: %s", ex)
686
+ return False
512
687
 
513
- async def _steady(self, sid: str, t: Target, counted: Optional[Dict[str, Any]] = None) -> Target:
688
+ async def _steady(self, sid: str, t: Target, counted: Optional[Dict[str, Any]] = None, ctx: Optional[int] = None) -> Target:
514
689
  """
515
690
  Locators that spell out data that changes (a product link named with its price) find nothing on the next run:
516
691
  each gets a pattern version by the part that holds, checked on the page, and goes after it.
517
692
  """
518
- ctx = (self.pages.get(sid) or {}).get("ctx")
693
+ ctx = ctx if ctx is not None else (self.pages.get(sid) or {}).get("ctx")
519
694
  extra: list = []
520
695
  for loc in t.locators:
521
696
  kind = loc.get("type")
@@ -557,39 +732,49 @@ class RecordSession:
557
732
  if not extra and not any(l.get("live_data") for l in t.locators):
558
733
  return t
559
734
  locs = sorted(t.locators + extra, key=lambda l: (not l.get("verified"), bool(l.get("live_data")), -int(l.get("confidence") or 0)))
560
- return Target(t.url, t.facts, locs)
735
+ return Target(t.url, t.facts, locs, t.frames, closed_shadow=t.closed_shadow)
561
736
 
562
- async def _uploaded(self, sid: str, data: Dict[str, Any]) -> Optional[str]:
563
- """The files chosen in a file field, by their paths on this machine, kept when a test may use them."""
737
+ async def _uploaded(self, sid: str, data: Dict[str, Any], ctx: Any, target: Callable[[Dict[str, Any]], Awaitable[Target]]) -> Optional[str]:
738
+ """
739
+ The files chosen in a file field, or dropped on the page (`drop`), by their paths on this machine: kept where a
740
+ test may use them (keep_upload: the working folder, else a copy in the recording's folder).
741
+ """
564
742
  rec = self.rec
565
743
  assert rec is not None
566
- t = await self._target(sid, data)
744
+ t = await target(data)
567
745
  paths: list = []
568
- ctx = (self.pages.get(sid) or {}).get("ctx")
746
+ drop = bool(data.get("drop"))
569
747
  try:
570
- r = await self.send("Runtime.evaluate", {"expression": f"__fqeRec.el({int(data.get('id', -1))})", "contextId": ctx}, sid)
571
- field_obj = (r.get("result") or {}).get("objectId")
572
- for i in range(min(int(data.get("count") or 0), 10)):
573
- f = await self.send("Runtime.callFunctionOn", {"objectId": field_obj, "functionDeclaration": "function(i){return this.files[i]}", "arguments": [{"value": i}]}, sid)
748
+ expr = f"__fqeRec.dropped({int(data.get('drop_id', -1))})" if drop else f"__fqeRec.el({int(data.get('id', -1))})"
749
+ r = await self.send("Runtime.evaluate", {"expression": expr, "contextId": ctx}, sid)
750
+ holder = (r.get("result") or {}).get("objectId")
751
+ pick = "function(i){return this[i]}" if drop else "function(i){return this.files[i]}"
752
+ for i in range(min(int(data.get("count") or 0), MAX_UPLOAD_FILES)):
753
+ f = await self.send("Runtime.callFunctionOn", {"objectId": holder, "functionDeclaration": pick, "arguments": [{"value": i}]}, sid)
574
754
  oid = (f.get("result") or {}).get("objectId")
575
755
  if oid:
576
756
  info = await self.send("DOM.getFileInfo", {"objectId": oid}, sid)
577
757
  paths.append(str(info.get("path") or ""))
578
758
  except Exception as ex:
579
759
  logger.debug("record: upload paths not read: %s", ex)
580
- if not paths:
760
+ if not [p for p in paths if p]:
581
761
  return rec.on_unsupported("upload", "the chosen files could not be read; add the upload in the test")
582
- files, refused = [], []
762
+ files, run_files, refused = [], [], []
583
763
  for p in paths:
584
- rel, why = upload_path(p, str(self.payload.get("work_dir") or ""))
585
- (files.append(rel) if rel else refused.append(why))
586
- return rec.on_upload(t, files, refused)
764
+ kind, ref, why = keep_upload(p, str(self.payload.get("work_dir") or ""), str(self.out_dir))
765
+ if kind == "work":
766
+ files.append(ref)
767
+ elif kind == "run":
768
+ run_files.append(ref)
769
+ else:
770
+ refused.append(why)
771
+ return rec.on_upload(t, files, refused, run_files=run_files, drop=drop)
587
772
 
588
- async def _picked(self, sid: str, data: Dict[str, Any]) -> str:
773
+ async def _picked(self, data: Dict[str, Any], target: Callable[[Dict[str, Any]], Awaitable[Target]]) -> str:
589
774
  purpose = data.get("purpose")
590
775
  rec = self.rec
591
776
  assert rec is not None
592
- t = await self._target(sid, data)
777
+ t = await target(data)
593
778
  text = str(data.get("text") or "")
594
779
  if purpose == "variable":
595
780
  return rec.add_capture(t, text)
@@ -639,6 +824,8 @@ class RecordSession:
639
824
  except Exception:
640
825
  pass
641
826
  await self._page_call(sid, f"__fqeRec.pick({json.dumps(cmd)})")
827
+ # The element can be in a frame: each frame of the tab picks too, and the first pick ends the others.
828
+ await self._frame_calls(sid, f"__fqeRec.pick({json.dumps(cmd)})")
642
829
  self.log(f"Pick the element in the page {'to check' if cmd == 'assert' else 'whose text to keep' if cmd == 'variable' else 'to wait for'} (Esc cancels).")
643
830
  return
644
831
  if cmd == "note":
@@ -1078,6 +1265,94 @@ def _count(loc: Dict[str, Any], counted: Dict[str, Any]) -> Optional[int]:
1078
1265
  return n if isinstance(n, int) and n >= 0 else None
1079
1266
 
1080
1267
 
1268
+ MAX_FRAME_DEPTH = 6
1269
+ # Locator kinds that, unique, find the element by itself: no anchored one is added then.
1270
+ STRONG_ALONE = ("test_id", "id", "role", "label", "placeholder", "name", "href", "text")
1271
+
1272
+
1273
+ def open_shadow_js(key: str) -> str:
1274
+ """
1275
+ In the page's own world, before its scripts: a shadow root the page asks for closed is made open, so its controls
1276
+ can be recorded and found, as the replay and the written test make it (src/code/replay.ts OPEN_SHADOW). The hosts
1277
+ asked for closed are kept in its closure beside `key` (never on the page's window), so a step there says so. Playwright cannot reach into a closed root otherwise.
1278
+ A root declared closed in the page's HTML (<template shadowrootmode="closed">) is made by the parser and stays closed.
1279
+ """
1280
+ return OPEN_SHADOW_JS.replace("__KEY__", json.dumps(key))
1281
+
1282
+
1283
+ OPEN_SHADOW_JS = r"""(() => {
1284
+ // Nothing of this is on the page's window: the hosts asked for closed are in this closure only, which ForgeQE reads
1285
+ // through the DevTools protocol (RecordSession._in_closed_shadow), with KEY to know it is its own.
1286
+ const KEY = __KEY__;
1287
+ const closed = new WeakSet();
1288
+ const attach = Element.prototype.attachShadow;
1289
+ Element.prototype.attachShadow = function attachShadow(init) {
1290
+ const root = attach.call(this, Object.assign({}, init, { mode: 'open' }));
1291
+ if (init && init.mode === 'closed' && KEY) closed.add(this);
1292
+ return root;
1293
+ };
1294
+ })()"""
1295
+
1296
+
1297
+ def click_position(raw: Any) -> Optional[Dict[str, int]]:
1298
+ """Where in a canvas a click landed, as the page script reported it: two whole numbers within a page's size, else None."""
1299
+ if not isinstance(raw, dict):
1300
+ return None
1301
+ x, y = raw.get("x"), raw.get("y")
1302
+ ok = lambda v: isinstance(v, int) and not isinstance(v, bool) and 0 <= v <= 20000 # noqa: E731
1303
+ return {"x": x, "y": y} if ok(x) and ok(y) else None
1304
+
1305
+
1306
+ def _frame_parent(tree: Dict[str, Any], fid: str, parent: Optional[str] = None) -> Optional[str]:
1307
+ """The id of the frame that holds frame `fid` in a frame tree (Page.getFrameTree), or None at its top or when absent."""
1308
+ stack = [(tree, parent)]
1309
+ while stack:
1310
+ node, up = stack.pop()
1311
+ if str((node.get("frame") or {}).get("id") or "") == fid:
1312
+ return up
1313
+ me = str((node.get("frame") or {}).get("id") or "")
1314
+ stack.extend((c, me) for c in node.get("childFrames") or [] if isinstance(c, dict))
1315
+ return None
1316
+
1317
+
1318
+ # What names an <iframe> in the document that holds it: its attributes, and its place among the frames there (the
1319
+ # fallback when it has none). Read as data: a page can put anything in them.
1320
+ _FRAME_FN = r"""function() {
1321
+ const out = { index: [...this.ownerDocument.querySelectorAll('iframe, frame')].indexOf(this) };
1322
+ for (const k of ['id', 'name', 'title', 'src']) { const v = this.getAttribute(k); if (v) out[k] = v.slice(0, 300); }
1323
+ return out;
1324
+ }"""
1325
+
1326
+
1327
+ async def _frame_facts(s: "RecordSession", sid: str, backend: int) -> Dict[str, Any]:
1328
+ """An <iframe>'s facts for a step's `frame`: plain one-line text, a generated id or name left out (it changes)."""
1329
+ if not backend:
1330
+ return {}
1331
+ obj = ((await s.send("DOM.resolveNode", {"backendNodeId": backend}, sid)).get("object") or {}).get("objectId")
1332
+ if not obj:
1333
+ return {}
1334
+ got = ((await s.send("Runtime.callFunctionOn", {"objectId": obj, "functionDeclaration": _FRAME_FN, "returnByValue": True}, sid)).get("result") or {}).get("value")
1335
+ return clean_frame(got)
1336
+
1337
+
1338
+ def clean_frame(raw: Any) -> Dict[str, Any]:
1339
+ """A frame's facts as a step keeps them: known keys only, each one line and capped; ids and names a build made dropped."""
1340
+ if not isinstance(raw, dict):
1341
+ return {}
1342
+ out: Dict[str, Any] = {}
1343
+ for k in ("id", "name", "title", "src"):
1344
+ v = " ".join(str(raw.get(k) or "").split())[:300]
1345
+ if not v or (k in ("id", "name") and looks_generated(v)):
1346
+ continue
1347
+ if k == "src" and re.match(r"^[a-z][a-z0-9+.-]*:", v, re.I) and not re.match(r"^https?:", v, re.I):
1348
+ # Only an address on the web or a path: no javascript:, data: or about: text in a locator.
1349
+ continue
1350
+ out[k] = v
1351
+ if isinstance(raw.get("index"), int) and not isinstance(raw.get("index"), bool) and 0 <= raw["index"] < 1000:
1352
+ out["index"] = raw["index"]
1353
+ return out
1354
+
1355
+
1081
1356
  def fallback_target(url: str, facts: Dict[str, Any], counted: Optional[Dict[str, Any]] = None) -> Target:
1082
1357
  """
1083
1358
  A target from the facts the page script read, for an element the page took away before ForgeQE could look at it.
@@ -22,7 +22,7 @@ from typing import Any, Callable, Dict, List, Optional, Set, Tuple
22
22
 
23
23
  from . import brand, userlike
24
24
  from .diagnostics import Diagnostics, box_for
25
- from .logins import _host_matches, can_sign_in, code_logins, guard_secrets, load_sessions, parse_logins, passkey_logins, prompt_block, push_logins, register_code_action, register_mfa_actions, save_sessions, use_logins
25
+ from .logins import _host_matches, can_sign_in, code_logins, guard_secrets, load_sessions, parse_logins, passkey_logins, prompt_block, push_logins, register_code_action, register_mfa_actions, save_sessions, use_env_secrets, use_logins
26
26
  from .memory import READ_ONLY_ACTIONS, MemoryStore, compact_step, flow_step, page_id
27
27
  from .prompts import CONVENTIONS, text as prompt_text, use_prompts
28
28
  from .report import CASE_REPORT_INSTRUCTION, CaseReport, build_timeline, case_report_from_history
@@ -77,6 +77,7 @@ from .loops import (
77
77
  making_progress,
78
78
  resume_point,
79
79
  resume_steps,
80
+ flow_step_number,
80
81
  _resolve_browser_control_loop_max_retries,
81
82
  _resolve_browser_control_loop_window,
82
83
  _loop_start,
@@ -121,6 +122,8 @@ class RunRequest:
121
122
  memory: Dict[str, Any] = field(default_factory=dict)
122
123
  # [{name, domains, username_env, password_env, totp_env, session_file}]
123
124
  logins: List[Dict[str, Any]] = field(default_factory=list)
125
+ # The environment's secret variables [{name, env, domains}] (env.yaml TestPassword: password): typed from <secret>name</secret>.
126
+ env_secrets: List[Dict[str, Any]] = field(default_factory=list)
124
127
  # Start the browser with the logins' saved sessions; false for a test case, which a test runs from a fresh browser.
125
128
  restore_sessions: bool = True
126
129
  # Set during the run: the logins whose saved session the browser started with, and each one's sites.
@@ -166,6 +169,7 @@ class RunRequest:
166
169
  def from_dict(cls, d: Dict[str, Any]) -> "RunRequest":
167
170
  return cls(
168
171
  logins=[x for x in (d.get("logins") or []) if isinstance(x, dict)],
172
+ env_secrets=[x for x in (d.get("env_secrets") or []) if isinstance(x, dict)],
169
173
  restore_sessions=d.get("restore_sessions") is not False,
170
174
  case_steps=int(d["case_steps"]) if str(d.get("case_steps") or "").isdigit() else 0,
171
175
  case_id=str(d.get("case_id") or ""),
@@ -1093,6 +1097,8 @@ async def run_browser_task(req: RunRequest, emit: Emit, cancel_event: asyncio.Ev
1093
1097
  sensitive, missing = use_logins(logins)
1094
1098
  for env in missing:
1095
1099
  emit({"type": "log", "level": "warn", "text": f"Saved login: {env} is not set, so that value is not available to the agent"})
1100
+ for name in use_env_secrets(sensitive, req.env_secrets):
1101
+ emit({"type": "log", "level": "warn", "text": f"Environment value {name}: its environment variable is not set (.env or the shell), so <secret>{name}</secret> cannot be typed"})
1096
1102
  # A test case runs from the state its test starts from: signed out. A login the agent cannot sign in to itself (no
1097
1103
  # username or password here) keeps its saved session, the only way in; the handoff then says the run started with it.
1098
1104
  restoring = logins if req.restore_sessions else [l for l in logins if not can_sign_in(l, missing)]
@@ -1562,8 +1568,10 @@ async def run_browser_task(req: RunRequest, emit: Emit, cancel_event: asyncio.Ev
1562
1568
  if not steps:
1563
1569
  return
1564
1570
  first_line = (str(reason or "").strip().splitlines() or [""])[0]
1565
- mem.resume = {"steps": steps, "reason": first_line[:400], "failed_at": at, "run_id": out_dir.name}
1566
- emit({"type": "memory", "text": f"Kept the {len(steps)} steps that worked before step {at}; the next run of this task replays them and picks up there"})
1571
+ # The agent counts its own steps; after a replay of earlier steps, the flow's step is after those.
1572
+ flow_at = flow_step_number(replay_offset, at)
1573
+ mem.resume = {"steps": steps, "reason": first_line[:400], "failed_at": flow_at, "run_id": out_dir.name}
1574
+ emit({"type": "memory", "text": f"Kept the {len(steps)} steps that worked before step {flow_at}; the next run of this task replays them and picks up there"})
1567
1575
 
1568
1576
  def _plan_assertion_resume(reason: str) -> None:
1569
1577
  """An expected result did not hold: keep the steps that led to it, so the next run replays them and checks it again."""