@capagents/forgeqe 2.9.1 → 2.9.3
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/HOW_TO_USE.md +1 -1
- package/dist/docs-site/docs/architecture/index.html +6 -0
- package/dist/docs-site/docs/index.html +1 -1
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/docs-site/docs/web-app/index.html +12 -1
- package/dist/forgeqe.js +1722 -1676
- package/dist/web/assets/Agent-B6xfobJ9.js +4 -0
- package/dist/web/assets/ApiTests-BwgezlYi.js +10 -0
- package/dist/web/assets/Browse-DDzk_KTh.js +2 -0
- package/dist/web/assets/Chat-BdlfK2ra.js +3 -0
- package/dist/web/assets/{CommandPalette-VSEzjRS1.js → CommandPalette-Cla7m818.js} +1 -1
- package/dist/web/assets/{Compare-Bjh-qB8C.js → Compare-BxUfo0rI.js} +1 -1
- package/dist/web/assets/Cost-Dpa8aWQG.js +1 -0
- package/dist/web/assets/Data-D_7m2GL6.js +6 -0
- package/dist/web/assets/Desktop-CgslBkAr.js +1 -0
- package/dist/web/assets/DesktopReview-CsW65QZz.js +1 -0
- package/dist/web/assets/Evidence-SYt-mbDx.js +1 -0
- package/dist/web/assets/Explore--B18Jvg9.js +2 -0
- package/dist/web/assets/{Features-DFwuL5cN.js → Features-BerYifH7.js} +1 -1
- package/dist/web/assets/Flags-ABMq---p.js +2 -0
- package/dist/web/assets/Flaky-DKeceXsa.js +1 -0
- package/dist/web/assets/{ForceGraph-DC7NzeR4.js → ForceGraph-C9HFjZX3.js} +1 -1
- package/dist/web/assets/{Impact-CfnvrPzq.js → Impact-DQ2c0dTT.js} +3 -3
- package/dist/web/assets/Jobs-Dy_C2x36.js +5 -0
- package/dist/web/assets/KindPage-DQzstMyM.js +6 -0
- package/dist/web/assets/Migration-B4GWsCLR.js +2 -0
- package/dist/web/assets/Product-CgVhHMMY.js +7 -0
- package/dist/web/assets/Production-OdB4gZ3T.js +1 -0
- package/dist/web/assets/Quality-DOV4suvD.js +1 -0
- package/dist/web/assets/Readiness-DawfUUHc.js +1 -0
- package/dist/web/assets/Record-C9uAKGYM.js +2 -0
- package/dist/web/assets/Regression-DZdddPfI.js +5 -0
- package/dist/web/assets/{Reports-BWtgbiVp.js → Reports-BHOS6af1.js} +2 -2
- package/dist/web/assets/{Response-DyvlQXek.js → Response-qfMk4Nrh.js} +2 -2
- package/dist/web/assets/RunDiff-BNywFV7t.js +1 -0
- package/dist/web/assets/Runs-BJPYXRiB.js +2 -0
- package/dist/web/assets/{Steps-DUG1BKJb.js → Steps-Cdzyueit.js} +2 -2
- package/dist/web/assets/TestCases-DcYY2l9q.js +1 -0
- package/dist/web/assets/TestData-CrzKA3xh.js +2 -0
- package/dist/web/assets/TestDebt-CVDJT511.js +1 -0
- package/dist/web/assets/Tosca-CBwGCrbL.js +3 -0
- package/dist/web/assets/{WhatsNew-B3xewvk5.js → WhatsNew-CIOTidx-.js} +1 -1
- package/dist/web/assets/dataParts-CUb0Q0IZ.js +3 -0
- package/dist/web/assets/{families-DWrv-fcS.js → families-C9MndVzT.js} +1 -1
- package/dist/web/assets/filters-Bk7ovF3M.js +1 -0
- package/dist/web/assets/{fold-BgITvJex.js → fold-97yBCSav.js} +1 -1
- package/dist/web/assets/frame-CqWJMIHh.js +4 -0
- package/dist/web/assets/index-ASvNRLI7.js +73 -0
- package/dist/web/assets/index-B5o9vY-v.css +2 -0
- package/dist/web/assets/{logos-C067hMmF.js → logos-CbNeXLAM.js} +1 -1
- package/dist/web/assets/{palette-Br50dJuQ.js → palette-Dg3RS-ff.js} +1 -1
- package/dist/web/assets/{parts-CbA0h_uO.js → parts-CPAyV15O.js} +1 -1
- package/dist/web/assets/{productParts-BxQnjrHo.js → productParts-BpXw1jMa.js} +1 -1
- package/dist/web/assets/{qualityParts-Cn74cNyX.js → qualityParts-8TPKphgl.js} +1 -1
- package/dist/web/assets/recordTest-DvnpHsd2.js +1 -0
- package/dist/web/assets/{rows-X8lfgK8j.js → rows-BdYJLCRD.js} +1 -1
- package/dist/web/assets/segmented-DlF5rvSR.js +1 -0
- package/dist/web/assets/{thread-Bamx8xqR.js → thread-DlyX7xQt.js} +1 -1
- package/dist/web/assets/{usePageChat-B-vpiXQ6.js → usePageChat-Dhu3upXA.js} +1 -1
- package/dist/web/index.html +4 -4
- package/docs/ARCHITECTURE.md +5 -0
- package/docs/WEB_APP.md +17 -1
- package/docs/user-guide.html +1 -1
- package/forgeqe.example.yaml +1 -0
- package/package.json +1 -1
- package/prompts/brain.md +4 -3
- package/py/forgeqe_desktop/agentdesktop_driver.py +69 -0
- package/py/forgeqe_desktop/boxes.py +32 -0
- package/py/forgeqe_desktop/handhooks.py +55 -5
- package/py/forgeqe_desktop/pywinauto_driver.py +25 -0
- package/py/forgeqe_desktop/service.py +85 -3
- package/py/forgeqe_engine/brand.py +3 -0
- package/py/forgeqe_engine/browser.py +46 -6
- package/py/forgeqe_engine/cli.py +10 -1
- package/py/forgeqe_engine/recordsession.py +92 -2
- package/py/forgeqe_engine/video.py +423 -0
- package/py/forgeqe_mobile/hyperexecute.py +1 -1
- package/py/forgeqe_mobile/maestro.py +1 -1
- package/py/forgeqe_tosca/vendored.py +3 -2
- package/dist/web/assets/Agent-BNWcLTrm.js +0 -4
- package/dist/web/assets/ApiTests-CZFzjMKc.js +0 -10
- package/dist/web/assets/Browse-CeiK4X_V.js +0 -2
- package/dist/web/assets/Chat-BqXSNxV2.js +0 -3
- package/dist/web/assets/Cost-BRtni21m.js +0 -1
- package/dist/web/assets/Data-Bzn351xU.js +0 -6
- package/dist/web/assets/Evidence-eM1ZsFF-.js +0 -1
- package/dist/web/assets/Explore-D07Qbzyq.js +0 -2
- package/dist/web/assets/Flags-pxSAu21R.js +0 -2
- package/dist/web/assets/Flaky-BdfqCR6j.js +0 -1
- package/dist/web/assets/Jobs-CIKpgvcv.js +0 -5
- package/dist/web/assets/KindPage-OyYE9NU7.js +0 -6
- package/dist/web/assets/Migration-BQA6MOPN.js +0 -2
- package/dist/web/assets/Product-DNe8RV_H.js +0 -7
- package/dist/web/assets/Production-ClEiFS1u.js +0 -1
- package/dist/web/assets/Quality-BZnQcbb2.js +0 -1
- package/dist/web/assets/Readiness-Dk2KZZm4.js +0 -1
- package/dist/web/assets/Record-CSapdwkr.js +0 -2
- package/dist/web/assets/Regression-C7bZ5sSE.js +0 -5
- package/dist/web/assets/RunDiff-DWV5qdHx.js +0 -1
- package/dist/web/assets/Runs-CET6zwQu.js +0 -2
- package/dist/web/assets/TestCases-DyicRSqL.js +0 -1
- package/dist/web/assets/TestData-D2aWG3dq.js +0 -2
- package/dist/web/assets/TestDebt-DobUiGTz.js +0 -1
- package/dist/web/assets/Tosca-DvTni6va.js +0 -3
- package/dist/web/assets/dataParts-rU9wRwfo.js +0 -3
- package/dist/web/assets/filters-BDJYWuRV.js +0 -1
- package/dist/web/assets/frame-Dn34zQXO.js +0 -4
- package/dist/web/assets/index-BiMUTOBo.js +0 -45
- package/dist/web/assets/index-CGfii-zv.css +0 -2
- package/dist/web/assets/segmented-mcjXGwLg.js +0 -1
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
browser engine. A later ``stop`` line on stdin stops a replay between steps, or ends a recording.
|
|
4
4
|
|
|
5
5
|
Request: ``mode`` (``replay``, ``explore`` or ``record``), ``out_dir``, ``desktop`` (``apps``, ``secrets``,
|
|
6
|
-
``ufo_dir
|
|
6
|
+
``ufo_dir``, ``video`` (true: video.mp4 of the screen while the request runs, forgeqe_engine.video); for replay ``driver`` (``pywinauto`` or ``agent-desktop``), ``headed`` and ``agent_desktop.path``), ``llm`` and ``profile_name`` (the llms.json profile, for healing and explore), and per mode: ``workflow``,
|
|
7
7
|
``variables``, ``heal``, ``screenshots``, ``update_baselines`` (replay); ``goal``, ``app``, ``name`` (explore); ``app``,
|
|
8
8
|
``name`` (record: the tester does the steps by hand).
|
|
9
9
|
|
|
@@ -127,6 +127,7 @@ def run_replay(req: Mapping[str, Any], events: Events, driver: Any, stop: thread
|
|
|
127
127
|
if png:
|
|
128
128
|
shot = f"steps/{res.index:03d}.png"
|
|
129
129
|
(out / shot).write_bytes(png)
|
|
130
|
+
write_controls(driver, out / "steps" / f"{res.index:03d}.json")
|
|
130
131
|
events.emit({"type": "step", **_step_fields(res), "screenshot": shot})
|
|
131
132
|
|
|
132
133
|
result = replay(
|
|
@@ -345,6 +346,32 @@ def _explored_from_memory(req: Mapping[str, Any], events: Events, driver: Any, m
|
|
|
345
346
|
}
|
|
346
347
|
|
|
347
348
|
|
|
349
|
+
def write_controls(driver: Any, file: Path) -> None:
|
|
350
|
+
"""Beside a step's picture, the controls it shows (where each is, what it is called and shows), so a check can be
|
|
351
|
+
chosen by clicking the picture. Nothing when the driver cannot tell."""
|
|
352
|
+
snap = getattr(driver, "controls_snapshot", None)
|
|
353
|
+
if snap is None:
|
|
354
|
+
return
|
|
355
|
+
try:
|
|
356
|
+
boxes = snap()
|
|
357
|
+
except Exception:
|
|
358
|
+
boxes = None
|
|
359
|
+
if boxes and boxes.get("controls"):
|
|
360
|
+
file.write_text(json.dumps(boxes), encoding="utf-8")
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def recording_shots(steps: List[Dict[str, Any]], out: Path) -> List[Dict[str, Any]]:
|
|
364
|
+
"""Each recorded step's picture with what the step does and to which control, so a review finds a step's picture
|
|
365
|
+
by the step itself, after steps are added or removed."""
|
|
366
|
+
shots = []
|
|
367
|
+
for i, s in enumerate(steps, 1):
|
|
368
|
+
file = f"steps/{i:03d}.png"
|
|
369
|
+
if (out / file).is_file():
|
|
370
|
+
t = s.get("target") if isinstance(s.get("target"), dict) else {}
|
|
371
|
+
shots.append({"index": i, "file": file, "op": s.get("op"), "target": {k: t[k] for k in ("automation_id", "name", "control_type") if k in t}})
|
|
372
|
+
return shots
|
|
373
|
+
|
|
374
|
+
|
|
348
375
|
def run_record(req: Mapping[str, Any], events: Events, driver: Any, stop: threading.Event, recorder_loop: Optional[Callable[..., str]] = None) -> Dict[str, Any]:
|
|
349
376
|
"""Recording by hand: the tester does the steps, their clicks and keys become workflow.yaml. No model."""
|
|
350
377
|
from .handrecord import HandRecorder
|
|
@@ -363,8 +390,26 @@ def run_record(req: Mapping[str, Any], events: Events, driver: Any, stop: thread
|
|
|
363
390
|
started = time.time()
|
|
364
391
|
reason = ""
|
|
365
392
|
error = ""
|
|
393
|
+
# Each step's picture as the app showed it, as replay keeps them: steps/NNN.png in the run folder.
|
|
394
|
+
grab = getattr(driver, "screenshot_png", None)
|
|
395
|
+
want_shots = bool(req.get("screenshots", True)) and grab is not None
|
|
396
|
+
if want_shots:
|
|
397
|
+
(out / "steps").mkdir(exist_ok=True)
|
|
398
|
+
|
|
399
|
+
def on_shot(index: int) -> None:
|
|
400
|
+
try:
|
|
401
|
+
png = grab() if grab is not None else None
|
|
402
|
+
except Exception:
|
|
403
|
+
png = None
|
|
404
|
+
if png and 0 < index < 1000:
|
|
405
|
+
(out / "steps" / f"{index:03d}.png").write_bytes(png)
|
|
406
|
+
write_controls(driver, out / "steps" / f"{index:03d}.json")
|
|
407
|
+
|
|
366
408
|
try:
|
|
367
|
-
|
|
409
|
+
loop_kwargs: Dict[str, Any] = {"log": events.log, "on_change": lambda e: events.emit({"type": "recorded", **e})}
|
|
410
|
+
if want_shots:
|
|
411
|
+
loop_kwargs["on_shot"] = on_shot
|
|
412
|
+
reason = recorder_loop(driver, spec, recorder, stop, **loop_kwargs)
|
|
368
413
|
except Exception as e:
|
|
369
414
|
error = f"Recording stopped with an error: {type(e).__name__}: {e}"[:2000]
|
|
370
415
|
events.log(error, "error")
|
|
@@ -380,6 +425,10 @@ def run_record(req: Mapping[str, Any], events: Events, driver: Any, stop: thread
|
|
|
380
425
|
if recorded:
|
|
381
426
|
save(workflow, workflow_file)
|
|
382
427
|
checks = sum(1 for s in workflow["steps"] if s["op"] == "expect")
|
|
428
|
+
shots = recording_shots(workflow["steps"], out) if recorded else []
|
|
429
|
+
if shots:
|
|
430
|
+
(out / "shots.json").write_text(json.dumps(shots, indent=2), encoding="utf-8")
|
|
431
|
+
shot_of = {s["index"]: s["file"] for s in shots}
|
|
383
432
|
return {
|
|
384
433
|
"mode": "record",
|
|
385
434
|
"ok": recorded > 0 and not error,
|
|
@@ -392,7 +441,7 @@ def run_record(req: Mapping[str, Any], events: Events, driver: Any, stop: thread
|
|
|
392
441
|
"secrets": list(recorder.secrets_used),
|
|
393
442
|
"skipped": skipped,
|
|
394
443
|
"workflow": str(workflow_file) if recorded else None,
|
|
395
|
-
"steps": [{"index": i, "op": s["op"], "ok": True, "ms": 0, "target": s.get("target")} for i, s in enumerate(workflow["steps"], 1)],
|
|
444
|
+
"steps": [{"index": i, "op": s["op"], "ok": True, "ms": 0, "target": s.get("target"), "screenshot": shot_of.get(i)} for i, s in enumerate(workflow["steps"], 1)],
|
|
396
445
|
"error": error or ("" if recorded else "nothing was recorded: no click or typing in the app's windows"),
|
|
397
446
|
}
|
|
398
447
|
|
|
@@ -414,6 +463,29 @@ def default_driver(req: Mapping[str, Any]) -> Any:
|
|
|
414
463
|
return PywinautoDriver()
|
|
415
464
|
|
|
416
465
|
|
|
466
|
+
VIDEO_FILE = "video.mp4"
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _start_screen(req: Mapping[str, Any], events: Events, out: Path, factory: Optional[Callable[[Path], Any]] = None) -> Any:
|
|
470
|
+
"""desktop.video: the screen as video.mp4 in the run folder while the request runs; None (said once) when it cannot be."""
|
|
471
|
+
desktop = req.get("desktop") if isinstance(req.get("desktop"), dict) else {}
|
|
472
|
+
if desktop.get("video") is not True:
|
|
473
|
+
return None
|
|
474
|
+
if factory is not None:
|
|
475
|
+
screen = factory(out / VIDEO_FILE)
|
|
476
|
+
else:
|
|
477
|
+
try:
|
|
478
|
+
from forgeqe_engine.video import ScreenVideo
|
|
479
|
+
except Exception as e:
|
|
480
|
+
events.log(f"No video of this run: {type(e).__name__}", "warn")
|
|
481
|
+
return None
|
|
482
|
+
screen = ScreenVideo(out / VIDEO_FILE)
|
|
483
|
+
if not screen.start():
|
|
484
|
+
events.log(f"No video of this run: {screen.error}", "warn")
|
|
485
|
+
return None
|
|
486
|
+
return screen
|
|
487
|
+
|
|
488
|
+
|
|
417
489
|
def _watch_stop(stream: IO[str], stop: threading.Event) -> None:
|
|
418
490
|
for line in stream:
|
|
419
491
|
if line.strip() == "stop":
|
|
@@ -428,11 +500,13 @@ def serve(
|
|
|
428
500
|
runner: Optional[Callable[..., List[Dict[str, Any]]]] = None,
|
|
429
501
|
model_factory: Optional[Callable[..., Any]] = None,
|
|
430
502
|
recorder_loop: Optional[Callable[..., str]] = None,
|
|
503
|
+
screen_factory: Optional[Callable[[Path], Any]] = None,
|
|
431
504
|
) -> int:
|
|
432
505
|
events = Events(stdout)
|
|
433
506
|
stop = threading.Event()
|
|
434
507
|
result: Dict[str, Any]
|
|
435
508
|
out: Optional[Path] = None
|
|
509
|
+
screen: Any = None
|
|
436
510
|
driver_name = ""
|
|
437
511
|
req_mode = ""
|
|
438
512
|
try:
|
|
@@ -446,6 +520,8 @@ def serve(
|
|
|
446
520
|
req_mode = str(mode or "")
|
|
447
521
|
driver = driver_factory() if driver_factory is not None else default_driver(req)
|
|
448
522
|
driver_name = str(getattr(driver, "name", "") or "")
|
|
523
|
+
if mode in ("replay", "explore", "record"):
|
|
524
|
+
screen = _start_screen(req, events, out, screen_factory)
|
|
449
525
|
if mode == "replay":
|
|
450
526
|
result = run_replay(req, events, driver, stop, model_factory)
|
|
451
527
|
elif mode == "explore":
|
|
@@ -456,6 +532,12 @@ def serve(
|
|
|
456
532
|
raise WorkflowError(f"mode must be replay, explore or record, not {mode!r}")
|
|
457
533
|
except Exception as e:
|
|
458
534
|
result = {"ok": False, "error": f"{type(e).__name__}: {e}" if not isinstance(e, (WorkflowError, ValueError)) else str(e)}
|
|
535
|
+
if screen is not None:
|
|
536
|
+
# Finished before run.json is written, so the report finds it (video.mp4 beside run.json).
|
|
537
|
+
if screen.close():
|
|
538
|
+
result["video"] = VIDEO_FILE
|
|
539
|
+
else:
|
|
540
|
+
events.log(f"No video of this run: {screen.error or 'nothing was recorded'}", "warn")
|
|
459
541
|
result.setdefault("format", FORMAT)
|
|
460
542
|
if driver_name and result.get("mode", req_mode) == "replay":
|
|
461
543
|
result.setdefault("driver", driver_name)
|
|
@@ -291,6 +291,9 @@ def install() -> None:
|
|
|
291
291
|
from browser_use.browser.watchdogs.aboutblank_watchdog import AboutBlankWatchdog
|
|
292
292
|
except ImportError:
|
|
293
293
|
return
|
|
294
|
+
from .browser import take_edge_new_tab
|
|
295
|
+
|
|
296
|
+
take_edge_new_tab()
|
|
294
297
|
|
|
295
298
|
async def start_page(self: Any, target_id: Any, *args: Any, **kwargs: Any) -> None:
|
|
296
299
|
overlay = _OVERLAYS.get(id(self.browser_session))
|
|
@@ -366,6 +366,34 @@ def install_patient_start() -> None:
|
|
|
366
366
|
|
|
367
367
|
if getattr(LocalBrowserWatchdog._wait_for_cdp_url, "__name__", "") != "wait_for_devtools":
|
|
368
368
|
LocalBrowserWatchdog._wait_for_cdp_url = staticmethod(wait_for_devtools)
|
|
369
|
+
take_edge_new_tab()
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
# Microsoft Edge's new tab page. Edge opens it in its first window, and the library takes only Chrome's for a blank tab:
|
|
373
|
+
# a run, a recording and the start page met Edge's news page (which the tab then loads) instead of a blank tab.
|
|
374
|
+
_EDGE_NEW_TAB = ("edge://newtab/", "edge://newtab")
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def take_edge_new_tab() -> None:
|
|
378
|
+
"""Have the library treat Edge's new tab page as Chrome's: turned into a blank tab when the browser starts."""
|
|
379
|
+
try:
|
|
380
|
+
import browser_use.utils as utils
|
|
381
|
+
except ImportError:
|
|
382
|
+
return
|
|
383
|
+
original = utils.is_new_tab_page
|
|
384
|
+
if getattr(original, "__forgeqe__", False):
|
|
385
|
+
return
|
|
386
|
+
|
|
387
|
+
def is_new_tab_page(url: str) -> bool:
|
|
388
|
+
return original(url) or url in _EDGE_NEW_TAB
|
|
389
|
+
|
|
390
|
+
is_new_tab_page.__forgeqe__ = True # type: ignore[attr-defined]
|
|
391
|
+
utils.is_new_tab_page = is_new_tab_page
|
|
392
|
+
# Modules that imported the check by name keep their own reference.
|
|
393
|
+
for name in ("browser_use.browser.session", "browser_use.agent.prompts", "browser_use.tools.registry.service"):
|
|
394
|
+
module = sys.modules.get(name)
|
|
395
|
+
if module is not None and getattr(module, "is_new_tab_page", None) is original:
|
|
396
|
+
module.is_new_tab_page = is_new_tab_page
|
|
369
397
|
|
|
370
398
|
|
|
371
399
|
def find_playwright_chromium() -> Optional[str]:
|
|
@@ -771,7 +799,7 @@ def remote_debugging_policy() -> Optional[str]:
|
|
|
771
799
|
if sys.platform == "win32":
|
|
772
800
|
for key in _CHROME_POLICY_KEYS:
|
|
773
801
|
try:
|
|
774
|
-
r = subprocess.run(["reg", "query", key, "/v", "RemoteDebuggingAllowed"], capture_output=True, text=True, timeout=10)
|
|
802
|
+
r = subprocess.run(["reg", "query", key, "/v", "RemoteDebuggingAllowed"], capture_output=True, text=True, errors="replace", timeout=10)
|
|
775
803
|
except Exception:
|
|
776
804
|
continue
|
|
777
805
|
for line in (r.stdout or "").splitlines():
|
|
@@ -1138,22 +1166,34 @@ def _end_browsers(seen: Dict[int, List[str]], *, grace: float = 5.0) -> int:
|
|
|
1138
1166
|
return 0
|
|
1139
1167
|
import psutil
|
|
1140
1168
|
|
|
1141
|
-
|
|
1169
|
+
found: Dict[int, Any] = {}
|
|
1170
|
+
left: Dict[int, Any] = {}
|
|
1142
1171
|
for pid, args in seen.items():
|
|
1143
1172
|
try:
|
|
1144
1173
|
p = psutil.Process(pid)
|
|
1145
1174
|
if p.cmdline() != args:
|
|
1146
1175
|
continue
|
|
1147
|
-
|
|
1176
|
+
found[pid] = p
|
|
1177
|
+
for q in [p, *p.children(recursive=True)]:
|
|
1178
|
+
left.setdefault(q.pid, q)
|
|
1148
1179
|
except (psutil.Error, OSError):
|
|
1149
1180
|
continue
|
|
1150
1181
|
if not left:
|
|
1151
1182
|
return 0
|
|
1152
|
-
|
|
1153
|
-
|
|
1183
|
+
|
|
1184
|
+
def _under_another(p: Any) -> bool:
|
|
1185
|
+
# A launcher that starts the browser again with the same arguments (on Windows, a Python venv's python.exe
|
|
1186
|
+
# does too) leaves one browser, not two.
|
|
1187
|
+
try:
|
|
1188
|
+
return any(a.pid in found for a in p.parents())
|
|
1189
|
+
except (psutil.Error, OSError):
|
|
1190
|
+
return False
|
|
1191
|
+
|
|
1192
|
+
browsers = sum(1 for p in found.values() if not _under_another(p))
|
|
1193
|
+
for p in left.values():
|
|
1154
1194
|
with contextlib.suppress(psutil.Error, OSError):
|
|
1155
1195
|
p.terminate()
|
|
1156
|
-
_, alive = psutil.wait_procs(left, timeout=grace)
|
|
1196
|
+
_, alive = psutil.wait_procs(list(left.values()), timeout=grace)
|
|
1157
1197
|
for p in alive:
|
|
1158
1198
|
with contextlib.suppress(psutil.Error, OSError):
|
|
1159
1199
|
p.kill()
|
package/py/forgeqe_engine/cli.py
CHANGED
|
@@ -14,7 +14,8 @@ Engine process protocol, used by the Bun CLI:
|
|
|
14
14
|
python -m forgeqe_engine doctor
|
|
15
15
|
python -m forgeqe_engine token (stdin: an llms.json profile with auth: entra; prints {token, expires_on})
|
|
16
16
|
python -m forgeqe_engine probe (stdin: an llms.json profile; prints {ok, ms, structured, vision, error?})
|
|
17
|
-
python -m forgeqe_engine
|
|
17
|
+
python -m forgeqe_engine video <frames> <file.mp4> (a replay's kept frames as a video; see video.py)
|
|
18
|
+
python -m forgeqe_engine copilot-gateway (GitHub Copilot as an OpenAI-style endpoint on 127.0.0.1; see copilot_gateway.py)
|
|
18
19
|
"""
|
|
19
20
|
from __future__ import annotations
|
|
20
21
|
|
|
@@ -90,6 +91,10 @@ def _doctor(out: TextIO) -> int:
|
|
|
90
91
|
info["video"] = version("imageio")
|
|
91
92
|
except Exception:
|
|
92
93
|
pass
|
|
94
|
+
try:
|
|
95
|
+
info["ffmpeg"] = version("imageio-ffmpeg")
|
|
96
|
+
except Exception:
|
|
97
|
+
pass
|
|
93
98
|
try:
|
|
94
99
|
from .service import local_browser_launch_kwargs
|
|
95
100
|
|
|
@@ -338,6 +343,10 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
338
343
|
return _probe(out)
|
|
339
344
|
if cmd == "suggest":
|
|
340
345
|
return _suggest(out)
|
|
346
|
+
if cmd == "video":
|
|
347
|
+
from .video import main as video_main
|
|
348
|
+
|
|
349
|
+
return video_main(args[1:], out)
|
|
341
350
|
if cmd == "copilot-gateway":
|
|
342
351
|
from .copilot_gateway import main as copilot_gateway
|
|
343
352
|
|
|
@@ -13,7 +13,7 @@ reply from the browser would wait forever. One worker takes the queue in order a
|
|
|
13
13
|
|
|
14
14
|
Request (stdin line 1): ``start_url``, ``out_dir``, ``name``, ``logins``, ``signed_in`` (start with the saved
|
|
15
15
|
sessions), ``llm`` (for checks described in words; optional), ``leader`` ({code, ctrl, shift, alt, meta}),
|
|
16
|
-
``max_seconds``, ``case`` (a test case being recorded: {id, title, steps: [{action, expected}]}). Later stdin lines are commands, as the Recorder panel sends them ({"cmd": "stop"}, "chat", "undo"...).
|
|
16
|
+
``max_seconds``, ``video`` (true: video.mp4 of the tab being recorded, paused with the recording), ``case`` (a test case being recorded: {id, title, steps: [{action, expected}]}). Later stdin lines are commands, as the Recorder panel sends them ({"cmd": "stop"}, "chat", "undo"...).
|
|
17
17
|
Events: ``log``, ``steps`` (the whole list, after each change), ``call`` (one model call's time and tokens), ``done``.
|
|
18
18
|
"""
|
|
19
19
|
from __future__ import annotations
|
|
@@ -35,6 +35,11 @@ from . import dynamic
|
|
|
35
35
|
from .webrecord import Target, WebRecorder, auto_name, describe, upload_path
|
|
36
36
|
from .webrecord_page import recorder_js
|
|
37
37
|
|
|
38
|
+
|
|
39
|
+
def _utc_now() -> str:
|
|
40
|
+
"""Now, as an ISO time in UTC with a Z."""
|
|
41
|
+
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
42
|
+
|
|
38
43
|
logger = logging.getLogger("forgeqe_engine.record")
|
|
39
44
|
|
|
40
45
|
Emit = Callable[[Dict[str, Any]], None]
|
|
@@ -44,6 +49,8 @@ CDP_TIMEOUT = 5.0
|
|
|
44
49
|
SHOT_SETTLE = 0.7
|
|
45
50
|
MAX_SHOTS = 400
|
|
46
51
|
SHOT_QUALITY = 55
|
|
52
|
+
# The tester's tab as a video (browser.video): the page's own screencast, on the recorder's connection (video.py).
|
|
53
|
+
VIDEO_SCREENCAST = {"format": "jpeg", "quality": 60, "maxWidth": 1920, "maxHeight": 1200, "everyNthFrame": 1}
|
|
47
54
|
|
|
48
55
|
# What the page shows after a step, for the review to suggest checks from and to pick an element on the screenshot:
|
|
49
56
|
# the address and title, the visible text (a leaf's own words, with its box) and the fields with their values, in the
|
|
@@ -116,6 +123,8 @@ class RecordSession:
|
|
|
116
123
|
self.pages: Dict[str, Dict[str, Any]] = {}
|
|
117
124
|
self.active: Optional[str] = None
|
|
118
125
|
self.stop_reason = ""
|
|
126
|
+
# When the tester started and stopped, for how long the recording took (the Record page's Duration).
|
|
127
|
+
self.started_at = ""
|
|
119
128
|
self.paused = False
|
|
120
129
|
self.note_next = False
|
|
121
130
|
# Where the tester put the panel, and whether they made it small: kept across pages.
|
|
@@ -139,6 +148,9 @@ class RecordSession:
|
|
|
139
148
|
# The page's own API calls after each step (method, path, status), for checks of them in the review.
|
|
140
149
|
self.calls: Dict[int, List[Dict[str, Any]]] = {}
|
|
141
150
|
self._requests: Dict[str, str] = {}
|
|
151
|
+
# video.mp4 of the tab being recorded (payload ``video``), following the tester from tab to tab; paused with them.
|
|
152
|
+
self.video: Any = None
|
|
153
|
+
self._video_sid: Optional[str] = None
|
|
142
154
|
|
|
143
155
|
# -- the browser ----------------------------------------------------------------------------------------------
|
|
144
156
|
|
|
@@ -219,6 +231,7 @@ class RecordSession:
|
|
|
219
231
|
await self.send("Page.navigate", {"url": self.start_url}, main)
|
|
220
232
|
# The start page's picture, once it has loaded.
|
|
221
233
|
self._schedule_shot(2.0)
|
|
234
|
+
await self._start_video()
|
|
222
235
|
# Where ForgeQE reaches this browser (on this computer only), to play a block of steps first: never shown.
|
|
223
236
|
if str(getattr(self.browser, "cdp_url", "") or "").startswith(("http://127.0.0.1:", "ws://127.0.0.1:", "http://localhost:", "ws://localhost:")):
|
|
224
237
|
self.emit({"type": "browser", "cdp": self.browser.cdp_url})
|
|
@@ -226,6 +239,7 @@ class RecordSession:
|
|
|
226
239
|
async def close(self) -> None:
|
|
227
240
|
from .browser import _shutdown_browser_instance
|
|
228
241
|
|
|
242
|
+
await self._finish_video()
|
|
229
243
|
if self.client is not None:
|
|
230
244
|
try:
|
|
231
245
|
await self.client.stop()
|
|
@@ -236,6 +250,7 @@ class RecordSession:
|
|
|
236
250
|
# -- the loop -------------------------------------------------------------------------------------------------
|
|
237
251
|
|
|
238
252
|
async def run(self, max_seconds: float) -> None:
|
|
253
|
+
self.started_at = self.started_at or _utc_now()
|
|
239
254
|
deadline = time.monotonic() + max_seconds
|
|
240
255
|
while not self.stop_reason:
|
|
241
256
|
left = deadline - time.monotonic()
|
|
@@ -303,6 +318,7 @@ class RecordSession:
|
|
|
303
318
|
except Exception as ex:
|
|
304
319
|
logger.warning("record: %s not handled: %s", kind, ex)
|
|
305
320
|
logger.debug("record: details", exc_info=True)
|
|
321
|
+
await self._follow_video()
|
|
306
322
|
|
|
307
323
|
def _response(self, event: Dict[str, Any], sid: Optional[str]) -> None:
|
|
308
324
|
method = self._requests.pop(str(event.get("requestId") or ""), None)
|
|
@@ -634,6 +650,9 @@ class RecordSession:
|
|
|
634
650
|
if cmd == "pause":
|
|
635
651
|
self.paused = not self.paused
|
|
636
652
|
rec.paused = self.paused
|
|
653
|
+
# Paused, nothing is recorded: the video too (the time paused is not in it).
|
|
654
|
+
if self.video is not None:
|
|
655
|
+
self.video.hold(self.paused)
|
|
637
656
|
msg = "paused: what you do now is not recorded" if self.paused else "recording again"
|
|
638
657
|
elif cmd == "undo":
|
|
639
658
|
msg = rec.undo()
|
|
@@ -907,6 +926,73 @@ class RecordSession:
|
|
|
907
926
|
self.shot_at[len(rec.steps) - 1] = name
|
|
908
927
|
return name
|
|
909
928
|
|
|
929
|
+
# -- the video -------------------------------------------------------------------------------------------------------
|
|
930
|
+
|
|
931
|
+
async def _start_video(self) -> None:
|
|
932
|
+
if self.payload.get("video") is not True or self.client is None:
|
|
933
|
+
return
|
|
934
|
+
from .video import VIDEO_FILE, FrameVideo
|
|
935
|
+
|
|
936
|
+
video = FrameVideo(self.out_dir / VIDEO_FILE)
|
|
937
|
+
if not video.start():
|
|
938
|
+
self.log(f"No video of this recording: {video.error}", "warn")
|
|
939
|
+
return
|
|
940
|
+
self.video = video
|
|
941
|
+
self.client.register.Page.screencastFrame(self._on_frame)
|
|
942
|
+
await self._follow_video()
|
|
943
|
+
|
|
944
|
+
def _on_frame(self, event: Any, session_id: Optional[str] = None) -> None:
|
|
945
|
+
"""A picture of the screencast: kept for the video, and acknowledged (later, never awaited here) so more come."""
|
|
946
|
+
ack = event.get("sessionId") if isinstance(event, dict) else None
|
|
947
|
+
if ack is not None and session_id:
|
|
948
|
+
try:
|
|
949
|
+
asyncio.ensure_future(self.send("Page.screencastFrameAck", {"sessionId": ack}, session_id))
|
|
950
|
+
except RuntimeError:
|
|
951
|
+
pass
|
|
952
|
+
video = self.video
|
|
953
|
+
if video is None or session_id != self._video_sid or self.paused:
|
|
954
|
+
return
|
|
955
|
+
data = event.get("data") if isinstance(event, dict) else None
|
|
956
|
+
if isinstance(data, str):
|
|
957
|
+
import base64
|
|
958
|
+
|
|
959
|
+
try:
|
|
960
|
+
video.frame(base64.b64decode(data, validate=True))
|
|
961
|
+
except ValueError:
|
|
962
|
+
pass
|
|
963
|
+
|
|
964
|
+
async def _follow_video(self) -> None:
|
|
965
|
+
"""The video shows the tab the tester is on: the screencast moves when they move."""
|
|
966
|
+
if self.video is None or self.active == self._video_sid:
|
|
967
|
+
return
|
|
968
|
+
old, self._video_sid = self._video_sid, self.active
|
|
969
|
+
if old and old in self.pages:
|
|
970
|
+
try:
|
|
971
|
+
await self.send("Page.stopScreencast", {}, old)
|
|
972
|
+
except Exception:
|
|
973
|
+
pass
|
|
974
|
+
if self.active:
|
|
975
|
+
try:
|
|
976
|
+
await self.send("Page.startScreencast", dict(VIDEO_SCREENCAST), self.active)
|
|
977
|
+
except Exception as ex:
|
|
978
|
+
logger.debug("record: no screencast of the page: %s", ex)
|
|
979
|
+
|
|
980
|
+
async def _finish_video(self) -> Optional[str]:
|
|
981
|
+
video, self.video = self.video, None
|
|
982
|
+
if video is None:
|
|
983
|
+
return None
|
|
984
|
+
sid, self._video_sid = self._video_sid, None
|
|
985
|
+
if sid and sid in self.pages:
|
|
986
|
+
try:
|
|
987
|
+
await self.send("Page.stopScreencast", {}, sid)
|
|
988
|
+
except Exception:
|
|
989
|
+
pass
|
|
990
|
+
path = await asyncio.get_running_loop().run_in_executor(None, video.close)
|
|
991
|
+
if path is None:
|
|
992
|
+
self.log(f"No video of this recording: {video.error or 'nothing was shown'}", "warn")
|
|
993
|
+
return None
|
|
994
|
+
return str(path.resolve())
|
|
995
|
+
|
|
910
996
|
# -- the run folder -------------------------------------------------------------------------------------------------
|
|
911
997
|
|
|
912
998
|
async def finish(self) -> Dict[str, Any]:
|
|
@@ -916,6 +1002,7 @@ class RecordSession:
|
|
|
916
1002
|
rec = self.rec
|
|
917
1003
|
assert rec is not None
|
|
918
1004
|
self.out_dir.mkdir(parents=True, exist_ok=True)
|
|
1005
|
+
video = await self._finish_video()
|
|
919
1006
|
# The recorder's own working fields (an element's facts) stay out of the run.
|
|
920
1007
|
steps = [
|
|
921
1008
|
{**{k: v for k, v in s.items() if not k.startswith("_")}, **({"shot": self.shot_at[i]} if i in self.shot_at else {}), **({"calls": self.calls[i]} if self.calls.get(i) else {})}
|
|
@@ -949,6 +1036,7 @@ class RecordSession:
|
|
|
949
1036
|
"usage": dict(self.usage),
|
|
950
1037
|
"outcome": "passed" if ok else "error",
|
|
951
1038
|
"browser": profile,
|
|
1039
|
+
**({"started_at": self.started_at, "ended_at": _utc_now()} if self.started_at else {}),
|
|
952
1040
|
"recording": {
|
|
953
1041
|
"stopped": self.stop_reason,
|
|
954
1042
|
"checks": rec.checks,
|
|
@@ -963,7 +1051,9 @@ class RecordSession:
|
|
|
963
1051
|
}
|
|
964
1052
|
if not ok:
|
|
965
1053
|
run["error"] = summary
|
|
966
|
-
files = [str((self.out_dir / "run.json").resolve()), *([yaml_path] if yaml_path else []), str((self.out_dir / "trace.md").resolve())]
|
|
1054
|
+
files = [str((self.out_dir / "run.json").resolve()), *([yaml_path] if yaml_path else []), str((self.out_dir / "trace.md").resolve()), *([video] if video else [])]
|
|
1055
|
+
if video:
|
|
1056
|
+
run["video"] = Path(video).name
|
|
967
1057
|
run["files"] = files
|
|
968
1058
|
(self.out_dir / "run.json").write_text(json.dumps(run, indent=2, ensure_ascii=False, default=str), encoding="utf-8")
|
|
969
1059
|
return run
|