"""QA runner: execute Playwright tests, sync progress, finalize results.""" import json import os import subprocess import time from pathlib import Path from config.gemini import GEMINI_API_KEY from config.qa import QA_FRONTEND_DIR, QA_FRONTEND_URL, QA_RUN_TIMEOUT_SECONDS from enums import QaStatus, QaResult from qa.results import parse_qa_results from qa.scenarios import build_qa_scenarios, download_qa_images from qa.store import qa_int, qa_iso_now, qa_run_root, read_qa_run, write_qa_run def qa_runner_env(run_root: Path, scenarios: list[dict], use_gemini: bool, backend_url: str): env = os.environ.copy() env.update({ "API_URL": backend_url, "PLAYWRIGHT_BASE_URL": QA_FRONTEND_URL, "QA_HTML_REPORT_DIR": str(run_root / "html-report"), "QA_PLAYWRIGHT_OUTPUT_DIR": str(run_root / "artifacts"), "QA_PROGRESS_FILE": str(run_root / "progress.json"), "QA_PROGRESS_MODE": "cases", "QA_RESULTS_DIR": str(run_root / "results"), "QA_SCENARIOS": json.dumps(scenarios), "QA_SKIP_GEMINI": "0" if use_gemini else "1", "QA_TEST_IMAGES_DIR": str(run_root / "images"), "QA_WORKERS": "1", "VITE_API_URL": backend_url, }) if use_gemini: if not GEMINI_API_KEY: raise RuntimeError("Gemini is enabled for this QA run, but GEMINI_API_KEY is not configured.") env["GEMINI_API_KEY"] = GEMINI_API_KEY env.setdefault("GEMINI_MODEL", "gemini-3.1-flash-lite") return env def finalize_qa_run_from_report(run: dict, report_path: Path): results = parse_qa_results(run["id"], report_path) passed = sum(1 for result in results if result["status"] == QaResult.PASSED) failed = sum(1 for result in results if result["status"] == QaResult.FAILED) completed = sum(1 for result in results if result["status"] in {QaResult.PASSED, QaResult.FAILED, QaResult.SKIPPED}) run.update({ "completed": completed, "failed": failed, "passed": passed, "results": results, "status": QaStatus.COMPLETED if report_path.exists() else QaStatus.FAILED, }) if failed: run["status"] = QaStatus.FAILED def sync_qa_run_progress(run_id: str, progress_path: Path): if not progress_path.exists(): return try: progress = json.loads(progress_path.read_text()) except Exception: return run = read_qa_run(run_id) updates = { "completed": qa_int(progress.get("completed"), qa_int(run.get("completed"))), "failed": qa_int(progress.get("failed"), qa_int(run.get("failed"))), "passed": qa_int(progress.get("passed"), qa_int(run.get("passed"))), "progressUpdatedAt": progress.get("updatedAt"), "skipped": qa_int(progress.get("skipped"), qa_int(run.get("skipped"))), "total": qa_int(progress.get("total"), qa_int(run.get("total"))), } if run.get("status") == QaStatus.QUEUED: updates["status"] = QaStatus.RUNNING if all(run.get(key) == value for key, value in updates.items()): return run.update(updates) write_qa_run(run) def run_playwright_qa(run_id: str, run_root: Path, env: dict, log_file): command = ["npm", "run", "qa:e2e"] progress_path = run_root / "progress.json" process = subprocess.Popen( command, cwd=QA_FRONTEND_DIR, env=env, stderr=subprocess.STDOUT, stdout=log_file, ) deadline = time.monotonic() + QA_RUN_TIMEOUT_SECONDS while True: return_code = process.poll() sync_qa_run_progress(run_id, progress_path) if return_code is not None: return return_code if time.monotonic() >= deadline: process.terminate() try: process.wait(timeout=10) except subprocess.TimeoutExpired: process.kill() process.wait(timeout=10) sync_qa_run_progress(run_id, progress_path) raise subprocess.TimeoutExpired(command, QA_RUN_TIMEOUT_SECONDS) time.sleep(1) def run_qa_task(run_id: str, image_keys: list[str], tiles: list[str], descriptions: dict[str, str], use_gemini: bool, backend_url: str): run = read_qa_run(run_id) run_root = qa_run_root(run_id) log_path = run_root / "runner.log" report_path = run_root / "results" / "real-qa.json" summary_path = run_root / "qa-summary.md" try: if not QA_FRONTEND_URL: raise RuntimeError("QA_FRONTEND_URL must point to the hosted frontend.") if not QA_FRONTEND_DIR.exists(): raise RuntimeError(f"QA_FRONTEND_DIR does not exist: {QA_FRONTEND_DIR}") if not (QA_FRONTEND_DIR / "package.json").exists(): raise RuntimeError(f"QA_FRONTEND_DIR must point to frontend/viz2d-demo: {QA_FRONTEND_DIR}") run.update({"status": QaStatus.RUNNING, "startedAt": qa_iso_now()}) write_qa_run(run) downloaded_images = download_qa_images(run_id, image_keys) scenarios = build_qa_scenarios(downloaded_images, tiles, descriptions) (run_root / "scenarios.json").write_text(json.dumps(scenarios, indent=2)) env = qa_runner_env(run_root, scenarios, use_gemini, backend_url) with log_path.open("w") as log_file: exit_code = run_playwright_qa(run_id, run_root, env, log_file) log_file.write(f"\nqa:e2e exit code: {exit_code}\n") subprocess.run( ["npm", "run", "qa:report", "--", str(report_path), str(summary_path)], cwd=QA_FRONTEND_DIR, env=env, stderr=subprocess.STDOUT, stdout=log_file, timeout=300, ) run = read_qa_run(run_id) finalize_qa_run_from_report(run, report_path) if not report_path.exists(): run["error"] = "Playwright did not create a JSON report. Check runner.log." run["reportUrl"] = f"/qa/runs/{run_id}/report" write_qa_run(run) except subprocess.TimeoutExpired: run = read_qa_run(run_id) run.update({"status": QaStatus.FAILED, "error": "QA run timed out.", "reportUrl": f"/qa/runs/{run_id}/report"}) write_qa_run(run) except Exception as exc: run = read_qa_run(run_id) run.update({"status": QaStatus.FAILED, "error": str(exc), "reportUrl": f"/qa/runs/{run_id}/report"}) write_qa_run(run)