"""Patchwise remote browser runner: runs one Playwright attempt at a time for a Patchwise server that cannot drive a browser itself (for example a host whose network Oracle's edge refuses). Standard library only; Python 3.10+. The Patchwise server posts an attempt (case ids, config, the run's environment, any AI-written or library specs), polls it, then downloads one zip: the Playwright JSON report (attachment paths relative to the run directory), the run directory (screenshots, videos, traces), the pod values tried and the ledger of created test records. An attempt that reaches its own deadline is first asked to stop (SIGINT: Playwright ends the tests that run and still writes its report), and only killed after RUNNER_GRACE_S. Each job's metadata is kept in its folder (job.json), so after a runner restart a finished job still answers its status and bundle, and a job that was running is reported "lost" (the Patchwise server then fails it at once instead of waiting for its deadline). Assisted sign-in (a pod whose sign-in goes through the company's identity provider, with MFA): a person signs in through Astra's run page in a browser that runs here (scripts/sign-in-session.ts). POST /v1/sign-in opens it on the pod, GET /v1/sign-in/ returns its latest frame, POST .../input applies the person's clicks and keys, POST .../finish hands the signed-in session (Playwright storage state) back once and deletes it here, POST .../cancel closes it. It holds the same one-browser lock as an attempt and closes by itself after RUNNER_SIGN_IN_IDLE_S without input (default 900). An attempt may then carry that session ("storage_state"): it is written to the job folder (mode 0600) for the tests to start from instead of signing in, and deleted when the attempt ends; it never ships in a bundle. Security: every call needs `Authorization: Bearer ` (compared in constant time). Only known environment keys and the Patchwise Playwright configs are accepted; spec names are plain file names. The Fusion password exists only in the Playwright process's environment, never on disk. What a person types in a sign-in session is never logged. Put it behind HTTPS (deploy/remote-runner/Caddyfile). Environment: RUNNER_TOKEN (required), RUNNER_PORT (default 8899), RUNNER_HOME (default ~/runner-data), AUTOMATION_DIR (default: ../ of this file), RUNNER_KEEP_HOURS (default 24), RUNNER_GRACE_S (default 90), RUNNER_SIGN_IN_IDLE_S (default 900).""" from __future__ import annotations import base64 import hmac import io import json import os import re import secrets import shutil import signal import subprocess import threading import time import zipfile from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path TOKEN = os.environ.get("RUNNER_TOKEN", "") PORT = int(os.environ.get("RUNNER_PORT", "8899")) HOME = Path(os.environ.get("RUNNER_HOME", str(Path.home() / "runner-data"))) AUTOMATION = Path(os.environ.get("AUTOMATION_DIR", str(Path(__file__).resolve().parents[1]))) KEEP_S = float(os.environ.get("RUNNER_KEEP_HOURS", "24")) * 3600 GRACE_S = float(os.environ.get("RUNNER_GRACE_S", "90")) # an attempt past its deadline gets this long to write its report # the scenario files the repo's own step specs read (../tests/cases), and the commit deploy/runner/sync.sh installed CASES = AUTOMATION.parent / "tests" / "cases" VERSION_FILE = AUTOMATION.parent / "VERSION" CONFIGS = {"playwright.fusion.config.ts", "playwright.agent.config.ts"} ENV_KEYS = {"FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES", "FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS", "FPT_SIGN_IN_MODE", "FPT_HEALS", "FPT_NAV_LINKS", "FPT_NAV_LINKS_LEARNED", "FPT_ALLOW_IMPORTS"} SESSION_STATE = "sign-in-state.json" # an attempt's signed-in session (assisted sign-in), in its job folder while it runs SPEC = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.spec\.ts$") ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,80}$") MAX_BODY = 20_000_000 # each attempt in its own process group, so a cancel stops it and every browser it started (Linux and Windows) GROUP = {"start_new_session": True} if os.name == "posix" else {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} LOCK = threading.Lock() # one attempt at a time: the runner is sized for one browser JOBS: dict[str, dict] = {} META = ("id", "kind", "state", "started", "deadline", "pw_run_id", "exit_code", "timed_out", "error") ENDED = ("done", "cancelled", "failed") def write_secret(f: Path, text: str) -> None: """A file only this user can read, created that way (never world-readable, not even for a moment).""" fd = os.open(str(f), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as fh: fh.write(text) def write_session(jd: Path, state) -> Path: """The signed-in session an attempt starts from (a Playwright storage state), checked for its shape.""" if not isinstance(state, dict) or not isinstance(state.get("cookies"), list) or not isinstance(state.get("origins", []), list): raise ValueError("storage_state is a Playwright storage state ({cookies, origins})") f = jd / SESSION_STATE write_secret(f, json.dumps({"cookies": state["cookies"], "origins": state.get("origins") or []})) return f def drop_session(job: dict) -> None: try: (job["dir"] / SESSION_STATE).unlink(missing_ok=True) except OSError: pass def save_meta(job: dict) -> None: """The job's metadata (never its environment) in its folder, written whole, so a restarted runner can answer for it.""" try: tmp = job["dir"] / ".job.json.tmp" tmp.write_text(json.dumps({k: job.get(k) for k in META}), encoding="utf-8") tmp.replace(job["dir"] / "job.json") except OSError: pass def load_jobs() -> None: """After a restart: jobs kept on disk answer again. A finished one as it ended; one that was running is "lost" (its processes died with the old runner), and what it left (its ledger of test records, its run folder) still ships.""" for d in sorted(HOME.glob("job_*")): try: meta = json.loads((d / "job.json").read_text(encoding="utf-8")) except (OSError, ValueError): continue jid = str(meta.get("id") or "") if jid != d.name or jid in JOBS or not re.fullmatch(r"job_[0-9a-f]{12}", jid): continue job = {**{k: meta.get(k) for k in META}, "dir": d, "started": float(meta.get("started") or d.stat().st_mtime)} drop_session(job) # a session cookie file outlives no runner if job["state"] not in ENDED: job["state"] = "lost" try: _collect(job) except OSError: pass # what could not be moved stays where it is; the job still answers save_meta(job) JOBS[jid] = job def grep_for(ids: list[str]) -> str: return "|".join(re.escape(i) for i in ids) def _progress(log: Path) -> dict: try: b = log.read_bytes()[-20000:] except OSError: return {} m = list(re.finditer(rb"\[(\d+)/(\d+)\]", b)) return {"done": int(m[-1].group(1)), "total": int(m[-1].group(2))} if m else {} def _relativize(report: Path, run_dir: Path) -> None: """Attachment paths in the report become relative to the run directory (the server maps them to its own).""" data = json.loads(report.read_text(encoding="utf-8")) def walk(suites): for s in suites or []: for sp in s.get("specs") or []: for t in sp.get("tests") or []: for r in t.get("results") or []: for a in r.get("attachments") or []: p = a.get("path") if p: try: a["path"] = str(Path(p).resolve().relative_to(run_dir.resolve())).replace("\\", "/") except ValueError: a["path"] = None # outside the run directory: not shipped walk(s.get("suites")) walk(data.get("suites")) report.write_text(json.dumps(data), encoding="utf-8") YAML_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}\.yaml$") _IMPORT_SRC = re.compile(r"""(from\s+)(["'])[^"'\n]*?/automation/src/""") _STEPS_DIR = re.compile(r"""(dir:\s*)"(?:[^"\\\n]|\\.)*\"""") def local_spec(text: str, steps_dir: Path) -> str: """A spec written on the Patchwise server, made runnable here: its imports of the server's automation/src point to this runner's, and a steps scenario reads its YAML from the job's steps folder.""" text = _IMPORT_SRC.sub(lambda m: f"{m.group(1)}{m.group(2)}{(AUTOMATION / 'src').as_posix()}/", text) return _STEPS_DIR.sub(lambda m: m.group(1) + json.dumps(steps_dir.as_posix()), text) def start(body: dict) -> dict: ids = [str(i) for i in body.get("ids") or []] if not ids or not all(ID.match(i) for i in ids): raise ValueError("ids: case ids such as AP-FUS-001") pw_run_id = str(body.get("pw_run_id") or "") if not ID.match(pw_run_id): raise ValueError("pw_run_id is missing or not a plain id") config = str(body.get("config") or "playwright.fusion.config.ts") if config not in CONFIGS: raise ValueError(f"config is one of {sorted(CONFIGS)}") env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in ENV_KEYS} if not LOCK.acquire(blocking=False): raise BlockingIOError("another attempt is running on this runner") try: jid = "job_" + secrets.token_hex(6) jd = HOME / jid (jd / "drafts").mkdir(parents=True) (jd / "library").mkdir() (jd / "steps").mkdir() for name, text in (body.get("steps") or {}).items(): # the steps scenarios' YAML (the server's copy is not here) if not YAML_NAME.match(name): raise ValueError(f"steps: {name!r} is not a scenario file name") (jd / "steps" / name).write_text(str(text), encoding="utf-8") for kind in ("drafts", "library"): for name, text in (body.get(kind) or {}).items(): if not SPEC.match(name): raise ValueError(f"{kind}: {name!r} is not a spec file name") (jd / kind / name).write_text(local_spec(str(text), jd / "steps"), encoding="utf-8") report = jd / "report.json" env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN", "FPT_FUSION_STORAGE_STATE", "FPT_ALLOW_IMPORTS")} # imports only when the job says so env.update(env_in) if body.get("storage_state") is not None: # assisted sign-in: the tests start from the session a person signed in env["FPT_FUSION_STORAGE_STATE"] = str(write_session(jd, body["storage_state"])) env.update({"PLAYWRIGHT_MODE": "live", "PW_RETRIES": "0", "PW_RUN_ID": pw_run_id, "PLAYWRIGHT_JSON_OUTPUT_NAME": str(report), "FPT_TESTDATA_USED": str(jd / "testdata-used.jsonl"), "FPT_CREATED_FILE": str(jd / "created.jsonl")}) live = body.get("live") or {} for k in ("FPT_LIVE_VIEW_DIR", "FPT_LIVE_VIEW_ATTEMPT", "FPT_LIVE_VIEW_CHUNK"): env.pop(k, None) if live and ID.match(str(live.get("attempt") or "")): # live view: the browser hook drops its latest frame here (jd / "live").mkdir() env.update({"FPT_LIVE_VIEW_DIR": str(jd / "live"), "FPT_LIVE_VIEW_ATTEMPT": str(live["attempt"]), "FPT_LIVE_VIEW_CHUNK": "0"}) for kind in ("drafts", "library"): key = "FPT_DRAFTS_DIR" if kind == "drafts" else "FPT_LIBRARY_DIR" if any((jd / kind).glob("*.spec.ts")): env[key] = str(jd / kind) else: env.pop(key, None) cmd = ["node", str(AUTOMATION / "node_modules" / "@playwright" / "test" / "cli.js"), "test", "--config", config, "--retries=0", "--reporter=json", "--grep", grep_for(ids)] log = open(jd / "playwright.log", "wb") p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **GROUP) job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": pw_run_id, "started": time.time(), "kind": "attempt", "deadline": time.time() + min(float(body.get("timeout_s") or 3600), 4 * 3600), "state": "running", "exit_code": None} JOBS[jid] = job save_meta(job) threading.Thread(target=_watch, args=(job,), daemon=True).start() return {"id": jid, "state": "running"} except BaseException: LOCK.release() raise SCREEN_SCRIPTS = {"explore": "scripts/explore-fusion.ts", "capture": "scripts/capture-fusion.ts"} SCREEN_ENV = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA") TASK = re.compile(r"^[^\r\n<>]{5,250}$") OUT_FILE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,160}\.(json|values)$") def start_screens(body: dict) -> dict: """Read a pod's screens (labels only): "explore" with a plan of areas, or "capture" of one "Area > Page > Task". Same lock as the attempts (one browser); the files land in the job's out/ folder and come back in the bundle.""" kind = str(body.get("kind") or "") if kind not in SCREEN_SCRIPTS: raise ValueError(f"kind is one of {sorted(SCREEN_SCRIPTS)}") env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in SCREEN_ENV} if not all(env_in.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")): raise ValueError("env needs FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD") task = str(body.get("task") or "") if kind == "capture" and not TASK.match(task): raise ValueError('task is "Area > Page > Task"') if kind == "explore" and not isinstance(body.get("plan"), dict): raise ValueError("plan is the explorer's plan (an object)") if not LOCK.acquire(blocking=False): raise BlockingIOError("another attempt is running on this runner") try: jid = "job_" + secrets.token_hex(6) jd = HOME / jid (jd / "out").mkdir(parents=True) arg = task if kind == "explore": (jd / "plan.json").write_text(json.dumps(body["plan"]), encoding="utf-8") arg = str(jd / "plan.json") env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)} env.update(env_in) cmd = ["node", str(AUTOMATION / "node_modules" / "tsx" / "dist" / "cli.mjs"), SCREEN_SCRIPTS[kind], arg, "--out-dir", str(jd / "out")] log = open(jd / "playwright.log", "wb") p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **GROUP) job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": jid, "started": time.time(), "kind": kind, "deadline": time.time() + min(float(body.get("timeout_s") or 5400), 4 * 3600), "state": "running", "exit_code": None} JOBS[jid] = job save_meta(job) threading.Thread(target=_watch, args=(job,), daemon=True).start() return {"id": jid, "state": "running"} except BaseException: LOCK.release() raise def live_now(job: dict) -> dict: """The live view of a running attempt: the latest frame and the failed scenario's last frame (JPEG, base64) and the hook's status. The hook never writes a sign-in screen (it masks pages with a password field).""" d = job["dir"] / "live" out: dict = {"status": None, "frame": None, "failed": None, "frame_at": None} if not d.is_dir(): return out try: out["status"] = json.loads((d / "status.json").read_text(encoding="utf-8")) except (OSError, ValueError): pass for key, name in (("frame", "frame.jpg"), ("failed", "failed.jpg")): f = d / name try: if key == "frame": out["frame_at"] = f.stat().st_mtime out[key] = base64.b64encode(f.read_bytes()).decode() except OSError: pass return out def _lines(log: Path, since: int) -> tuple[list[str], int]: """The log's lines from `since` on (at most 200), and how many lines it has.""" try: lines = log.read_text(encoding="utf-8", errors="replace").splitlines() except OSError: return [], 0 return [ln[:500] for ln in lines[since:since + 200]], len(lines) def _kill_tree(p: subprocess.Popen) -> None: """Stop the attempt and every browser it started (a process group on Linux, a process tree on Windows).""" try: if os.name == "posix": os.killpg(p.pid, signal.SIGKILL) else: subprocess.run(["taskkill", "/PID", str(p.pid), "/T", "/F"], capture_output=True, timeout=30) except (OSError, subprocess.SubprocessError): pass def _interrupt(p: subprocess.Popen) -> bool: """Ask Playwright to stop as Ctrl+C does: it ends the running tests, marks the rest as not run and still writes its JSON report. False where that cannot be asked (Windows: the attempt is killed at once).""" if os.name != "posix": return False try: os.kill(p.pid, signal.SIGINT) return True except OSError: return False def _collect(job: dict) -> None: """What the attempt left becomes the job's: the report (attachment paths made relative) and the run folder.""" run_dir = AUTOMATION / "results" / "runs" / str(job.get("pw_run_id") or "") report = job["dir"] / "report.json" if report.exists(): try: _relativize(report, run_dir) except (OSError, ValueError): pass # a report cut off mid-write still ships as it is if job.get("pw_run_id") and run_dir.is_dir() and not (job["dir"] / "run").exists(): shutil.move(str(run_dir), str(job["dir"] / "run")) # the evidence moves into the job (the automation folder never piles up) def _watch(job: dict) -> None: p = job["proc"] try: stop_at = None while p.poll() is None: if job.get("cancel"): _kill_tree(p) elif time.time() > job["deadline"]: if stop_at is None: # its own time is up: stopped gently first, so its report is not lost job["timed_out"] = True stop_at = time.time() + (GRACE_S if _interrupt(p) else 0) if time.time() >= stop_at: _kill_tree(p) time.sleep(2) job["exit_code"] = p.returncode job["log"].close() _collect(job) job["state"] = "cancelled" if job.get("cancel") else "done" except Exception as e: # noqa: BLE001 - the job ends as failed, never stays "running" once the lock is released job["state"], job["error"] = "failed", f"{type(e).__name__}: {e}"[:300] _kill_tree(p) finally: drop_session(job) save_meta(job) LOCK.release() # ------------------------------------------------------------------ assisted sign-in: a browser a person signs in with SIGN_INS: dict[str, dict] = {} SIGN_IN_IDLE_S = float(os.environ.get("RUNNER_SIGN_IN_IDLE_S", "900")) SIGN_IN_KEEP_S = 600 # a signed-in session nobody fetched is deleted after this long POD_URL = re.compile(r"^https://[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?(?::\d{1,5})?$") KEY = re.compile(r"^(?:(?:Control|Shift|Alt|Meta)\+)*(?:[A-Za-z0-9]|Enter|Tab|Backspace|Delete|Escape|ArrowUp|ArrowDown|ArrowLeft" r"|ArrowRight|Home|End|PageUp|PageDown|Space)$") VIEW = (1280, 800) # the sign-in browser's viewport (scripts/sign-in-session.ts): clicks are in its pixels def sign_in_cmd(folder: Path) -> list[str]: """The sign-in browser (scripts/sign-in-session.ts), driven through `folder`.""" return ["node", str(AUTOMATION / "node_modules" / "tsx" / "dist" / "cli.mjs"), "scripts/sign-in-session.ts", str(folder)] def check_events(events) -> list[dict]: """The person's clicks, text, keys and scrolls, checked (at most 50 per call): anything else is refused whole.""" if not isinstance(events, list) or not 1 <= len(events) <= 50: raise ValueError("events: 1 to 50 input events") out = [] for e in events: t = e.get("type") if isinstance(e, dict) else None num = lambda k: isinstance(e.get(k), (int, float)) and not isinstance(e.get(k), bool) # noqa: E731 if t == "click" and num("x") and num("y") and 0 <= e["x"] <= VIEW[0] and 0 <= e["y"] <= VIEW[1]: out.append({"type": "click", "x": round(float(e["x"]), 1), "y": round(float(e["y"]), 1)}) elif t == "type" and isinstance(e.get("text"), str) and 0 < len(e["text"]) <= 500: out.append({"type": "type", "text": e["text"]}) elif t == "press" and isinstance(e.get("key"), str) and KEY.match(e["key"]): out.append({"type": "press", "key": e["key"]}) elif t == "scroll" and num("dy") and abs(e["dy"]) <= 2000: out.append({"type": "scroll", "dy": float(e["dy"])}) else: raise ValueError(f"event {len(out) + 1} is not a click, text, key or scroll this browser accepts") return out def _say(s: dict, events: list[dict]) -> None: with open(s["dir"] / "input.jsonl", "a", encoding="utf-8") as fh: for e in events: fh.write(json.dumps(e) + "\n") def start_sign_in(body: dict) -> dict: base = str(body.get("base_url") or "").strip().rstrip("/") if not POD_URL.match(base): raise ValueError("base_url is the pod's https address") try: idle = max(60.0, min(float(body.get("idle_s") or SIGN_IN_IDLE_S), 3600.0)) except (TypeError, ValueError): raise ValueError("idle_s is a number of seconds") from None if not LOCK.acquire(blocking=False): raise BlockingIOError("another attempt is running on this runner") try: sid = "si_" + secrets.token_hex(6) d = HOME / sid d.mkdir(parents=True) env = {k: v for k, v in os.environ.items() if k not in ENV_KEYS and k not in ("RUNNER_TOKEN", "FPT_FUSION_STORAGE_STATE")} env.update({"FUSION_BASE_URL": base, "FPT_SIGN_IN_MAX_S": "3600"}) log = open(d / "sign-in.log", "wb") p = subprocess.Popen(sign_in_cmd(d), cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **GROUP) s = {"id": sid, "dir": d, "proc": p, "log": log, "started": time.time(), "last_input": time.time(), "idle_s": idle, "state": "open"} SIGN_INS[sid] = s threading.Thread(target=_watch_sign_in, args=(s,), daemon=True).start() return {"id": sid, "state": "starting"} except BaseException: LOCK.release() raise def sign_in_now(s: dict) -> dict: """The session as Astra's run page shows it: its state, which kind of page is open, the latest frame (JPEG, base64).""" d = s["dir"] try: st = json.loads((d / "status.json").read_text(encoding="utf-8")) except (OSError, ValueError): st = {} state = s["state"] if s["state"] != "open" else (st.get("state") or "starting") if state == "closed" and (d / "state.json").exists(): state = "signed_in" out = {"id": s["id"], "state": state, "page": st.get("page"), "error": st.get("error") if state == "failed" else None, "frame": None, "frame_at": None, "idle_left_s": max(0, int(s["idle_s"] - (time.time() - s["last_input"])))} if state in ("starting", "open"): try: out["frame_at"] = (d / "frame.jpg").stat().st_mtime out["frame"] = base64.b64encode((d / "frame.jpg").read_bytes()).decode() except OSError: pass return out def sign_in_input(s: dict, body: dict) -> dict: if s["state"] != "open" or s["proc"].poll() is not None: raise LookupError("this sign-in session is not open any more") events = check_events(body.get("events")) _say(s, events) s["last_input"] = time.time() return {"accepted": len(events)} def finish_sign_in(s: dict, wait_s: float = 20.0) -> dict | None: """The signed-in session, handed back once: the browser saves it when asked (or saved it on reaching the Fusion home page), then it is deleted here with the session's folder.""" f = s["dir"] / "state.json" if not f.exists() and s["state"] == "open" and s["proc"].poll() is None: _say(s, [{"type": "finish"}]) end = time.time() + wait_s while not f.exists() and s["proc"].poll() is None and time.time() < end: time.sleep(0.2) for _ in range(10): # the browser writes the file, then closes: give it a moment to finish if s["proc"].poll() is not None: break time.sleep(0.2) try: data = json.loads(f.read_text(encoding="utf-8")) except (OSError, ValueError): return None s["state"] = "finished" _close_sign_in(s) return data def cancel_sign_in(s: dict) -> None: if s["state"] == "open" and s["proc"].poll() is None: s["cancel"] = True try: _say(s, [{"type": "cancel"}]) except OSError: pass else: s["state"] = "cancelled" if s["state"] in ("open", "signed_in") else s["state"] _close_sign_in(s) def _close_sign_in(s: dict) -> None: if s["proc"].poll() is None: _kill_tree(s["proc"]) try: s["proc"].wait(timeout=10) except subprocess.TimeoutExpired: pass try: s["log"].close() # its log is in the folder (Windows keeps an open file) except OSError: pass shutil.rmtree(s["dir"], ignore_errors=True) # frames, the session, the inbox: nothing of it stays on disk def _watch_sign_in(s: dict) -> None: """The browser runs until the person signs in, finishes, cancels, or leaves it idle; the lock is free once it is gone.""" p = s["proc"] try: stop_at = None while p.poll() is None: idle = time.time() - s["last_input"] > s["idle_s"] if s.get("cancel") or idle: s["expired"] = s.get("expired") or (idle and not s.get("cancel")) stop_at = stop_at or time.time() + 5 # asked to close first, then stopped if time.time() >= stop_at: _kill_tree(p) time.sleep(0.5) s["log"].close() except Exception: # noqa: BLE001 - the session ends as failed, the lock is never kept _kill_tree(p) finally: LOCK.release() if s["state"] != "open": # handed back (or cancelled) while the browser closed return saved = (s["dir"] / "state.json").exists() state = "cancelled" if s.get("cancel") else "expired" if s.get("expired") else "signed_in" if saved else "closed" if state != "signed_in": _close_sign_in(s) # nothing of it on disk before it reads as ended s["state"] = state return s["state"] = state end = time.time() + SIGN_IN_KEEP_S # waiting for Astra to fetch it, but not for ever while time.time() < end and s["state"] == "signed_in": time.sleep(1) if s["state"] == "signed_in": s["state"] = "expired" _close_sign_in(s) def bundle(job: dict) -> bytes: buf = io.BytesIO() with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z: for name in ("report.json", "testdata-used.jsonl", "created.jsonl", "playwright.log"): f = job["dir"] / name if f.exists(): z.write(f, name) out = job["dir"] / "out" # a screen read: the inventories (labels) and the list choices it found if out.exists(): for f in out.iterdir(): if f.is_file() and OUT_FILE.match(f.name): z.write(f, "out/" + f.name) run = job["dir"] / "run" if run.exists(): for f in run.rglob("*"): if f.is_file() and f.name != ".fusion-session.json": # never ship the session cookies z.write(f, "run/" + str(f.relative_to(run)).replace("\\", "/")) return buf.getvalue() def sweep() -> None: while True: cut = time.time() - KEEP_S for jid, job in list(JOBS.items()): if job["state"] != "running" and job["started"] < cut: shutil.rmtree(job["dir"], ignore_errors=True) JOBS.pop(jid, None) # folders of jobs from before a restart are not in JOBS: their age on disk decides for d in HOME.glob("job_*"): if d.is_dir() and d.name not in JOBS and d.stat().st_mtime < cut: shutil.rmtree(d, ignore_errors=True) time.sleep(600) class H(BaseHTTPRequestHandler): server_version = "PatchwiseRunner/1" timeout = 120 # a client that stalls mid-request (slow headers or body) frees its thread instead of holding it for ever def log_message(self, fmt, *args): # one quiet line per call, never a header or a body print(time.strftime("%H:%M:%S"), self.command, self.path.split("?")[0], args[1] if len(args) > 1 else "", flush=True) def _send(self, code: int, obj=None, raw: bytes | None = None, ctype="application/json"): b = raw if raw is not None else json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(b))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(b) def _auth(self) -> bool: h = self.headers.get("Authorization", "") # bytes, so a non-ASCII header is a wrong token (compare_digest on str would raise); constant time ok = bool(TOKEN) and h.startswith("Bearer ") and hmac.compare_digest(h[7:].strip().encode("utf-8", "replace"), TOKEN.encode("utf-8")) if not ok: self._send(401, {"error": "a valid runner token is needed"}) return ok def _job(self, jid: str): job = JOBS.get(jid) if not job: self._send(404, {"error": "no such attempt"}) return job def do_GET(self): if self.path == "/healthz": version = VERSION_FILE.read_text(encoding="utf-8").strip()[:40] if VERSION_FILE.is_file() else "unknown" return self._send(200, {"ok": bool(TOKEN), "busy": LOCK.locked(), "automation": AUTOMATION.exists(), "cases": CASES.is_dir(), "version": version}) if not self._auth(): return si = re.fullmatch(r"/v1/sign-in/(si_[0-9a-f]{12})", self.path) if si: s = SIGN_INS.get(si.group(1)) return self._send(200, sign_in_now(s)) if s else self._send(404, {"error": "no such sign-in session"}) m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})(/bundle|/live)?(?:\?since=(\d{1,7}))?", self.path) if not m: return self._send(404, {"error": "not found"}) job = self._job(m.group(1)) if not job: return if m.group(2) == "/live": return self._send(200, live_now(job) if job["state"] == "running" else {"status": None, "frame": None, "failed": None, "frame_at": None}) if m.group(2): if job["state"] == "running": return self._send(409, {"error": "the attempt is still running"}) return self._send(200, raw=bundle(job), ctype="application/zip") st = {"id": job["id"], "state": job["state"], "exit_code": job.get("exit_code"), "timed_out": bool(job.get("timed_out")), "progress": _progress(job["dir"] / "playwright.log"), "report": (job["dir"] / "report.json").exists(), "started": job.get("started"), "pw_run_id": job.get("pw_run_id")} if m.group(3) is not None: # a screen read follows its log lines ("[explore] ...") for its progress st["lines"], st["line_count"] = _lines(job["dir"] / "playwright.log", int(m.group(3))) self._send(200, st) def do_POST(self): if not self._auth(): return try: n = int(self.headers.get("Content-Length") or 0) except ValueError: n = -1 if n < 0: return self._send(400, {"error": "Content-Length is not a length"}) if n > MAX_BODY: return self._send(413, {"error": "body too large"}) if self.path in ("/v1/attempts", "/v1/screens"): try: body = json.loads(self.rfile.read(n) or b"{}") return self._send(202, start(body) if self.path == "/v1/attempts" else start_screens(body)) except BlockingIOError as e: return self._send(409, {"error": str(e)}) except (ValueError, TypeError) as e: return self._send(400, {"error": str(e)}) if self.path == "/v1/sign-in": try: return self._send(202, start_sign_in(json.loads(self.rfile.read(n) or b"{}"))) except BlockingIOError as e: return self._send(409, {"error": str(e)}) except (ValueError, TypeError, AttributeError) as e: return self._send(400, {"error": str(e)}) si = re.fullmatch(r"/v1/sign-in/(si_[0-9a-f]{12})/(input|finish|cancel)", self.path) if si: s = SIGN_INS.get(si.group(1)) if not s: return self._send(404, {"error": "no such sign-in session"}) try: if si.group(2) == "input": # only the session this id opened, and only while it is open return self._send(200, sign_in_input(s, json.loads(self.rfile.read(n) or b"{}"))) if si.group(2) == "finish": state = finish_sign_in(s) if state is None: return self._send(409, {"error": "the sign-in session holds no signed-in session (not signed in yet, or closed)"}) return self._send(200, {"id": s["id"], "state": "finished", "storage_state": state}) cancel_sign_in(s) return self._send(202, {"id": s["id"], "state": "cancelling" if s.get("cancel") else s["state"]}) except LookupError as e: return self._send(409, {"error": str(e)}) except (ValueError, TypeError, AttributeError) as e: return self._send(400, {"error": str(e)}) m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})/cancel", self.path) if m: job = self._job(m.group(1)) if job: if job["state"] == "running": job["cancel"] = True self._send(202, {"id": job["id"], "state": "cancelling" if job["state"] == "running" else job["state"]}) return self._send(404, {"error": "not found"}) if __name__ == "__main__": if not TOKEN or len(TOKEN) < 24: raise SystemExit("set RUNNER_TOKEN (at least 24 characters)") HOME.mkdir(parents=True, exist_ok=True) for old in HOME.glob("si_*"): # a sign-in session never outlives the runner: its frames and cookies go shutil.rmtree(old, ignore_errors=True) load_jobs() threading.Thread(target=sweep, daemon=True).start() print(f"Patchwise remote runner on 127.0.0.1:{PORT}, automation {AUTOMATION}", flush=True) ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()