@capagents/forgeqe 2.8.8 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HOW_TO_USE.md +10 -2
- package/dist/docs-site/docs/index.html +83 -2
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/forgeqe.js +2036 -2029
- package/dist/template.html +66 -66
- package/dist/web/THIRD_PARTY_NOTICES.md +455 -0
- package/dist/web/assets/Agent-BGwHbXbc.js +4 -0
- package/dist/web/assets/ApiTests-DSnZHRlF.js +10 -0
- package/dist/web/assets/Browse-Dx3pHGuG.js +2 -0
- package/dist/web/assets/Chat-BcFP0BbA.js +3 -0
- package/dist/web/assets/CommandPalette-v6mqHZnU.js +1 -0
- package/dist/web/assets/Cost-C9LZdx1p.js +1 -0
- package/dist/web/assets/Data-DvbaOc9e.js +6 -0
- package/dist/web/assets/Evidence-Y1AeSzh5.js +1 -0
- package/dist/web/assets/Explore-Dw8S6DG1.js +2 -0
- package/dist/web/assets/Features-CjrVraBE.js +1 -0
- package/dist/web/assets/Flags-C_Qm0078.js +2 -0
- package/dist/web/assets/Flaky-DYgN586D.js +1 -0
- package/dist/web/assets/ForceGraph-CEH86-Z0.js +1 -0
- package/dist/web/assets/Impact-dBPp7aM2.js +3 -0
- package/dist/web/assets/Jobs-CSyN6YRx.js +5 -0
- package/dist/web/assets/KindPage-BQl-5bcd.js +6 -0
- package/dist/web/assets/Migration-COly7O-T.js +2 -0
- package/dist/web/assets/Product-7mM8tcxH.js +7 -0
- package/dist/web/assets/Production-De5CCUoP.js +1 -0
- package/dist/web/assets/Quality-Q_iqj3fk.js +1 -0
- package/dist/web/assets/Readiness-kU9kum_I.js +1 -0
- package/dist/web/assets/Record-CIhINuEz.js +2 -0
- package/dist/web/assets/Regression-CMQnH7dN.js +5 -0
- package/dist/web/assets/Reports-dUOe6_vN.js +2 -0
- package/dist/web/assets/Response-DGl2R0A-.js +4 -0
- package/dist/web/assets/RunDiff-BVRRIz3m.js +1 -0
- package/dist/web/assets/Runs-CkNWhAhe.js +2 -0
- package/dist/web/assets/TestCases-exR7hRWd.js +1 -0
- package/dist/web/assets/TestData-yVPMg9kw.js +2 -0
- package/dist/web/assets/TestDebt-C3sM6cH0.js +1 -0
- package/dist/web/assets/Tosca-Bcalg1JU.js +2 -0
- package/dist/web/assets/WhatsNew-EFSt6xx2.js +1 -0
- package/dist/web/assets/dataParts-D33u08WR.js +3 -0
- package/dist/web/assets/{families-7ZW63NF1.js → families-Btjss8bN.js} +1 -1
- package/dist/web/assets/frame-D3IhgCFt.js +4 -0
- package/dist/web/assets/index-D5sya6FK.css +2 -0
- package/dist/web/assets/index-v-k_CVn7.js +45 -0
- package/dist/web/assets/line-icons-CQ-3V8ax.js +1 -0
- package/dist/web/assets/logos-CfpaNwbY.js +1 -0
- package/dist/web/assets/palette-X7hU78Wy.js +1 -0
- package/dist/web/assets/parts-B7YrlR3a.js +1 -0
- package/dist/web/assets/productParts-CAxyMnWJ.js +1 -0
- package/dist/web/assets/qualityParts-CN9JVKZN.js +1 -0
- package/dist/web/assets/rows-IEP4Jvfi.js +1 -0
- package/dist/web/assets/{segmented-CCfjZKVa.js → segmented-DBqHvZW3.js} +1 -1
- package/dist/web/assets/thread-BeaLQ_f4.js +5 -0
- package/dist/web/assets/usePageChat-D_3KsqBU.js +1 -0
- package/dist/web/index.html +4 -3
- package/docs/user-guide.html +87 -2
- 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 +3 -0
- package/package.json +2 -1
- package/py/forgeqe_engine/browser.py +533 -28
- 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/dist/web/assets/Agent-Cp8VlBIz.js +0 -4
- package/dist/web/assets/ApiTests-BcZLc09C.js +0 -10
- package/dist/web/assets/Browse-C_YjgIEb.js +0 -1
- package/dist/web/assets/Chat-BoCGL6_O.js +0 -3
- package/dist/web/assets/CommandPalette-BfM5HzzB.js +0 -1
- package/dist/web/assets/Cost-TS6CXmoR.js +0 -1
- package/dist/web/assets/Data-CBPzLyv3.js +0 -6
- package/dist/web/assets/Evidence-BZq0G649.js +0 -1
- package/dist/web/assets/Explore-l6Hdu8Sv.js +0 -2
- package/dist/web/assets/Features-YYJcXLBf.js +0 -1
- package/dist/web/assets/Flags-C60CLbzH.js +0 -2
- package/dist/web/assets/Flaky-BkLguGXu.js +0 -1
- package/dist/web/assets/ForceGraph-D1krkEJe.js +0 -1
- package/dist/web/assets/Impact-640wqe0S.js +0 -3
- package/dist/web/assets/Jobs-C97GqHLF.js +0 -5
- package/dist/web/assets/KindPage-Bux228tV.js +0 -6
- package/dist/web/assets/Migration-VTuXJ3MF.js +0 -2
- package/dist/web/assets/Product-BNDHj6KV.js +0 -7
- package/dist/web/assets/Production-BC-kcNIt.js +0 -1
- package/dist/web/assets/Quality-CuSQTvtJ.js +0 -1
- package/dist/web/assets/Readiness-Bh2cynJx.js +0 -1
- package/dist/web/assets/Record-DJfuaIqW.js +0 -2
- package/dist/web/assets/Regression-oW_4rSE7.js +0 -5
- package/dist/web/assets/Reports-CBkl7Abx.js +0 -2
- package/dist/web/assets/Response-f5217Gw2.js +0 -4
- package/dist/web/assets/RunDiff-B7o9vQBr.js +0 -1
- package/dist/web/assets/Runs-CkdASpHU.js +0 -2
- package/dist/web/assets/TestCases-BPif-KCg.js +0 -1
- package/dist/web/assets/TestData-CQAI8n3o.js +0 -2
- package/dist/web/assets/TestDebt-C94phbAj.js +0 -1
- package/dist/web/assets/Tosca-CX7hZsNJ.js +0 -2
- package/dist/web/assets/WhatsNew-ktL7koKS.js +0 -1
- package/dist/web/assets/dataParts-DD_0rviO.js +0 -3
- package/dist/web/assets/frame-Ct3Ey3bQ.js +0 -4
- package/dist/web/assets/index-DvuGI8X3.css +0 -2
- package/dist/web/assets/index-tdO1bZWq.js +0 -45
- package/dist/web/assets/logos-Czko8FVx.js +0 -1
- package/dist/web/assets/parts-ryIgw8NG.js +0 -1
- package/dist/web/assets/productParts-CSw1V5I9.js +0 -1
- package/dist/web/assets/qualityParts-Czf68wgs.js +0 -1
- package/dist/web/assets/thread-_hyYtCeH.js +0 -5
- package/dist/web/assets/usePageChat-Cm84Zkf4.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()
|
|
@@ -159,8 +163,209 @@ def local_browser_launch_kwargs(*, headless: bool) -> Dict[str, Any]:
|
|
|
159
163
|
# The library's words when Chrome exits before its DevTools port answers, and close variants of other versions.
|
|
160
164
|
_EARLY_EXIT = ("exited before CDP", "before CDP became available", "Browser process exited", "Failed to start browser", "Chrome failed to start")
|
|
161
165
|
|
|
162
|
-
# How long one browser has to
|
|
163
|
-
|
|
166
|
+
# How long one browser's DevTools port has to answer before the next browser is tried. Company PCs are slow to start a
|
|
167
|
+
# browser (security software scans it first); FORGEQE_ENGINE_BROWSER_START_SECONDS changes it, from 15 to 600.
|
|
168
|
+
DEVTOOLS_WAIT_SECONDS = 90.0
|
|
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
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def devtools_wait_seconds() -> float:
|
|
177
|
+
try:
|
|
178
|
+
value = float((os.getenv("FORGEQE_ENGINE_BROWSER_START_SECONDS") or "").strip())
|
|
179
|
+
except ValueError:
|
|
180
|
+
return DEVTOOLS_WAIT_SECONDS
|
|
181
|
+
return min(600.0, max(15.0, value)) if value == value else DEVTOOLS_WAIT_SECONDS
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
start_logger = logging.getLogger("forgeqe_engine.browser_start")
|
|
185
|
+
|
|
186
|
+
# Browsers a launcher handed over to (not this engine's own descendants), closed with the ones it started.
|
|
187
|
+
_HANDED_OVER: Dict[int, List[str]] = {}
|
|
188
|
+
|
|
189
|
+
_SAFE_FLAG_VALUES = ("--remote-debugging-port", "--user-data-dir", "--profile-directory", "--headless", "--window-size")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def describe_args(args: List[str]) -> str:
|
|
193
|
+
"""A browser's command line for the log: the program, and each flag by name, with a value only for flags whose
|
|
194
|
+
value says how it was started (never a proxy, a URL or anything else that may hold a credential)."""
|
|
195
|
+
if not args:
|
|
196
|
+
return "(unknown)"
|
|
197
|
+
shown = [args[0]]
|
|
198
|
+
for a in args[1:]:
|
|
199
|
+
name = a.split("=", 1)[0]
|
|
200
|
+
if not name.startswith("--"):
|
|
201
|
+
continue
|
|
202
|
+
shown.append(a if name in _SAFE_FLAG_VALUES else name)
|
|
203
|
+
return " ".join(shown)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _process_args(proc: Any) -> List[str]:
|
|
207
|
+
try:
|
|
208
|
+
return list(proc.cmdline())
|
|
209
|
+
except Exception:
|
|
210
|
+
return []
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _alive(proc: Any) -> bool:
|
|
214
|
+
import psutil
|
|
215
|
+
|
|
216
|
+
try:
|
|
217
|
+
return bool(proc.is_running()) and proc.status() != psutil.STATUS_ZOMBIE
|
|
218
|
+
except psutil.AccessDenied:
|
|
219
|
+
return True
|
|
220
|
+
except Exception:
|
|
221
|
+
return False
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _exit_code(proc: Any) -> str:
|
|
225
|
+
try:
|
|
226
|
+
code = proc.wait(timeout=0)
|
|
227
|
+
except Exception:
|
|
228
|
+
return "not known"
|
|
229
|
+
if code is None:
|
|
230
|
+
return "not known"
|
|
231
|
+
# Windows reports codes like 0xC0000022 (access denied) as large unsigned numbers: show them as Windows does.
|
|
232
|
+
return f"{code} (0x{code & 0xFFFFFFFF:08X})" if isinstance(code, int) and (code < 0 or code > 255) else str(code)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def port_owner(port: int, *, not_pid: Optional[int] = None) -> Optional[Any]:
|
|
236
|
+
"""The browser's main process started with this DevTools port, when it is not the one ForgeQE started (a launcher
|
|
237
|
+
on the PC may start the browser again under another process and exit). None when there is none."""
|
|
238
|
+
import psutil
|
|
239
|
+
|
|
240
|
+
flag = f"--remote-debugging-port={port}"
|
|
241
|
+
for proc in psutil.process_iter():
|
|
242
|
+
if proc.pid == not_pid:
|
|
243
|
+
continue
|
|
244
|
+
args = _process_args(proc)
|
|
245
|
+
if flag in args and not any(a.startswith("--type=") for a in args):
|
|
246
|
+
return proc
|
|
247
|
+
return None
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _handed_over(proc: Any) -> None:
|
|
251
|
+
args = _process_args(proc)
|
|
252
|
+
if args:
|
|
253
|
+
_HANDED_OVER[proc.pid] = args
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
async def wait_for_devtools(port: int, timeout: float = 30, process: Any = None) -> str:
|
|
257
|
+
"""
|
|
258
|
+
Wait for a browser's DevTools port to answer; the library's own wait, made patient and logged. The library gives up
|
|
259
|
+
the moment the process it started has exited; on a company PC that process is often a launcher that starts the
|
|
260
|
+
browser again under another process (security software, a browser wrapper) and exits, and the browser answers on
|
|
261
|
+
the same port a few seconds later. So an exit is noted and the port still watched, for HANDOVER_SECONDS more when no
|
|
262
|
+
other browser has the port and up to the full wait when one has. Every step goes to the run's log.
|
|
263
|
+
"""
|
|
264
|
+
import aiohttp
|
|
265
|
+
|
|
266
|
+
loop = asyncio.get_running_loop()
|
|
267
|
+
started = loop.time()
|
|
268
|
+
limit = max(float(timeout or 0), devtools_wait_seconds())
|
|
269
|
+
pid = getattr(process, "pid", None)
|
|
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)")
|
|
275
|
+
start_logger.info("browser start: waiting up to %ds for DevTools on 127.0.0.1:%d", int(limit), port)
|
|
276
|
+
exited_at: Optional[float] = None
|
|
277
|
+
exit_code = "not known"
|
|
278
|
+
children: Dict[int, Any] = {}
|
|
279
|
+
owner: Any = None
|
|
280
|
+
last = "no answer yet"
|
|
281
|
+
next_note = started + 5
|
|
282
|
+
next_scan = started
|
|
283
|
+
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=3)) as session:
|
|
284
|
+
while True:
|
|
285
|
+
now = loop.time()
|
|
286
|
+
waited = now - started
|
|
287
|
+
try:
|
|
288
|
+
async with session.get(f"http://127.0.0.1:{port}/json/version") as resp:
|
|
289
|
+
if resp.status == 200:
|
|
290
|
+
if owner is None and exited_at is not None:
|
|
291
|
+
owner = port_owner(port, not_pid=pid)
|
|
292
|
+
if owner is not None:
|
|
293
|
+
_handed_over(owner)
|
|
294
|
+
start_logger.info("browser start: DevTools answered after %.1fs from PID %s, which took over from PID %s", waited, owner.pid, pid)
|
|
295
|
+
else:
|
|
296
|
+
start_logger.info("browser start: DevTools answered after %.1fs", waited)
|
|
297
|
+
return f"http://127.0.0.1:{port}/"
|
|
298
|
+
last = f"HTTP {resp.status}"
|
|
299
|
+
except Exception as ex:
|
|
300
|
+
last = type(ex).__name__
|
|
301
|
+
if process is not None and exited_at is None:
|
|
302
|
+
if _alive(process):
|
|
303
|
+
try:
|
|
304
|
+
for child in process.children(recursive=True):
|
|
305
|
+
children.setdefault(child.pid, child)
|
|
306
|
+
except Exception:
|
|
307
|
+
pass
|
|
308
|
+
else:
|
|
309
|
+
exited_at = waited
|
|
310
|
+
exit_code = _exit_code(process)
|
|
311
|
+
start_logger.warning(
|
|
312
|
+
"browser start: PID %s exited after %.1fs, exit code %s, before DevTools answered; it started %d other process%s",
|
|
313
|
+
pid, waited, exit_code, len(children), "" if len(children) == 1 else "es",
|
|
314
|
+
)
|
|
315
|
+
if exited_at is not None and owner is None and now >= next_scan:
|
|
316
|
+
next_scan = now + 1
|
|
317
|
+
owner = next((c for c in children.values() if _alive(c) and f"--remote-debugging-port={port}" in _process_args(c)), None)
|
|
318
|
+
owner = owner or port_owner(port, not_pid=pid)
|
|
319
|
+
if owner is not None:
|
|
320
|
+
_handed_over(owner)
|
|
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)))
|
|
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:
|
|
324
|
+
raise RuntimeError(
|
|
325
|
+
f"Browser process (PID {pid}) exited before CDP became available on port {port}. It exited after "
|
|
326
|
+
f"{exited_at:.1f}s with exit code {exit_code}, and no other browser took its port in {int(grace)}s ({last})."
|
|
327
|
+
)
|
|
328
|
+
if owner is not None and not _alive(owner) and exited_at is not None:
|
|
329
|
+
raise RuntimeError(
|
|
330
|
+
f"Browser process (PID {pid}) exited before CDP became available on port {port}, and PID {owner.pid}, "
|
|
331
|
+
f"which took it over, exited too ({last})."
|
|
332
|
+
)
|
|
333
|
+
if waited >= limit:
|
|
334
|
+
state = f"PID {pid} " + (f"exited after {exited_at:.1f}s with exit code {exit_code}" if exited_at is not None else "still runs")
|
|
335
|
+
if owner is not None:
|
|
336
|
+
state += f"; PID {owner.pid} has the port"
|
|
337
|
+
raise RuntimeError(f"Failed to start browser: DevTools on port {port} did not answer within {int(limit)}s ({state}; {last}).")
|
|
338
|
+
if now >= next_note:
|
|
339
|
+
next_note = now + 5
|
|
340
|
+
start_logger.info(
|
|
341
|
+
"browser start: still waiting after %.0fs (%s; PID %s %s)", waited, last, pid,
|
|
342
|
+
"running" if exited_at is None else f"exited at {exited_at:.1f}s" + (f", PID {owner.pid} has the port" if owner is not None else ""),
|
|
343
|
+
)
|
|
344
|
+
await asyncio.sleep(0.25)
|
|
345
|
+
|
|
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
|
+
|
|
351
|
+
def install_patient_start() -> None:
|
|
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
|
+
"""
|
|
356
|
+
from browser_use.browser.watchdogs.local_browser_watchdog import LocalBrowserWatchdog
|
|
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
|
+
|
|
367
|
+
if getattr(LocalBrowserWatchdog._wait_for_cdp_url, "__name__", "") != "wait_for_devtools":
|
|
368
|
+
LocalBrowserWatchdog._wait_for_cdp_url = staticmethod(wait_for_devtools)
|
|
164
369
|
|
|
165
370
|
|
|
166
371
|
def find_playwright_chromium() -> Optional[str]:
|
|
@@ -197,20 +402,39 @@ def find_playwright_chromium() -> Optional[str]:
|
|
|
197
402
|
return max(files, key=build) if files else None
|
|
198
403
|
|
|
199
404
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
""
|
|
405
|
+
LOCAL_BROWSERS = ("auto", "chrome", "edge", "chromium")
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def local_browser_choice(value: Any) -> str:
|
|
409
|
+
"""browser.local_browser of forgeqe.yaml: auto (the default), chrome, edge or chromium; anything else is auto."""
|
|
410
|
+
v = str(value or "").strip().lower()
|
|
411
|
+
return v if v in LOCAL_BROWSERS else "auto"
|
|
412
|
+
|
|
413
|
+
|
|
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`)."""
|
|
206
416
|
first = local_browser_launch_kwargs(headless=headless)
|
|
207
417
|
pinned = bool((os.getenv("BROWSER_USE_EXECUTABLE_PATH") or "").strip()) and first.get("executable_path")
|
|
418
|
+
if pinned:
|
|
419
|
+
return [first]
|
|
420
|
+
base = {k: v for k, v in first.items() if k not in ("channel", "executable_path")}
|
|
421
|
+
pick = local_browser_choice(choice)
|
|
422
|
+
if pick == "edge":
|
|
423
|
+
edge = find_edge_executable()
|
|
424
|
+
if not edge:
|
|
425
|
+
raise RuntimeError("browser.local_browser is edge, but Microsoft Edge is not installed on this computer.")
|
|
426
|
+
return [{**base, "channel": "msedge", "executable_path": edge}]
|
|
427
|
+
if pick == "chromium":
|
|
428
|
+
pw = find_playwright_chromium()
|
|
429
|
+
# Without Playwright's Chromium here, the library finds a Chromium or installs its own.
|
|
430
|
+
return [{**base, "channel": "chromium", **({"executable_path": pw} if pw else {})}]
|
|
431
|
+
if pick == "chrome":
|
|
432
|
+
return [first]
|
|
208
433
|
off = (os.getenv("BROWSER_USE_FALLBACK") or "").strip().lower() in ("0", "false", "no", "off")
|
|
209
434
|
out = [first]
|
|
210
|
-
if
|
|
435
|
+
if off:
|
|
211
436
|
return out
|
|
212
437
|
seen = {os.path.normcase(str(first.get("executable_path") or ""))}
|
|
213
|
-
base = {k: v for k, v in first.items() if k not in ("channel", "executable_path")}
|
|
214
438
|
for channel, exe in (("msedge", find_edge_executable()), ("chromium", find_playwright_chromium())):
|
|
215
439
|
key = os.path.normcase(str(exe or ""))
|
|
216
440
|
if exe and key not in seen:
|
|
@@ -219,15 +443,85 @@ def local_launch_candidates(*, headless: bool) -> List[Dict[str, Any]]:
|
|
|
219
443
|
return out
|
|
220
444
|
|
|
221
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
|
+
|
|
222
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')}"
|
|
223
504
|
exe = str(launch.get("executable_path") or "")
|
|
224
505
|
if launch.get("channel") == "msedge":
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
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}
|
|
231
525
|
|
|
232
526
|
|
|
233
527
|
def can_fall_back(error: BaseException) -> bool:
|
|
@@ -238,38 +532,220 @@ def can_fall_back(error: BaseException) -> bool:
|
|
|
238
532
|
return any(m.lower() in text for m in _EARLY_EXIT) or "failed to launch browser" in text
|
|
239
533
|
|
|
240
534
|
|
|
535
|
+
async def _within(coro: Any, seconds: float) -> Any:
|
|
536
|
+
"""Await coro in the caller's own task, as it was before a time limit was put on it (asyncio.wait_for would run the
|
|
537
|
+
browser's start in a task of its own); on Python before 3.11, which has no asyncio.timeout, through wait_for."""
|
|
538
|
+
limit = getattr(asyncio, "timeout", None)
|
|
539
|
+
if limit is None:
|
|
540
|
+
return await asyncio.wait_for(coro, timeout=seconds)
|
|
541
|
+
async with limit(seconds):
|
|
542
|
+
return await coro
|
|
543
|
+
|
|
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
|
+
|
|
241
677
|
async def start_local_browser(
|
|
242
678
|
candidates: List[Dict[str, Any]],
|
|
243
679
|
*,
|
|
244
680
|
make: Any,
|
|
245
681
|
on_fallback: Any = None,
|
|
246
|
-
timeout: float =
|
|
682
|
+
timeout: Optional[float] = None,
|
|
247
683
|
) -> "tuple[Any, Dict[str, Any]]":
|
|
248
684
|
"""
|
|
249
685
|
Start the first candidate browser that starts; returns it with its launch kwargs. A browser that closes before it
|
|
250
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
|
+
|
|
251
697
|
When none starts, the first browser's error is raised, so its explanation (`explain_browser_start`) still applies,
|
|
252
|
-
with the others' results added.
|
|
698
|
+
with the others' results added. A browser the person started (attach) is never fallen back from.
|
|
253
699
|
"""
|
|
700
|
+
from .browserlaunch import forget, remember, remembered
|
|
701
|
+
|
|
254
702
|
failures: List[str] = []
|
|
255
703
|
first_error: Optional[BaseException] = None
|
|
256
|
-
|
|
257
|
-
|
|
704
|
+
with contextlib.suppress(Exception):
|
|
705
|
+
install_patient_start()
|
|
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
|
+
)
|
|
258
718
|
try:
|
|
259
|
-
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)
|
|
260
722
|
return browser, launch
|
|
261
723
|
except Exception as ex:
|
|
262
|
-
|
|
263
|
-
if not can_fall_back(ex):
|
|
724
|
+
if launch.get("_via") == "attach" or not can_fall_back(ex):
|
|
264
725
|
raise
|
|
265
726
|
if isinstance(ex, (asyncio.TimeoutError, TimeoutError)):
|
|
266
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
|
|
267
735
|
if first_error is None:
|
|
268
736
|
first_error = ex
|
|
269
|
-
reason = str(ex).strip().splitlines()[0][:300]
|
|
270
737
|
failures.append(f"{browser_name(launch)}: {reason}")
|
|
271
|
-
if
|
|
272
|
-
|
|
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
|
|
273
749
|
if first_error is None:
|
|
274
750
|
raise RuntimeError("No local browser to start.")
|
|
275
751
|
if len(failures) > 1:
|
|
@@ -348,7 +824,10 @@ def explain_browser_start(message: str, policy: Optional[str] = None, *, check_p
|
|
|
348
824
|
"policy that turns off remote debugging (open chrome://policy and look for RemoteDebuggingAllowed), security "
|
|
349
825
|
"software that stops a Chrome started for automation, or a Chrome update in progress (restart Chrome once). "
|
|
350
826
|
"ForgeQE also tries Microsoft Edge and Playwright's Chromium (npx playwright install chromium) when they are "
|
|
351
|
-
"installed.
|
|
827
|
+
"installed; browser.local_browser in forgeqe.yaml picks one of them. On a slow computer, give the browser longer "
|
|
828
|
+
"to answer with FORGEQE_ENGINE_BROWSER_START_SECONDS (90 by default); the run's log has each step of the start "
|
|
829
|
+
"(browser start: ...). Run with --headed to watch it start, or set "
|
|
830
|
+
"BROWSER_USE_EXECUTABLE_PATH to another Chrome or Edge."
|
|
352
831
|
)
|
|
353
832
|
|
|
354
833
|
|
|
@@ -617,6 +1096,14 @@ async def stop_video(browser: Any) -> Optional[Path]:
|
|
|
617
1096
|
return Path(path) if path and Path(path).is_file() and Path(path).stat().st_size else None
|
|
618
1097
|
|
|
619
1098
|
|
|
1099
|
+
def _handed_over_browsers() -> Dict[int, List[str]]:
|
|
1100
|
+
"""Browsers a launcher started for this engine (`wait_for_devtools` found them by their DevTools port): taken out of
|
|
1101
|
+
the list here, so each is closed once, and only while it still runs with the same command line (`_end_browsers`)."""
|
|
1102
|
+
out = dict(_HANDED_OVER)
|
|
1103
|
+
_HANDED_OVER.clear()
|
|
1104
|
+
return out
|
|
1105
|
+
|
|
1106
|
+
|
|
620
1107
|
def _automation_browsers_of_mine() -> Dict[int, List[str]]:
|
|
621
1108
|
"""
|
|
622
1109
|
The browsers this engine started for automation that run now: its own descendants started with a debugging port,
|
|
@@ -682,7 +1169,15 @@ async def _shutdown_browser_instance(browser: Any) -> None:
|
|
|
682
1169
|
"""
|
|
683
1170
|
if browser is None:
|
|
684
1171
|
return
|
|
685
|
-
|
|
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
|
|
1180
|
+
mine = {**_handed_over_browsers(), **_automation_browsers_of_mine()}
|
|
686
1181
|
for name in ("kill", "stop"):
|
|
687
1182
|
fn = getattr(browser, name, None)
|
|
688
1183
|
if not callable(fn):
|
|
@@ -694,7 +1189,15 @@ async def _shutdown_browser_instance(browser: Any) -> None:
|
|
|
694
1189
|
break
|
|
695
1190
|
except Exception as ex:
|
|
696
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)
|
|
697
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)
|
|
698
1201
|
if left:
|
|
699
1202
|
logger.info("closed %d browser%s the library left running", left, "" if left == 1 else "s")
|
|
700
1203
|
|
|
@@ -729,6 +1232,8 @@ async def browser_profile(browser: Any, launch: Dict[str, Any], *, provider: str
|
|
|
729
1232
|
"driver": driver,
|
|
730
1233
|
"channel": launch.get("channel") or "",
|
|
731
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 ""),
|
|
732
1237
|
"headless": bool(launch.get("headless")),
|
|
733
1238
|
"removed_default_args": list(launch.get("ignore_default_args") or []),
|
|
734
1239
|
"extra_http_headers": {},
|