@capagents/forgeqe 2.8.9 → 2.9.1
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 +250 -22
- package/dist/docs-site/docs/desktop/index.html +45 -1
- package/dist/docs-site/docs/index.html +335 -4
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/forgeqe.js +2077 -2022
- package/dist/template.html +66 -66
- package/dist/web/THIRD_PARTY_NOTICES.md +455 -0
- package/dist/web/assets/Agent-BNWcLTrm.js +4 -0
- package/dist/web/assets/ApiTests-CZFzjMKc.js +10 -0
- package/dist/web/assets/Browse-CeiK4X_V.js +2 -0
- package/dist/web/assets/Chat-BqXSNxV2.js +3 -0
- package/dist/web/assets/CommandPalette-VSEzjRS1.js +1 -0
- package/dist/web/assets/Compare-Bjh-qB8C.js +1 -0
- package/dist/web/assets/Cost-BRtni21m.js +1 -0
- package/dist/web/assets/Data-Bzn351xU.js +6 -0
- package/dist/web/assets/Evidence-eM1ZsFF-.js +1 -0
- package/dist/web/assets/Explore-D07Qbzyq.js +2 -0
- package/dist/web/assets/Features-DFwuL5cN.js +1 -0
- package/dist/web/assets/Flags-pxSAu21R.js +2 -0
- package/dist/web/assets/Flaky-BdfqCR6j.js +1 -0
- package/dist/web/assets/ForceGraph-DC7NzeR4.js +1 -0
- package/dist/web/assets/Impact-CfnvrPzq.js +3 -0
- package/dist/web/assets/Jobs-CIKpgvcv.js +5 -0
- package/dist/web/assets/KindPage-OyYE9NU7.js +6 -0
- package/dist/web/assets/Migration-BQA6MOPN.js +2 -0
- package/dist/web/assets/Product-DNe8RV_H.js +7 -0
- package/dist/web/assets/Production-ClEiFS1u.js +1 -0
- package/dist/web/assets/Quality-BZnQcbb2.js +1 -0
- package/dist/web/assets/Readiness-Dk2KZZm4.js +1 -0
- package/dist/web/assets/Record-CSapdwkr.js +2 -0
- package/dist/web/assets/Regression-C7bZ5sSE.js +5 -0
- package/dist/web/assets/Reports-BWtgbiVp.js +2 -0
- package/dist/web/assets/Response-DyvlQXek.js +4 -0
- package/dist/web/assets/RunDiff-DWV5qdHx.js +1 -0
- package/dist/web/assets/Runs-CET6zwQu.js +2 -0
- package/dist/web/assets/Steps-DUG1BKJb.js +2 -0
- package/dist/web/assets/TestCases-DyicRSqL.js +1 -0
- package/dist/web/assets/TestData-D2aWG3dq.js +2 -0
- package/dist/web/assets/TestDebt-DobUiGTz.js +1 -0
- package/dist/web/assets/Tosca-DvTni6va.js +3 -0
- package/dist/web/assets/WhatsNew-B3xewvk5.js +1 -0
- package/dist/web/assets/dataParts-rU9wRwfo.js +3 -0
- package/dist/web/assets/families-DWrv-fcS.js +1 -0
- package/dist/web/assets/filters-BDJYWuRV.js +1 -0
- package/dist/web/assets/fold-BgITvJex.js +1 -0
- package/dist/web/assets/frame-Dn34zQXO.js +4 -0
- package/dist/web/assets/index-BiMUTOBo.js +45 -0
- package/dist/web/assets/index-CGfii-zv.css +2 -0
- package/dist/web/assets/line-icons-CQ-3V8ax.js +1 -0
- package/dist/web/assets/logos-C067hMmF.js +1 -0
- package/dist/web/assets/palette-Br50dJuQ.js +1 -0
- package/dist/web/assets/parts-CbA0h_uO.js +1 -0
- package/dist/web/assets/productParts-BxQnjrHo.js +1 -0
- package/dist/web/assets/qualityParts-Cn74cNyX.js +1 -0
- package/dist/web/assets/rows-X8lfgK8j.js +1 -0
- package/dist/web/assets/segmented-mcjXGwLg.js +1 -0
- package/dist/web/assets/thread-Bamx8xqR.js +5 -0
- package/dist/web/assets/usePageChat-B-vpiXQ6.js +1 -0
- package/dist/web/index.html +5 -3
- package/docs/DESKTOP.md +48 -1
- package/docs/user-guide.html +335 -4
- package/evals/evidence/build/README.md +20 -0
- package/evals/evidence/build/base/package.json +1 -0
- package/evals/evidence/build/base/src/index.ts +1 -0
- package/evals/evidence/build/base/src/pricing.ts +22 -0
- package/evals/evidence/build/base/tests/discount.test.ts +6 -0
- package/evals/evidence/build/base/tests/legacy.test.ts +7 -0
- package/evals/evidence/build/base/tests/pricing.test.ts +10 -0
- package/evals/evidence/build/cases/build-broken/after/src/pricing.ts +22 -0
- package/evals/evidence/build/cases/build-broken/case.json +13 -0
- package/evals/evidence/build/cases/fixes-legacy/after/src/pricing.ts +22 -0
- package/evals/evidence/build/cases/fixes-legacy/case.json +11 -0
- package/evals/evidence/build/cases/flaky-test/after/tests/flaky.test.ts +11 -0
- package/evals/evidence/build/cases/flaky-test/case.json +11 -0
- package/evals/evidence/build/cases/good-feature/after/src/index.ts +1 -0
- package/evals/evidence/build/cases/good-feature/after/src/pricing.ts +28 -0
- package/evals/evidence/build/cases/good-feature/after/tests/bulk.test.ts +7 -0
- package/evals/evidence/build/cases/good-feature/case.json +17 -0
- package/evals/evidence/build/cases/new-test-fails/after/src/index.ts +1 -0
- package/evals/evidence/build/cases/new-test-fails/after/src/pricing.ts +27 -0
- package/evals/evidence/build/cases/new-test-fails/after/tests/coupon.test.ts +6 -0
- package/evals/evidence/build/cases/new-test-fails/case.json +19 -0
- package/evals/evidence/build/cases/regression/after/src/pricing.ts +23 -0
- package/evals/evidence/build/cases/regression/case.json +13 -0
- package/evals/evidence/build/cases/test-removed/case.json +14 -0
- package/forgeqe.example.yaml +2 -0
- package/package.json +2 -1
- package/prompts/README.md +1 -0
- package/prompts/impact-reader.md +8 -9
- package/prompts/tosca-assistant.md +47 -0
- package/prompts/tosca.md +3 -1
- package/py/forgeqe_desktop/agentdesktop_driver.py +57 -7
- package/py/forgeqe_desktop/handhooks.py +71 -22
- package/py/forgeqe_desktop/handrecord.py +7 -1
- package/py/forgeqe_desktop/heal.py +24 -2
- package/py/forgeqe_desktop/memory.py +54 -4
- package/py/forgeqe_desktop/pywinauto_driver.py +210 -12
- package/py/forgeqe_desktop/replay.py +10 -2
- package/py/forgeqe_desktop/service.py +9 -2
- package/py/forgeqe_desktop/ufo_runner.py +101 -1
- package/py/forgeqe_engine/browser.py +309 -31
- package/py/forgeqe_engine/browserdoctor.py +255 -0
- package/py/forgeqe_engine/browserlaunch.py +271 -0
- package/py/forgeqe_engine/capture.py +20 -4
- package/py/forgeqe_engine/cli.py +26 -0
- package/py/forgeqe_engine/logins.py +1 -1
- package/py/forgeqe_engine/pwlaunch.mjs +61 -0
- package/py/forgeqe_engine/recordsession.py +1 -1
- package/py/forgeqe_engine/service.py +1 -1
- package/py/forgeqe_mobile/service.py +4 -1
- package/py/forgeqe_tosca/__init__.py +11 -1
- package/py/forgeqe_tosca/app.py +168 -0
- package/py/forgeqe_tosca/db.py +131 -0
- package/py/forgeqe_tosca/files.py +74 -0
- package/py/forgeqe_tosca/ntir.py +357 -5
- package/py/forgeqe_tosca/render.py +38 -0
- package/py/forgeqe_tosca/tsu.py +110 -0
- package/skills/tosca-knowledge/SKILL.md +14 -3
- package/skills/tosca-knowledge/references/api.md +54 -0
- package/dist/web/assets/Agent-CHliM9aG.js +0 -4
- package/dist/web/assets/ApiTests-DcGDtIjl.js +0 -10
- package/dist/web/assets/Browse-DWZgEdaB.js +0 -1
- package/dist/web/assets/Chat-DVolc6Rs.js +0 -3
- package/dist/web/assets/CommandPalette-CdwjRIsa.js +0 -1
- package/dist/web/assets/Cost-BifpK_Ac.js +0 -1
- package/dist/web/assets/Data-Crk0ef8O.js +0 -6
- package/dist/web/assets/Evidence-EYGofupD.js +0 -1
- package/dist/web/assets/Explore-DtqBRQi7.js +0 -2
- package/dist/web/assets/Features-B_ZtQEtR.js +0 -1
- package/dist/web/assets/Flags-DCLSg8Na.js +0 -2
- package/dist/web/assets/Flaky-HpgrkJIF.js +0 -1
- package/dist/web/assets/ForceGraph-Dm4VEUjO.js +0 -1
- package/dist/web/assets/Impact-CyzbgGih.js +0 -3
- package/dist/web/assets/Jobs-CbTd9csb.js +0 -5
- package/dist/web/assets/KindPage-cfP76U_9.js +0 -6
- package/dist/web/assets/Migration-va16JqtB.js +0 -2
- package/dist/web/assets/Product-D0iY6orX.js +0 -7
- package/dist/web/assets/Production-CBUb6wZJ.js +0 -1
- package/dist/web/assets/Quality-OMhrUKTU.js +0 -1
- package/dist/web/assets/Readiness-B64Rxahv.js +0 -1
- package/dist/web/assets/Record-B_JXq6Dv.js +0 -2
- package/dist/web/assets/Regression-2blJAX7v.js +0 -5
- package/dist/web/assets/Reports-DCgjGdw4.js +0 -2
- package/dist/web/assets/Response-BtMM8nqx.js +0 -4
- package/dist/web/assets/RunDiff-KuUVRuQI.js +0 -1
- package/dist/web/assets/Runs-zHDZ-rSo.js +0 -2
- package/dist/web/assets/TestCases-B1j2Oelt.js +0 -1
- package/dist/web/assets/TestData-CZSynoi-.js +0 -2
- package/dist/web/assets/TestDebt-DEdIBwdb.js +0 -1
- package/dist/web/assets/Tosca-BcuaHsQC.js +0 -2
- package/dist/web/assets/WhatsNew-CjvX6DNo.js +0 -1
- package/dist/web/assets/dataParts-BImZKYEu.js +0 -3
- package/dist/web/assets/families-q4nF1Fqo.js +0 -1
- package/dist/web/assets/frame-eAHxqKfn.js +0 -4
- package/dist/web/assets/index-COTk3Bz-.js +0 -45
- package/dist/web/assets/index-DvuGI8X3.css +0 -2
- package/dist/web/assets/logos-DEPdha9g.js +0 -1
- package/dist/web/assets/parts-CVdJRIxI.js +0 -1
- package/dist/web/assets/productParts-CqY4Zs7J.js +0 -1
- package/dist/web/assets/qualityParts-BcrXEQ9B.js +0 -1
- package/dist/web/assets/segmented-BJECij_J.js +0 -1
- package/dist/web/assets/thread-Cuvu0HhP.js +0 -5
- package/dist/web/assets/usePageChat-Bz7fuynu.js +0 -1
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
|
+
import atexit
|
|
6
7
|
import contextlib
|
|
7
8
|
import json
|
|
8
9
|
import logging
|
|
@@ -142,6 +143,9 @@ def local_browser_launch_kwargs(*, headless: bool) -> Dict[str, Any]:
|
|
|
142
143
|
"headless": headless,
|
|
143
144
|
"channel": channel,
|
|
144
145
|
"ignore_default_args": list(_UNSUPPORTED_BROWSER_USE_ARGS),
|
|
146
|
+
# The page as its users see it: the library would otherwise load an ad blocker, a cookie banner remover and a
|
|
147
|
+
# URL cleaner (downloaded on first use), so a recorded flow would skip the banner a test then meets.
|
|
148
|
+
"enable_default_extensions": False,
|
|
145
149
|
}
|
|
146
150
|
exe = resolve_chrome_executable_path(channel)
|
|
147
151
|
edge = None if exe or channel not in ("chrome", "msedge") else find_edge_executable()
|
|
@@ -162,8 +166,11 @@ _EARLY_EXIT = ("exited before CDP", "before CDP became available", "Browser proc
|
|
|
162
166
|
# How long one browser's DevTools port has to answer before the next browser is tried. Company PCs are slow to start a
|
|
163
167
|
# browser (security software scans it first); FORGEQE_ENGINE_BROWSER_START_SECONDS changes it, from 15 to 600.
|
|
164
168
|
DEVTOOLS_WAIT_SECONDS = 90.0
|
|
165
|
-
# After the process ForgeQE started has exited, how long a browser it handed over to has to
|
|
166
|
-
|
|
169
|
+
# After the process ForgeQE started has exited, how long a browser it handed over to has to take its port: a launcher
|
|
170
|
+
# that starts the browser again does so within a few seconds. A process that exited with an error code crashed instead,
|
|
171
|
+
# and gets CRASH_SECONDS.
|
|
172
|
+
HANDOVER_SECONDS = 15.0
|
|
173
|
+
CRASH_SECONDS = 3.0
|
|
167
174
|
|
|
168
175
|
|
|
169
176
|
def devtools_wait_seconds() -> float:
|
|
@@ -260,7 +267,11 @@ async def wait_for_devtools(port: int, timeout: float = 30, process: Any = None)
|
|
|
260
267
|
started = loop.time()
|
|
261
268
|
limit = max(float(timeout or 0), devtools_wait_seconds())
|
|
262
269
|
pid = getattr(process, "pid", None)
|
|
263
|
-
|
|
270
|
+
first_args = _process_args(process) if process is not None else []
|
|
271
|
+
seen = _profile_of(first_args)
|
|
272
|
+
if seen:
|
|
273
|
+
_SEEN_PROFILES.add(seen)
|
|
274
|
+
start_logger.info("browser start: PID %s, %s", pid, describe_args(first_args) if process is not None else "(no process)")
|
|
264
275
|
start_logger.info("browser start: waiting up to %ds for DevTools on 127.0.0.1:%d", int(limit), port)
|
|
265
276
|
exited_at: Optional[float] = None
|
|
266
277
|
exit_code = "not known"
|
|
@@ -308,10 +319,11 @@ async def wait_for_devtools(port: int, timeout: float = 30, process: Any = None)
|
|
|
308
319
|
if owner is not None:
|
|
309
320
|
_handed_over(owner)
|
|
310
321
|
start_logger.warning("browser start: PID %s now runs the browser with DevTools port %d (%s); still waiting for it", owner.pid, port, describe_args(_process_args(owner)))
|
|
311
|
-
|
|
322
|
+
grace = HANDOVER_SECONDS if exit_code.split(" ")[0] in ("0", "not") else CRASH_SECONDS
|
|
323
|
+
if exited_at is not None and owner is None and waited - exited_at >= grace:
|
|
312
324
|
raise RuntimeError(
|
|
313
325
|
f"Browser process (PID {pid}) exited before CDP became available on port {port}. It exited after "
|
|
314
|
-
f"{exited_at:.1f}s with exit code {exit_code}, and no other browser took its port in {int(
|
|
326
|
+
f"{exited_at:.1f}s with exit code {exit_code}, and no other browser took its port in {int(grace)}s ({last})."
|
|
315
327
|
)
|
|
316
328
|
if owner is not None and not _alive(owner) and exited_at is not None:
|
|
317
329
|
raise RuntimeError(
|
|
@@ -332,10 +344,26 @@ async def wait_for_devtools(port: int, timeout: float = 30, process: Any = None)
|
|
|
332
344
|
await asyncio.sleep(0.25)
|
|
333
345
|
|
|
334
346
|
|
|
347
|
+
# The library's own time limits on starting a browser (30s each by default), read when each start begins.
|
|
348
|
+
_LIBRARY_START_LIMITS = ("TIMEOUT_BrowserStartEvent", "TIMEOUT_BrowserLaunchEvent")
|
|
349
|
+
|
|
350
|
+
|
|
335
351
|
def install_patient_start() -> None:
|
|
336
|
-
"""
|
|
352
|
+
"""
|
|
353
|
+
Use `wait_for_devtools` for every local browser the library starts, and give the library's own start steps as long:
|
|
354
|
+
their 30s limit would cut the patient wait (and a launcher's handover) short.
|
|
355
|
+
"""
|
|
337
356
|
from browser_use.browser.watchdogs.local_browser_watchdog import LocalBrowserWatchdog
|
|
338
357
|
|
|
358
|
+
needed = devtools_wait_seconds() + HANDOVER_SECONDS + 15
|
|
359
|
+
for name in _LIBRARY_START_LIMITS:
|
|
360
|
+
try:
|
|
361
|
+
current = float(os.environ.get(name) or 0)
|
|
362
|
+
except ValueError:
|
|
363
|
+
current = 0
|
|
364
|
+
if current < needed:
|
|
365
|
+
os.environ[name] = str(int(needed))
|
|
366
|
+
|
|
339
367
|
if getattr(LocalBrowserWatchdog._wait_for_cdp_url, "__name__", "") != "wait_for_devtools":
|
|
340
368
|
LocalBrowserWatchdog._wait_for_cdp_url = staticmethod(wait_for_devtools)
|
|
341
369
|
|
|
@@ -383,13 +411,8 @@ def local_browser_choice(value: Any) -> str:
|
|
|
383
411
|
return v if v in LOCAL_BROWSERS else "auto"
|
|
384
412
|
|
|
385
413
|
|
|
386
|
-
def
|
|
387
|
-
"""
|
|
388
|
-
The local browsers to try, in order. With browser.local_browser auto: the one `local_browser_launch_kwargs` picks
|
|
389
|
-
(installed Chrome by default), then Microsoft Edge, then Playwright's Chromium; the same browser is never listed
|
|
390
|
-
twice. chrome, edge or chromium: that browser only. A browser named with BROWSER_USE_EXECUTABLE_PATH wins over the
|
|
391
|
-
setting, and it or BROWSER_USE_FALLBACK=0 means that one only. Each is a full set of launch kwargs.
|
|
392
|
-
"""
|
|
414
|
+
def _browsers(*, headless: bool, choice: Any) -> List[Dict[str, Any]]:
|
|
415
|
+
"""The local browsers browser.local_browser names, in order, as launch kwargs (see `local_launch_candidates`)."""
|
|
393
416
|
first = local_browser_launch_kwargs(headless=headless)
|
|
394
417
|
pinned = bool((os.getenv("BROWSER_USE_EXECUTABLE_PATH") or "").strip()) and first.get("executable_path")
|
|
395
418
|
if pinned:
|
|
@@ -420,15 +443,85 @@ def local_launch_candidates(*, headless: bool, choice: Any = "auto") -> List[Dic
|
|
|
420
443
|
return out
|
|
421
444
|
|
|
422
445
|
|
|
446
|
+
def local_launch_candidates(*, headless: bool, choice: Any = "auto", method: Any = "auto", port: Any = None) -> List[Dict[str, Any]]:
|
|
447
|
+
"""
|
|
448
|
+
The local browsers to try, in order, as launch kwargs with how each is started in `_via`.
|
|
449
|
+
|
|
450
|
+
Which browsers (browser.local_browser): auto is the one `local_browser_launch_kwargs` picks (installed Chrome by
|
|
451
|
+
default), then Microsoft Edge, then Playwright's Chromium, the same browser never twice; chrome, edge or chromium is
|
|
452
|
+
that one only. A browser named with BROWSER_USE_EXECUTABLE_PATH wins over the setting, and it or
|
|
453
|
+
BROWSER_USE_FALLBACK=0 means that one only.
|
|
454
|
+
|
|
455
|
+
How (browser.launch): direct (the library starts it), playwright (ForgeQE's Playwright starts it), auto (each
|
|
456
|
+
directly, then each through Playwright when ForgeQE's Playwright is here; the direct starts always first, and among
|
|
457
|
+
the Playwright starts the one that started last time on this computer first), or attach (the browser the person started on browser.attach_port, and nothing else).
|
|
458
|
+
"""
|
|
459
|
+
from .browserlaunch import attach_port, launch_method, playwright_runtime, remembered
|
|
460
|
+
|
|
461
|
+
how = launch_method(method)
|
|
462
|
+
if how == "attach":
|
|
463
|
+
p = attach_port(port)
|
|
464
|
+
if p is None:
|
|
465
|
+
raise RuntimeError(f"browser.launch is attach, but browser.attach_port is not a port from 1024 to 65535 ({str(port)[:40]!r}).")
|
|
466
|
+
return [{**local_browser_launch_kwargs(headless=headless), "_via": "attach", "_port": p}]
|
|
467
|
+
browsers = _browsers(headless=headless, choice=choice)
|
|
468
|
+
direct = [{**b, "_via": "direct"} for b in browsers]
|
|
469
|
+
# Playwright starts a browser by its path or as chrome/msedge; a Chromium without a path is the library's to find.
|
|
470
|
+
through = [{**b, "_via": "playwright"} for b in browsers if b.get("executable_path") or b.get("channel") in ("chrome", "msedge")]
|
|
471
|
+
if how == "direct":
|
|
472
|
+
return direct
|
|
473
|
+
if how == "playwright":
|
|
474
|
+
if playwright_runtime() is None:
|
|
475
|
+
raise RuntimeError("browser.launch is playwright, but ForgeQE's Playwright is not installed here (forgeqe setup installs it).")
|
|
476
|
+
if not through:
|
|
477
|
+
raise RuntimeError("browser.launch is playwright, but there is no browser it can start here.")
|
|
478
|
+
return through
|
|
479
|
+
if playwright_runtime() is None:
|
|
480
|
+
return direct
|
|
481
|
+
# The direct starts always come first, in their order. What started through Playwright last time on this computer
|
|
482
|
+
# only goes first among the Playwright starts.
|
|
483
|
+
last = remembered()
|
|
484
|
+
if last is not None and last[1] == "playwright":
|
|
485
|
+
first = next((c for c in through if browser_key(c) == last[0]), None)
|
|
486
|
+
if first is not None:
|
|
487
|
+
through = [first] + [c for c in through if c is not first]
|
|
488
|
+
return direct + through
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def browser_key(launch: Dict[str, Any]) -> str:
|
|
492
|
+
"""chrome, edge or chromium: which browser a launch starts, for remembering what started."""
|
|
493
|
+
if launch.get("channel") == "msedge":
|
|
494
|
+
return "edge"
|
|
495
|
+
if launch.get("channel") == "chromium":
|
|
496
|
+
return "chromium"
|
|
497
|
+
return "chrome"
|
|
498
|
+
|
|
499
|
+
|
|
423
500
|
def browser_name(launch: Dict[str, Any]) -> str:
|
|
501
|
+
"""The browser a launch starts, and how when not directly: "Microsoft Edge through Playwright"."""
|
|
502
|
+
if launch.get("_via") == "attach":
|
|
503
|
+
return f"the browser on port {launch.get('_port')}"
|
|
424
504
|
exe = str(launch.get("executable_path") or "")
|
|
425
505
|
if launch.get("channel") == "msedge":
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
506
|
+
name = "Microsoft Edge"
|
|
507
|
+
elif "ms-playwright" in exe.replace("\\", "/"):
|
|
508
|
+
name = "Playwright's Chromium"
|
|
509
|
+
elif launch.get("channel") == "chromium":
|
|
510
|
+
name = "Chromium"
|
|
511
|
+
else:
|
|
512
|
+
name = "Google Chrome"
|
|
513
|
+
return f"{name} through Playwright" if launch.get("_via") == "playwright" else name
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def library_kwargs(launch: Dict[str, Any]) -> Dict[str, Any]:
|
|
517
|
+
"""A launch's kwargs for the library: without ForgeQE's own keys (`_via`, `_port`)."""
|
|
518
|
+
return {k: v for k, v in launch.items() if not k.startswith("_")}
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _connect_kwargs(launch: Dict[str, Any], url: str, *, local: bool) -> Dict[str, Any]:
|
|
522
|
+
"""Kwargs that connect the library to a browser already running at url, instead of starting one."""
|
|
523
|
+
drop = ("channel", "executable_path", "ignore_default_args", "is_local")
|
|
524
|
+
return {**{k: v for k, v in library_kwargs(launch).items() if k not in drop}, "cdp_url": url, "is_local": local}
|
|
432
525
|
|
|
433
526
|
|
|
434
527
|
def can_fall_back(error: BaseException) -> bool:
|
|
@@ -449,6 +542,138 @@ async def _within(coro: Any, seconds: float) -> Any:
|
|
|
449
542
|
return await coro
|
|
450
543
|
|
|
451
544
|
|
|
545
|
+
# Temporary profile folders made for one browser start (by the library, or for Playwright): a name that starts so is
|
|
546
|
+
# never a person's own profile. A browser is found by its --user-data-dir's last part, which survives a launcher that
|
|
547
|
+
# starts the browser again with the same arguments.
|
|
548
|
+
_PROFILE_PREFIXES = ("browser-use-user-data-dir-", "browseruse-tmp-", "forgeqe-pw-")
|
|
549
|
+
# Profile folders of starts that failed: a browser still running on one was left behind, and is closed.
|
|
550
|
+
_FAILED_PROFILES: set = set()
|
|
551
|
+
# Profile folders seen on browsers being started (wait_for_devtools), for a start whose own process left too soon.
|
|
552
|
+
_SEEN_PROFILES: set = set()
|
|
553
|
+
# Late sweeps running, kept so they are not collected before they finish.
|
|
554
|
+
_SWEEPS: set = set()
|
|
555
|
+
# A browser a failed start left may only show up later (a launcher that is slow to start it again): looked for again.
|
|
556
|
+
LEFT_BROWSER_SWEEPS = (5.0, 15.0, 30.0, 60.0)
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def own_profile(path: Any) -> Optional[str]:
|
|
560
|
+
"""The last part of a temporary profile folder made for one start, else None (a person's own profile included)."""
|
|
561
|
+
name = os.path.basename(os.path.normpath(str(path or "").strip().strip('"')))
|
|
562
|
+
return name if any(name.startswith(p) and len(name) >= len(p) + 4 for p in _PROFILE_PREFIXES) else None
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _profile_of(args: List[str]) -> Optional[str]:
|
|
566
|
+
for a in args:
|
|
567
|
+
if a.startswith("--user-data-dir="):
|
|
568
|
+
return own_profile(a.split("=", 1)[1])
|
|
569
|
+
return None
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def browsers_on_profiles(names: set) -> Dict[int, List[str]]:
|
|
573
|
+
"""Browsers (main processes) running on one of these temporary profile folders, by pid with their command line."""
|
|
574
|
+
import psutil
|
|
575
|
+
|
|
576
|
+
found: Dict[int, List[str]] = {}
|
|
577
|
+
if not names:
|
|
578
|
+
return found
|
|
579
|
+
for proc in psutil.process_iter():
|
|
580
|
+
args = _process_args(proc)
|
|
581
|
+
if args and not any(a.startswith("--type=") for a in args) and _profile_of(args) in names:
|
|
582
|
+
found[proc.pid] = args
|
|
583
|
+
return found
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def end_left_browsers(names: Optional[set] = None) -> int:
|
|
587
|
+
"""Close the browsers running on the profile folders of failed starts (or `names`); returns how many."""
|
|
588
|
+
wanted = {n for n in (set(names) if names is not None else set(_FAILED_PROFILES)) if n}
|
|
589
|
+
if not wanted:
|
|
590
|
+
return 0
|
|
591
|
+
try:
|
|
592
|
+
closed = _end_browsers(browsers_on_profiles(wanted))
|
|
593
|
+
except Exception as ex:
|
|
594
|
+
start_logger.debug("browser start: could not look for left browsers: %s", ex)
|
|
595
|
+
return 0
|
|
596
|
+
if closed:
|
|
597
|
+
start_logger.warning("browser start: closed %d browser%s a failed start left running", closed, "" if closed == 1 else "s")
|
|
598
|
+
return closed
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
async def _sweep_later(names: set) -> None:
|
|
602
|
+
"""Look for browsers left on these profile folders again over the next minute, and close any that showed up."""
|
|
603
|
+
waited = 0.0
|
|
604
|
+
for at in LEFT_BROWSER_SWEEPS:
|
|
605
|
+
await asyncio.sleep(at - waited)
|
|
606
|
+
waited = at
|
|
607
|
+
await asyncio.to_thread(end_left_browsers, names)
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
async def _after_failed_start(browser: Any, launch: Dict[str, Any], before: set) -> None:
|
|
611
|
+
"""A start failed: close what it left, now and later in the background."""
|
|
612
|
+
names = set(_SEEN_PROFILES - before)
|
|
613
|
+
names.add(own_profile(getattr(getattr(browser, "browser_profile", None), "user_data_dir", None)) or "")
|
|
614
|
+
names.discard("")
|
|
615
|
+
if not names:
|
|
616
|
+
return
|
|
617
|
+
_FAILED_PROFILES.update(names)
|
|
618
|
+
await asyncio.to_thread(end_left_browsers, names)
|
|
619
|
+
with contextlib.suppress(RuntimeError):
|
|
620
|
+
task = asyncio.get_running_loop().create_task(_sweep_later(names))
|
|
621
|
+
_SWEEPS.add(task)
|
|
622
|
+
task.add_done_callback(_SWEEPS.discard)
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
@atexit.register
|
|
626
|
+
def _close_left_browsers_at_exit() -> None:
|
|
627
|
+
end_left_browsers()
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
async def _start_one(launch: Dict[str, Any], make: Any, timeout: float) -> Any:
|
|
631
|
+
"""Start or reach one candidate as its `_via` says; returns the library's started Browser."""
|
|
632
|
+
via = launch.get("_via") or "direct"
|
|
633
|
+
if via == "attach":
|
|
634
|
+
from .browserlaunch import attach_url
|
|
635
|
+
|
|
636
|
+
browser = make(_connect_kwargs(launch, await attach_url(launch.get("_port")), local=False))
|
|
637
|
+
_ATTACHED.add(id(browser))
|
|
638
|
+
try:
|
|
639
|
+
await _within(browser.start(), timeout)
|
|
640
|
+
except BaseException:
|
|
641
|
+
await _shutdown_browser_instance(browser)
|
|
642
|
+
raise
|
|
643
|
+
return browser
|
|
644
|
+
if via == "playwright":
|
|
645
|
+
from .browserlaunch import keep_launcher, launch_with_playwright
|
|
646
|
+
|
|
647
|
+
url, proc, profile = await launch_with_playwright(launch, name=browser_name(launch))
|
|
648
|
+
browser = make(_connect_kwargs(launch, url, local=True))
|
|
649
|
+
keep_launcher(browser, proc, profile)
|
|
650
|
+
else:
|
|
651
|
+
browser = make(library_kwargs(launch))
|
|
652
|
+
before = set(_SEEN_PROFILES)
|
|
653
|
+
try:
|
|
654
|
+
await _within(browser.start(), timeout)
|
|
655
|
+
except BaseException:
|
|
656
|
+
await _shutdown_browser_instance(browser)
|
|
657
|
+
if via == "direct":
|
|
658
|
+
with contextlib.suppress(Exception):
|
|
659
|
+
await _after_failed_start(browser, launch, before)
|
|
660
|
+
raise
|
|
661
|
+
return browser
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
# Browsers ForgeQE connected to and did not start (browser.launch: attach): never ended by it.
|
|
665
|
+
_ATTACHED: set = set()
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def _blocked_directly(error: BaseException) -> bool:
|
|
669
|
+
"""The PC stopped a browser ForgeQE started directly: it closed early and no browser took its port."""
|
|
670
|
+
return "exited before CDP" in str(error)
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _slow(error: BaseException) -> bool:
|
|
674
|
+
return "did not answer within" in str(error)
|
|
675
|
+
|
|
676
|
+
|
|
452
677
|
async def start_local_browser(
|
|
453
678
|
candidates: List[Dict[str, Any]],
|
|
454
679
|
*,
|
|
@@ -459,33 +684,68 @@ async def start_local_browser(
|
|
|
459
684
|
"""
|
|
460
685
|
Start the first candidate browser that starts; returns it with its launch kwargs. A browser that closes before it
|
|
461
686
|
can be driven, or never answers, is shut down and the next one tried (`on_fallback(failed, next, error)` says so).
|
|
687
|
+
|
|
688
|
+
So a slow or locked-down PC still gets a browser:
|
|
689
|
+
- a browser that was only slow (its port did not answer in time) is tried once more before the next;
|
|
690
|
+
- once a browser started directly was stopped by the PC, the other direct starts are skipped for the ones through
|
|
691
|
+
Playwright, which the same PC usually lets run;
|
|
692
|
+
- what started through Playwright is remembered for this computer and tried first among the Playwright starts next
|
|
693
|
+
time (`browserlaunch.remember`), never before a direct start; a remembered start that fails is forgotten;
|
|
694
|
+
- a browser a failed start left running (one a launcher started again, maybe after ForgeQE gave up, or one whose
|
|
695
|
+
Playwright launcher was stopped) is found by the profile folder ForgeQE gave it and closed (`end_left_browsers`).
|
|
696
|
+
|
|
462
697
|
When none starts, the first browser's error is raised, so its explanation (`explain_browser_start`) still applies,
|
|
463
|
-
with the others' results added.
|
|
698
|
+
with the others' results added. A browser the person started (attach) is never fallen back from.
|
|
464
699
|
"""
|
|
700
|
+
from .browserlaunch import forget, remember, remembered
|
|
701
|
+
|
|
465
702
|
failures: List[str] = []
|
|
466
703
|
first_error: Optional[BaseException] = None
|
|
467
704
|
with contextlib.suppress(Exception):
|
|
468
705
|
install_patient_start()
|
|
469
|
-
# The library's
|
|
470
|
-
timeout = timeout if timeout is not None else devtools_wait_seconds() + 30.0
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
706
|
+
# The library's start steps get the wait, a launcher's handover and 15s (install_patient_start); this is past them.
|
|
707
|
+
timeout = timeout if timeout is not None else devtools_wait_seconds() + HANDOVER_SECONDS + 30.0
|
|
708
|
+
last = remembered()
|
|
709
|
+
queue = list(candidates)
|
|
710
|
+
retried = False
|
|
711
|
+
i = 0
|
|
712
|
+
while i < len(queue):
|
|
713
|
+
launch = queue[i]
|
|
714
|
+
start_logger.info(
|
|
715
|
+
"browser start: trying %s (%s)", browser_name(launch),
|
|
716
|
+
f"127.0.0.1:{launch.get('_port')}" if launch.get("_via") == "attach" else launch.get("executable_path") or f"channel {launch.get('channel')}",
|
|
717
|
+
)
|
|
474
718
|
try:
|
|
475
|
-
await
|
|
719
|
+
browser = await _start_one(launch, make, timeout)
|
|
720
|
+
if launch.get("_via") in (None, "direct", "playwright") and len(candidates) > 1:
|
|
721
|
+
remember(launch)
|
|
476
722
|
return browser, launch
|
|
477
723
|
except Exception as ex:
|
|
478
|
-
|
|
479
|
-
if not can_fall_back(ex):
|
|
724
|
+
if launch.get("_via") == "attach" or not can_fall_back(ex):
|
|
480
725
|
raise
|
|
481
726
|
if isinstance(ex, (asyncio.TimeoutError, TimeoutError)):
|
|
482
727
|
ex = RuntimeError(f"Failed to start browser: {browser_name(launch)} did not answer within {int(timeout)} seconds")
|
|
728
|
+
reason = str(ex).strip().splitlines()[0][:300]
|
|
729
|
+
if last is not None and browser_key(launch) == last[0] and launch.get("_via") == last[1]:
|
|
730
|
+
forget()
|
|
731
|
+
if _slow(ex) and not retried:
|
|
732
|
+
retried = True
|
|
733
|
+
start_logger.warning("browser start: %s was slow to answer; trying it once more", browser_name(launch))
|
|
734
|
+
continue
|
|
483
735
|
if first_error is None:
|
|
484
736
|
first_error = ex
|
|
485
|
-
reason = str(ex).strip().splitlines()[0][:300]
|
|
486
737
|
failures.append(f"{browser_name(launch)}: {reason}")
|
|
487
|
-
if
|
|
488
|
-
|
|
738
|
+
if launch.get("_via", "direct") == "direct" and _blocked_directly(ex) and any(c.get("_via") == "playwright" for c in queue[i + 1 :]):
|
|
739
|
+
skipped = [c for c in queue[i + 1 :] if c.get("_via", "direct") == "direct"]
|
|
740
|
+
if skipped:
|
|
741
|
+
start_logger.warning(
|
|
742
|
+
"browser start: this computer stopped %s started directly; skipping %s, and starting through Playwright",
|
|
743
|
+
browser_name(launch), ", ".join(browser_name(c) for c in skipped),
|
|
744
|
+
)
|
|
745
|
+
queue = queue[: i + 1] + [c for c in queue[i + 1 :] if c.get("_via", "direct") != "direct"]
|
|
746
|
+
if i + 1 < len(queue) and on_fallback is not None:
|
|
747
|
+
on_fallback(launch, queue[i + 1], reason)
|
|
748
|
+
i += 1
|
|
489
749
|
if first_error is None:
|
|
490
750
|
raise RuntimeError("No local browser to start.")
|
|
491
751
|
if len(failures) > 1:
|
|
@@ -909,6 +1169,14 @@ async def _shutdown_browser_instance(browser: Any) -> None:
|
|
|
909
1169
|
"""
|
|
910
1170
|
if browser is None:
|
|
911
1171
|
return
|
|
1172
|
+
if id(browser) in _ATTACHED:
|
|
1173
|
+
# A browser the person started: only let go of it (stop() leaves the browser running), never end it.
|
|
1174
|
+
_ATTACHED.discard(id(browser))
|
|
1175
|
+
with contextlib.suppress(Exception):
|
|
1176
|
+
res = browser.stop()
|
|
1177
|
+
if asyncio.iscoroutine(res):
|
|
1178
|
+
await asyncio.wait_for(res, timeout=30.0)
|
|
1179
|
+
return
|
|
912
1180
|
mine = {**_handed_over_browsers(), **_automation_browsers_of_mine()}
|
|
913
1181
|
for name in ("kill", "stop"):
|
|
914
1182
|
fn = getattr(browser, name, None)
|
|
@@ -921,7 +1189,15 @@ async def _shutdown_browser_instance(browser: Any) -> None:
|
|
|
921
1189
|
break
|
|
922
1190
|
except Exception as ex:
|
|
923
1191
|
logger.debug("engine library: browser.%s() failed: %s", name, ex)
|
|
1192
|
+
# A browser Playwright started is closed by its launcher, which then exits.
|
|
1193
|
+
from .browserlaunch import close_launcher
|
|
1194
|
+
|
|
1195
|
+
with contextlib.suppress(Exception):
|
|
1196
|
+
await close_launcher(browser)
|
|
924
1197
|
left = await asyncio.to_thread(_end_browsers, mine)
|
|
1198
|
+
# Browsers that failed starts of this engine left running, found by their profile folders.
|
|
1199
|
+
with contextlib.suppress(Exception):
|
|
1200
|
+
await asyncio.to_thread(end_left_browsers)
|
|
925
1201
|
if left:
|
|
926
1202
|
logger.info("closed %d browser%s the library left running", left, "" if left == 1 else "s")
|
|
927
1203
|
|
|
@@ -956,6 +1232,8 @@ async def browser_profile(browser: Any, launch: Dict[str, Any], *, provider: str
|
|
|
956
1232
|
"driver": driver,
|
|
957
1233
|
"channel": launch.get("channel") or "",
|
|
958
1234
|
"executable": launch.get("executable_path") or "",
|
|
1235
|
+
# How the local browser was reached: direct, playwright or attach (browser.launch).
|
|
1236
|
+
"started": launch.get("_via") or ("direct" if provider == "local" else ""),
|
|
959
1237
|
"headless": bool(launch.get("headless")),
|
|
960
1238
|
"removed_default_args": list(launch.get("ignore_default_args") or []),
|
|
961
1239
|
"extra_http_headers": {},
|