Patchwise Agent Studio: Oracle AI Agent Studio cycles
Browse files- automation/remote_runner/server.py +253 -0
- automation/scripts/check-dates.ts +23 -0
- automation/src/fusion/dates.ts +69 -0
- automation/src/fusion/ui.ts +16 -3
- coworker/adapters/remote_runner.py +123 -0
- coworker/config.py +3 -0
- coworker/graph/nodes/execute.py +11 -0
- coworker/tests/test_remote_runner.py +115 -0
- docs/REMOTE_RUNNER.md +81 -0
automation/remote_runner/server.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Patchwise remote browser runner: runs one Playwright attempt at a time for a Patchwise server that cannot drive a
|
| 2 |
+
browser itself (for example a host whose network Oracle's edge refuses). Standard library only; Python 3.10+.
|
| 3 |
+
|
| 4 |
+
The Patchwise server posts an attempt (case ids, config, the run's environment, any AI-written or library specs),
|
| 5 |
+
polls it, then downloads one zip: the Playwright JSON report (attachment paths relative to the run directory), the
|
| 6 |
+
run directory (screenshots, videos, traces), the pod values tried and the ledger of created test records.
|
| 7 |
+
|
| 8 |
+
Security: every call needs `Authorization: Bearer <RUNNER_TOKEN>` (compared in constant time). Only known environment
|
| 9 |
+
keys and the Patchwise Playwright configs are accepted; spec names are plain file names. The Fusion password exists
|
| 10 |
+
only in the Playwright process's environment, never on disk. Put it behind HTTPS (deploy/remote-runner/Caddyfile).
|
| 11 |
+
|
| 12 |
+
Environment: RUNNER_TOKEN (required), RUNNER_PORT (default 8899), RUNNER_HOME (default ~/runner-data),
|
| 13 |
+
AUTOMATION_DIR (default: ../ of this file), RUNNER_KEEP_HOURS (default 24)."""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import hmac
|
| 17 |
+
import io
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import re
|
| 21 |
+
import secrets
|
| 22 |
+
import shutil
|
| 23 |
+
import signal
|
| 24 |
+
import subprocess
|
| 25 |
+
import threading
|
| 26 |
+
import time
|
| 27 |
+
import zipfile
|
| 28 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
TOKEN = os.environ.get("RUNNER_TOKEN", "")
|
| 32 |
+
PORT = int(os.environ.get("RUNNER_PORT", "8899"))
|
| 33 |
+
HOME = Path(os.environ.get("RUNNER_HOME", str(Path.home() / "runner-data")))
|
| 34 |
+
AUTOMATION = Path(os.environ.get("AUTOMATION_DIR", str(Path(__file__).resolve().parents[1])))
|
| 35 |
+
KEEP_S = float(os.environ.get("RUNNER_KEEP_HOURS", "24")) * 3600
|
| 36 |
+
CONFIGS = {"playwright.fusion.config.ts", "playwright.agent.config.ts"}
|
| 37 |
+
ENV_KEYS = {"FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES",
|
| 38 |
+
"FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS"}
|
| 39 |
+
SPEC = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.spec\.ts$")
|
| 40 |
+
ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,80}$")
|
| 41 |
+
MAX_BODY = 20_000_000
|
| 42 |
+
LOCK = threading.Lock() # one attempt at a time: the runner is sized for one browser
|
| 43 |
+
JOBS: dict[str, dict] = {}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def grep_for(ids: list[str]) -> str:
|
| 47 |
+
return "|".join(re.escape(i) for i in ids)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _progress(log: Path) -> dict:
|
| 51 |
+
try:
|
| 52 |
+
b = log.read_bytes()[-20000:]
|
| 53 |
+
except OSError:
|
| 54 |
+
return {}
|
| 55 |
+
m = list(re.finditer(rb"\[(\d+)/(\d+)\]", b))
|
| 56 |
+
return {"done": int(m[-1].group(1)), "total": int(m[-1].group(2))} if m else {}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _relativize(report: Path, run_dir: Path) -> None:
|
| 60 |
+
"""Attachment paths in the report become relative to the run directory (the server maps them to its own)."""
|
| 61 |
+
data = json.loads(report.read_text(encoding="utf-8"))
|
| 62 |
+
|
| 63 |
+
def walk(suites):
|
| 64 |
+
for s in suites or []:
|
| 65 |
+
for sp in s.get("specs") or []:
|
| 66 |
+
for t in sp.get("tests") or []:
|
| 67 |
+
for r in t.get("results") or []:
|
| 68 |
+
for a in r.get("attachments") or []:
|
| 69 |
+
p = a.get("path")
|
| 70 |
+
if p:
|
| 71 |
+
try:
|
| 72 |
+
a["path"] = str(Path(p).resolve().relative_to(run_dir.resolve())).replace("\\", "/")
|
| 73 |
+
except ValueError:
|
| 74 |
+
a["path"] = None # outside the run directory: not shipped
|
| 75 |
+
walk(s.get("suites"))
|
| 76 |
+
walk(data.get("suites"))
|
| 77 |
+
report.write_text(json.dumps(data), encoding="utf-8")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def start(body: dict) -> dict:
|
| 81 |
+
ids = [str(i) for i in body.get("ids") or []]
|
| 82 |
+
if not ids or not all(ID.match(i) for i in ids):
|
| 83 |
+
raise ValueError("ids: case ids such as AP-FUS-001")
|
| 84 |
+
pw_run_id = str(body.get("pw_run_id") or "")
|
| 85 |
+
if not ID.match(pw_run_id):
|
| 86 |
+
raise ValueError("pw_run_id is missing or not a plain id")
|
| 87 |
+
config = str(body.get("config") or "playwright.fusion.config.ts")
|
| 88 |
+
if config not in CONFIGS:
|
| 89 |
+
raise ValueError(f"config is one of {sorted(CONFIGS)}")
|
| 90 |
+
env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in ENV_KEYS}
|
| 91 |
+
if not LOCK.acquire(blocking=False):
|
| 92 |
+
raise BlockingIOError("another attempt is running on this runner")
|
| 93 |
+
try:
|
| 94 |
+
jid = "job_" + secrets.token_hex(6)
|
| 95 |
+
jd = HOME / jid
|
| 96 |
+
(jd / "drafts").mkdir(parents=True)
|
| 97 |
+
(jd / "library").mkdir()
|
| 98 |
+
for kind in ("drafts", "library"):
|
| 99 |
+
for name, text in (body.get(kind) or {}).items():
|
| 100 |
+
if not SPEC.match(name):
|
| 101 |
+
raise ValueError(f"{kind}: {name!r} is not a spec file name")
|
| 102 |
+
(jd / kind / name).write_text(str(text), encoding="utf-8")
|
| 103 |
+
report = jd / "report.json"
|
| 104 |
+
env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)}
|
| 105 |
+
env.update(env_in)
|
| 106 |
+
env.update({"PLAYWRIGHT_MODE": "live", "PW_RETRIES": "0", "PW_RUN_ID": pw_run_id, "PLAYWRIGHT_JSON_OUTPUT_NAME": str(report),
|
| 107 |
+
"FPT_TESTDATA_USED": str(jd / "testdata-used.jsonl"), "FPT_CREATED_FILE": str(jd / "created.jsonl")})
|
| 108 |
+
for kind in ("drafts", "library"):
|
| 109 |
+
key = "FPT_DRAFTS_DIR" if kind == "drafts" else "FPT_LIBRARY_DIR"
|
| 110 |
+
if any((jd / kind).glob("*.spec.ts")):
|
| 111 |
+
env[key] = str(jd / kind)
|
| 112 |
+
else:
|
| 113 |
+
env.pop(key, None)
|
| 114 |
+
cmd = ["node", str(AUTOMATION / "node_modules" / "@playwright" / "test" / "cli.js"), "test", "--config", config,
|
| 115 |
+
"--retries=0", "--reporter=json", "--grep", grep_for(ids)]
|
| 116 |
+
log = open(jd / "playwright.log", "wb")
|
| 117 |
+
p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
| 118 |
+
job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": pw_run_id, "started": time.time(),
|
| 119 |
+
"deadline": time.time() + min(float(body.get("timeout_s") or 3600), 4 * 3600), "state": "running", "exit_code": None}
|
| 120 |
+
JOBS[jid] = job
|
| 121 |
+
threading.Thread(target=_watch, args=(job,), daemon=True).start()
|
| 122 |
+
return {"id": jid, "state": "running"}
|
| 123 |
+
except BaseException:
|
| 124 |
+
LOCK.release()
|
| 125 |
+
raise
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _watch(job: dict) -> None:
|
| 129 |
+
p = job["proc"]
|
| 130 |
+
try:
|
| 131 |
+
while p.poll() is None:
|
| 132 |
+
if time.time() > job["deadline"] or job.get("cancel"):
|
| 133 |
+
job["timed_out"] = not job.get("cancel")
|
| 134 |
+
try:
|
| 135 |
+
os.killpg(p.pid, signal.SIGKILL)
|
| 136 |
+
except OSError:
|
| 137 |
+
pass
|
| 138 |
+
time.sleep(2)
|
| 139 |
+
job["exit_code"] = p.returncode
|
| 140 |
+
job["log"].close()
|
| 141 |
+
run_dir = AUTOMATION / "results" / "runs" / job["pw_run_id"]
|
| 142 |
+
report = job["dir"] / "report.json"
|
| 143 |
+
if report.exists():
|
| 144 |
+
_relativize(report, run_dir)
|
| 145 |
+
if run_dir.exists(): # the run's evidence moves into the job (so the automation folder never piles up)
|
| 146 |
+
shutil.move(str(run_dir), str(job["dir"] / "run"))
|
| 147 |
+
job["state"] = "cancelled" if job.get("cancel") else "done"
|
| 148 |
+
finally:
|
| 149 |
+
LOCK.release()
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def bundle(job: dict) -> bytes:
|
| 153 |
+
buf = io.BytesIO()
|
| 154 |
+
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
|
| 155 |
+
for name in ("report.json", "testdata-used.jsonl", "created.jsonl", "playwright.log"):
|
| 156 |
+
f = job["dir"] / name
|
| 157 |
+
if f.exists():
|
| 158 |
+
z.write(f, name)
|
| 159 |
+
run = job["dir"] / "run"
|
| 160 |
+
if run.exists():
|
| 161 |
+
for f in run.rglob("*"):
|
| 162 |
+
if f.is_file() and f.name != ".fusion-session.json": # never ship the session cookies
|
| 163 |
+
z.write(f, "run/" + str(f.relative_to(run)).replace("\\", "/"))
|
| 164 |
+
return buf.getvalue()
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def sweep() -> None:
|
| 168 |
+
while True:
|
| 169 |
+
cut = time.time() - KEEP_S
|
| 170 |
+
for jid, job in list(JOBS.items()):
|
| 171 |
+
if job["state"] != "running" and job["started"] < cut:
|
| 172 |
+
shutil.rmtree(job["dir"], ignore_errors=True)
|
| 173 |
+
JOBS.pop(jid, None)
|
| 174 |
+
time.sleep(600)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class H(BaseHTTPRequestHandler):
|
| 178 |
+
server_version = "PatchwiseRunner/1"
|
| 179 |
+
|
| 180 |
+
def log_message(self, fmt, *args): # one quiet line per call, never a header or a body
|
| 181 |
+
print(time.strftime("%H:%M:%S"), self.command, self.path.split("?")[0], args[1] if len(args) > 1 else "", flush=True)
|
| 182 |
+
|
| 183 |
+
def _send(self, code: int, obj=None, raw: bytes | None = None, ctype="application/json"):
|
| 184 |
+
b = raw if raw is not None else json.dumps(obj).encode()
|
| 185 |
+
self.send_response(code)
|
| 186 |
+
self.send_header("Content-Type", ctype)
|
| 187 |
+
self.send_header("Content-Length", str(len(b)))
|
| 188 |
+
self.send_header("Cache-Control", "no-store")
|
| 189 |
+
self.end_headers()
|
| 190 |
+
self.wfile.write(b)
|
| 191 |
+
|
| 192 |
+
def _auth(self) -> bool:
|
| 193 |
+
h = self.headers.get("Authorization", "")
|
| 194 |
+
ok = bool(TOKEN) and h.startswith("Bearer ") and hmac.compare_digest(h[7:].strip(), TOKEN)
|
| 195 |
+
if not ok:
|
| 196 |
+
self._send(401, {"error": "a valid runner token is needed"})
|
| 197 |
+
return ok
|
| 198 |
+
|
| 199 |
+
def _job(self, jid: str):
|
| 200 |
+
job = JOBS.get(jid)
|
| 201 |
+
if not job:
|
| 202 |
+
self._send(404, {"error": "no such attempt"})
|
| 203 |
+
return job
|
| 204 |
+
|
| 205 |
+
def do_GET(self):
|
| 206 |
+
if self.path == "/healthz":
|
| 207 |
+
return self._send(200, {"ok": bool(TOKEN), "busy": LOCK.locked(), "automation": AUTOMATION.exists()})
|
| 208 |
+
if not self._auth():
|
| 209 |
+
return
|
| 210 |
+
m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})(/bundle)?", self.path)
|
| 211 |
+
if not m:
|
| 212 |
+
return self._send(404, {"error": "not found"})
|
| 213 |
+
job = self._job(m.group(1))
|
| 214 |
+
if not job:
|
| 215 |
+
return
|
| 216 |
+
if m.group(2):
|
| 217 |
+
if job["state"] == "running":
|
| 218 |
+
return self._send(409, {"error": "the attempt is still running"})
|
| 219 |
+
return self._send(200, raw=bundle(job), ctype="application/zip")
|
| 220 |
+
self._send(200, {"id": job["id"], "state": job["state"], "exit_code": job["exit_code"], "timed_out": bool(job.get("timed_out")),
|
| 221 |
+
"progress": _progress(job["dir"] / "playwright.log"), "report": (job["dir"] / "report.json").exists()})
|
| 222 |
+
|
| 223 |
+
def do_POST(self):
|
| 224 |
+
if not self._auth():
|
| 225 |
+
return
|
| 226 |
+
n = int(self.headers.get("Content-Length") or 0)
|
| 227 |
+
if n > MAX_BODY:
|
| 228 |
+
return self._send(413, {"error": "body too large"})
|
| 229 |
+
if self.path == "/v1/attempts":
|
| 230 |
+
try:
|
| 231 |
+
body = json.loads(self.rfile.read(n) or b"{}")
|
| 232 |
+
return self._send(202, start(body))
|
| 233 |
+
except BlockingIOError as e:
|
| 234 |
+
return self._send(409, {"error": str(e)})
|
| 235 |
+
except (ValueError, TypeError) as e:
|
| 236 |
+
return self._send(400, {"error": str(e)})
|
| 237 |
+
m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})/cancel", self.path)
|
| 238 |
+
if m:
|
| 239 |
+
job = self._job(m.group(1))
|
| 240 |
+
if job:
|
| 241 |
+
job["cancel"] = True
|
| 242 |
+
self._send(202, {"id": job["id"], "state": "cancelling"})
|
| 243 |
+
return
|
| 244 |
+
self._send(404, {"error": "not found"})
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
if __name__ == "__main__":
|
| 248 |
+
if not TOKEN or len(TOKEN) < 24:
|
| 249 |
+
raise SystemExit("set RUNNER_TOKEN (at least 24 characters)")
|
| 250 |
+
HOME.mkdir(parents=True, exist_ok=True)
|
| 251 |
+
threading.Thread(target=sweep, daemon=True).start()
|
| 252 |
+
print(f"Patchwise remote runner on 127.0.0.1:{PORT}, automation {AUTOMATION}", flush=True)
|
| 253 |
+
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
|
automation/scripts/check-dates.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Checks the Fusion date format logic (src/fusion/dates.ts) without a browser: `npx tsx scripts/check-dates.ts`. */
|
| 2 |
+
import assert from 'node:assert/strict';
|
| 3 |
+
import { formatDate, inferDateFormat, parseDate, reformat } from '../src/fusion/dates';
|
| 4 |
+
|
| 5 |
+
const d = new Date(Date.UTC(2026, 10, 14)); // 14 Nov 2026
|
| 6 |
+
const today = new Date(Date.UTC(2026, 10, 14, 6));
|
| 7 |
+
assert.equal(formatDate(d, 'dd.MM.yyyy'), '14.11.2026');
|
| 8 |
+
assert.equal(formatDate(d, 'M/d/yy'), '11/14/26');
|
| 9 |
+
assert.equal(formatDate(d, 'dd-MMM-yyyy'), '14-Nov-2026');
|
| 10 |
+
assert.equal(parseDate('11/14/26', 'M/d/yy')?.toISOString().slice(0, 10), '2026-11-14');
|
| 11 |
+
assert.equal(parseDate('14/11/26', 'M/d/yy'), null); // no 14th month
|
| 12 |
+
assert.equal(parseDate('31.02.2026', 'dd.MM.yyyy'), null); // no 31 February
|
| 13 |
+
// the demo pod (fa-euth-dev61): Fusion filled Terms Date with 11/14/26
|
| 14 |
+
assert.equal(inferDateFormat(['11/14/26', 'US1 Business Unit', '', '100'], today), 'M/d/yy');
|
| 15 |
+
assert.equal(inferDateFormat(['14.11.2026'], today), 'dd.MM.yyyy');
|
| 16 |
+
assert.equal(inferDateFormat(['14-Nov-2026'], today), 'dd-MMM-yyyy');
|
| 17 |
+
assert.equal(inferDateFormat(['2026-11-14'], today), 'yyyy-MM-dd');
|
| 18 |
+
// 11/10/26 fits both month-first and day-first: the reading nearest today wins (10 Nov, not 11 Oct)
|
| 19 |
+
assert.equal(inferDateFormat(['11/10/26'], new Date(Date.UTC(2026, 10, 12))), 'M/d/yy');
|
| 20 |
+
assert.equal(inferDateFormat(['Payables', '1250.00'], today), null);
|
| 21 |
+
assert.equal(reformat('14.11.2026', 'dd.MM.yyyy', 'M/d/yy'), '11/14/26');
|
| 22 |
+
assert.equal(reformat('TEST_INV_1', 'dd.MM.yyyy', 'M/d/yy'), 'TEST_INV_1');
|
| 23 |
+
console.log('dates: all checks pass');
|
automation/src/fusion/dates.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Fusion shows and takes dates in the signed-in user's own format (their preferences): one pod's user types
|
| 3 |
+
* 14.11.2026, another's 11/14/26. Nothing may assume one. A date is written in the format this run has learned,
|
| 4 |
+
* FUSION_DATE_FORMAT when the pod registration sets it, else dd.MM.yyyy until the page shows otherwise.
|
| 5 |
+
* When Fusion refuses a date, the format is read from the dates Fusion itself shows on the page (Terms Date and the
|
| 6 |
+
* like) and the date is typed again in it (ui.ts put()).
|
| 7 |
+
*/
|
| 8 |
+
|
| 9 |
+
export const DATE_FORMATS = ['dd.MM.yyyy', 'M/d/yy', 'MM/dd/yyyy', 'M/d/yyyy', 'dd/MM/yyyy', 'd/M/yy', 'dd-MMM-yyyy',
|
| 10 |
+
'dd-MMM-yy', 'yyyy-MM-dd', 'dd-MM-yyyy', 'yyyy/MM/dd'] as const;
|
| 11 |
+
const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
| 12 |
+
|
| 13 |
+
let current: string = process.env.FUSION_DATE_FORMAT || 'dd.MM.yyyy';
|
| 14 |
+
export const dateFormat = () => current;
|
| 15 |
+
export const setDateFormat = (f: string) => { current = f; };
|
| 16 |
+
|
| 17 |
+
const pad = (n: number) => String(n).padStart(2, '0');
|
| 18 |
+
|
| 19 |
+
/** The UTC calendar day of `d` in `fmt` (tokens yyyy yy MMM MM M dd d). */
|
| 20 |
+
export function formatDate(d: Date, fmt = current): string {
|
| 21 |
+
return fmt.replace(/yyyy|yy|MMM|MM|M|dd|d/g, (t) => ({
|
| 22 |
+
yyyy: String(d.getUTCFullYear()), yy: pad(d.getUTCFullYear() % 100), MMM: MON[d.getUTCMonth()], MM: pad(d.getUTCMonth() + 1),
|
| 23 |
+
M: String(d.getUTCMonth() + 1), dd: pad(d.getUTCDate()), d: String(d.getUTCDate()),
|
| 24 |
+
}[t] as string));
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
/** `s` read in `fmt` as a UTC date, or null when it does not fit. */
|
| 28 |
+
export function parseDate(s: string, fmt: string): Date | null {
|
| 29 |
+
const order: string[] = [];
|
| 30 |
+
const re = new RegExp('^' + fmt.replace(/[.*+?^${}()|[\]\\/-]/g, '\\$&').replace(/yyyy|yy|MMM|MM|M|dd|d/g, (t) => {
|
| 31 |
+
order.push(t);
|
| 32 |
+
return t === 'MMM' ? '([A-Za-z]{3})' : t === 'yyyy' ? '(\\d{4})' : t.length === 2 ? '(\\d{2})' : '(\\d{1,2})';
|
| 33 |
+
}) + '$');
|
| 34 |
+
const m = re.exec(s.trim());
|
| 35 |
+
if (!m) return null;
|
| 36 |
+
let y = 0, mo = 0, day = 0;
|
| 37 |
+
order.forEach((t, i) => {
|
| 38 |
+
const v = m[i + 1];
|
| 39 |
+
if (t === 'yyyy') y = Number(v);
|
| 40 |
+
else if (t === 'yy') y = 2000 + Number(v);
|
| 41 |
+
else if (t === 'MMM') mo = MON.findIndex((x) => x.toLowerCase() === v.toLowerCase()) + 1;
|
| 42 |
+
else if (t === 'MM' || t === 'M') mo = Number(v);
|
| 43 |
+
else day = Number(v);
|
| 44 |
+
});
|
| 45 |
+
if (mo < 1 || mo > 12 || day < 1 || day > 31) return null;
|
| 46 |
+
const d = new Date(Date.UTC(y, mo - 1, day));
|
| 47 |
+
return d.getUTCDate() === day ? d : null;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
/** The format of dates Fusion shows (`seen`): the one that reads every value as a real date, and when several do
|
| 51 |
+
* (11/10/26 fits M/d/yy and d/M/yy), the one whose dates lie closest to `today`. Null when nothing looks like a date. */
|
| 52 |
+
export function inferDateFormat(seen: string[], today = new Date()): string | null {
|
| 53 |
+
const vals = seen.map((s) => s.trim()).filter((s) => /^[\dA-Za-z]{1,4}[./-][\dA-Za-z]{1,4}[./-][\d]{2,4}$/.test(s));
|
| 54 |
+
if (!vals.length) return null;
|
| 55 |
+
let best: { f: string; dist: number } | null = null;
|
| 56 |
+
for (const f of DATE_FORMATS) {
|
| 57 |
+
const ds = vals.map((v) => parseDate(v, f));
|
| 58 |
+
if (ds.some((d) => !d)) continue;
|
| 59 |
+
const dist = Math.min(...ds.map((d) => Math.abs((d as Date).getTime() - today.getTime())));
|
| 60 |
+
if (!best || dist < best.dist) best = { f, dist };
|
| 61 |
+
}
|
| 62 |
+
return best?.f ?? null;
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
/** `value` (written in `from`) rewritten in `to`; unchanged when it is not a date in `from`. */
|
| 66 |
+
export function reformat(value: string, from: string, to: string): string {
|
| 67 |
+
const d = parseDate(value, from);
|
| 68 |
+
return d ? formatDate(d, to) : value;
|
| 69 |
+
}
|
automation/src/fusion/ui.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import { expect, type Locator, type Page } from '@playwright/test';
|
|
|
|
| 2 |
|
| 3 |
/** A text as a literal inside a regular expression. */
|
| 4 |
const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
@@ -63,8 +64,8 @@ export const apData = () => ({
|
|
| 63 |
* a day ahead of the pod's. */
|
| 64 |
export const podToday = () => new Date(Date.now() - 12 * 3600_000);
|
| 65 |
|
| 66 |
-
/**
|
| 67 |
-
export const fusionDate = (d = podToday()) =>
|
| 68 |
|
| 69 |
/** The invoice status Fusion shows next to the page title (a link opening the validation details). */
|
| 70 |
export const INVOICE_STATUSES = ['Validated', 'Not validated', 'Needs revalidation', 'Canceled', 'Never validated'] as const;
|
|
@@ -395,7 +396,19 @@ export class FusionUi {
|
|
| 395 |
/** Type a value (or choose it in a drop-down list) and leave the field, so Fusion runs its own logic (look-ups,
|
| 396 |
* defaults) as it does for a user. */
|
| 397 |
async put(label: string, value: string) {
|
| 398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
}
|
| 400 |
|
| 401 |
async value(label: string): Promise<string> {
|
|
|
|
| 1 |
import { expect, type Locator, type Page } from '@playwright/test';
|
| 2 |
+
import { dateFormat, formatDate, inferDateFormat, parseDate, reformat, setDateFormat } from './dates';
|
| 3 |
|
| 4 |
/** A text as a literal inside a regular expression. */
|
| 5 |
const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
|
|
| 64 |
* a day ahead of the pod's. */
|
| 65 |
export const podToday = () => new Date(Date.now() - 12 * 3600_000);
|
| 66 |
|
| 67 |
+
/** The UTC calendar day of `d` (default: podToday()) in the date format this run learned for the pod (dates.ts). */
|
| 68 |
+
export const fusionDate = (d = podToday()) => formatDate(d);
|
| 69 |
|
| 70 |
/** The invoice status Fusion shows next to the page title (a link opening the validation details). */
|
| 71 |
export const INVOICE_STATUSES = ['Validated', 'Not validated', 'Needs revalidation', 'Canceled', 'Never validated'] as const;
|
|
|
|
| 396 |
/** Type a value (or choose it in a drop-down list) and leave the field, so Fusion runs its own logic (look-ups,
|
| 397 |
* defaults) as it does for a user. */
|
| 398 |
async put(label: string, value: string) {
|
| 399 |
+
const was = dateFormat();
|
| 400 |
+
try {
|
| 401 |
+
await this.fill(this.field(label), value, label);
|
| 402 |
+
} catch (e) {
|
| 403 |
+
// a date Fusion refused: learn the user's date format from the dates Fusion shows on this page, type it again
|
| 404 |
+
if (!(e instanceof ValueRefused) || !parseDate(value, was)) throw e;
|
| 405 |
+
const seen = await this.page.locator('input').evaluateAll((els) => els.map((el) => (el as HTMLInputElement).value || ''));
|
| 406 |
+
const fmt = inferDateFormat(seen.filter((v) => v.trim() && v.trim() !== value.trim()), podToday());
|
| 407 |
+
if (!fmt || fmt === was) throw e;
|
| 408 |
+
setDateFormat(fmt);
|
| 409 |
+
console.log(`[dates] this pod's user writes dates as ${fmt} (Fusion refused ${value}); typing ${reformat(value, was, fmt)}`);
|
| 410 |
+
await this.fill(this.field(label), reformat(value, was, fmt), label);
|
| 411 |
+
}
|
| 412 |
}
|
| 413 |
|
| 414 |
async value(label: string): Promise<string> {
|
coworker/adapters/remote_runner.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A browser attempt run on the remote runner (automation/remote_runner/server.py) instead of this host.
|
| 2 |
+
|
| 3 |
+
Used for Oracle Fusion pods when FPT_REMOTE_RUNNER_URL is set (and the runner token is in the vault as
|
| 4 |
+
remote_runner.token, or FPT_SECRET_REMOTE_RUNNER_TOKEN): this host may sit on a network Oracle's edge refuses. The
|
| 5 |
+
attempt goes out through the egress gate (https, the runner's host only; the audit log never sees the password), is
|
| 6 |
+
polled, and its bundle is unpacked where a local attempt would leave its files: the JSON report at out_file
|
| 7 |
+
(attachment paths made absolute here), the run directory under automation/results/runs, the pod values tried and the
|
| 8 |
+
ledger of created test records. Everything after that (evidence, triage, clean-up, reports) runs unchanged."""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import io
|
| 12 |
+
import json
|
| 13 |
+
import time
|
| 14 |
+
import zipfile
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
from .playwright import AUTOMATION, testdata_used_file
|
| 18 |
+
|
| 19 |
+
ENV_KEYS = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES",
|
| 20 |
+
"FPT_FUSION_WORKERS", "FPT_BROWSER_SLOWMO_MS")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class RemoteRunnerError(RuntimeError):
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _specs(d: Path | None) -> dict[str, str]:
|
| 28 |
+
if not d or not Path(d).is_dir():
|
| 29 |
+
return {}
|
| 30 |
+
return {p.name: p.read_text(encoding="utf-8") for p in Path(d).glob("*.spec.ts")}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _absolutize(report: Path, run_dir: Path) -> None:
|
| 34 |
+
data = json.loads(report.read_text(encoding="utf-8"))
|
| 35 |
+
|
| 36 |
+
def walk(suites):
|
| 37 |
+
for s in suites or []:
|
| 38 |
+
for sp in s.get("specs") or []:
|
| 39 |
+
for t in sp.get("tests") or []:
|
| 40 |
+
for r in t.get("results") or []:
|
| 41 |
+
for a in r.get("attachments") or []:
|
| 42 |
+
if a.get("path"):
|
| 43 |
+
p = (run_dir / a["path"]).resolve()
|
| 44 |
+
a["path"] = str(p) if p.is_relative_to(run_dir.resolve()) else None
|
| 45 |
+
walk(s.get("suites"))
|
| 46 |
+
walk(data.get("suites"))
|
| 47 |
+
report.write_text(json.dumps(data), encoding="utf-8")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: str, attempt: int) -> bool:
|
| 51 |
+
with zipfile.ZipFile(io.BytesIO(blob)) as z:
|
| 52 |
+
for info in z.infolist():
|
| 53 |
+
name = info.filename
|
| 54 |
+
if info.is_dir():
|
| 55 |
+
continue
|
| 56 |
+
if name.startswith("run/"):
|
| 57 |
+
dest = (run_dir / name[4:]).resolve()
|
| 58 |
+
if not dest.is_relative_to(run_dir.resolve()): # a path that climbs out of the run directory is dropped
|
| 59 |
+
continue
|
| 60 |
+
else:
|
| 61 |
+
dest = {"report.json": out_file, "testdata-used.jsonl": testdata_used_file(out_file),
|
| 62 |
+
"created.jsonl": log_dir / ledger, "playwright.log": log_dir / f"playwright-a{attempt}.log"}.get(name)
|
| 63 |
+
if dest is None:
|
| 64 |
+
continue
|
| 65 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 66 |
+
dest.write_bytes(z.read(info))
|
| 67 |
+
if out_file.exists():
|
| 68 |
+
_absolutize(out_file, run_dir)
|
| 69 |
+
return True
|
| 70 |
+
return False
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: list[str], attempt: int, out_file: Path,
|
| 74 |
+
cred_env: dict | None, drafts_dir: Path | None, library_dir: Path | None, overrides_file: Path | None,
|
| 75 |
+
log_dir: Path, config: str, timeout_s: int = 3600, kill=None, poll_s: float = 5.0) -> dict:
|
| 76 |
+
from ..platform.cleanup import LEDGER
|
| 77 |
+
from ..platform.failures import ExecutionError
|
| 78 |
+
base = base_url.rstrip("/")
|
| 79 |
+
hdr = {"Authorization": f"Bearer {token}"}
|
| 80 |
+
pw_run_id = f"fpt-{run_id}-a{attempt}"
|
| 81 |
+
env = {k: str(v) for k, v in (cred_env or {}).items() if k in ENV_KEYS}
|
| 82 |
+
if overrides_file and Path(overrides_file).exists():
|
| 83 |
+
ov = json.loads(Path(overrides_file).read_text(encoding="utf-8") or "{}")
|
| 84 |
+
if ov:
|
| 85 |
+
env["PW_LOCATOR_OVERRIDES"] = json.dumps(ov)
|
| 86 |
+
body = {"ids": ids, "pw_run_id": pw_run_id, "config": config, "env": env, "timeout_s": timeout_s,
|
| 87 |
+
"drafts": _specs(drafts_dir), "library": _specs(library_dir)}
|
| 88 |
+
r = egress.service_request("remote_runner", "POST", base + "/v1/attempts", allowed_base=base, json_body=body, headers=hdr,
|
| 89 |
+
log_body={"ids": ids, "config": config, "pw_run_id": pw_run_id, "specs": len(body["drafts"]) + len(body["library"])},
|
| 90 |
+
timeout=60)
|
| 91 |
+
if r.status_code != 202:
|
| 92 |
+
raise RemoteRunnerError(f"the remote browser runner refused the attempt (HTTP {r.status_code}: {r.text[:200]})")
|
| 93 |
+
jid = r.json()["id"]
|
| 94 |
+
deadline = time.time() + timeout_s + 300
|
| 95 |
+
st = {}
|
| 96 |
+
while True:
|
| 97 |
+
try:
|
| 98 |
+
if kill:
|
| 99 |
+
kill()
|
| 100 |
+
except BaseException:
|
| 101 |
+
egress.service_request("remote_runner", "POST", f"{base}/v1/attempts/{jid}/cancel", allowed_base=base, headers=hdr,
|
| 102 |
+
log_body={"cancel": jid}, timeout=30)
|
| 103 |
+
raise
|
| 104 |
+
time.sleep(poll_s)
|
| 105 |
+
try:
|
| 106 |
+
st = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}", allowed_base=base, headers=hdr,
|
| 107 |
+
log_body=None, timeout=30).json()
|
| 108 |
+
except Exception: # noqa: BLE001 - a dropped poll is tried again; the attempt keeps running on the runner
|
| 109 |
+
st = {}
|
| 110 |
+
if st.get("state") in ("done", "cancelled"):
|
| 111 |
+
break
|
| 112 |
+
if time.time() > deadline:
|
| 113 |
+
raise ExecutionError("The remote browser runner did not finish the attempt in time.", timed_out=True, minutes=timeout_s // 60)
|
| 114 |
+
z = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}/bundle", allowed_base=base, headers=hdr,
|
| 115 |
+
log_body=None, timeout=300)
|
| 116 |
+
if z.status_code != 200:
|
| 117 |
+
raise RemoteRunnerError(f"the remote browser runner did not return the results (HTTP {z.status_code})")
|
| 118 |
+
run_dir = AUTOMATION / "results" / "runs" / pw_run_id
|
| 119 |
+
if not _unpack(z.content, Path(out_file), run_dir, Path(log_dir), LEDGER, attempt):
|
| 120 |
+
raise ExecutionError(f"The remote browser run produced no report (exit {st.get('exit_code')}), so no scenario result was recorded.",
|
| 121 |
+
exit_code=st.get("exit_code"), timed_out=bool(st.get("timed_out")), minutes=max(1, timeout_s // 60))
|
| 122 |
+
return {"file": str(out_file), "pw_run_id": pw_run_id, "run_dir": str(run_dir), "exit_code": st.get("exit_code"),
|
| 123 |
+
"mode": "live", "timed_out": bool(st.get("timed_out")), "remote": True}
|
coworker/config.py
CHANGED
|
@@ -151,6 +151,9 @@ class Settings(BaseSettings):
|
|
| 151 |
scout_personas: dict[str, str] = Field(default_factory=lambda: {"default": "auditor_ro", "p2p": "buyer"})
|
| 152 |
|
| 153 |
playwright_mode: Literal["stub", "live"] = "live"
|
|
|
|
|
|
|
|
|
|
| 154 |
executor_backend: Literal["local"] = "local" # "docker" is not implemented: rejected at startup, never mid-run
|
| 155 |
llm_local: Literal["stub", "ollama"] = "stub"
|
| 156 |
ollama_url: str = "http://127.0.0.1:11434"
|
|
|
|
| 151 |
scout_personas: dict[str, str] = Field(default_factory=lambda: {"default": "auditor_ro", "p2p": "buyer"})
|
| 152 |
|
| 153 |
playwright_mode: Literal["stub", "live"] = "live"
|
| 154 |
+
# Browser attempts on an Oracle Fusion pod run on this remote runner (automation/remote_runner) when set: for a host
|
| 155 |
+
# whose network Oracle's edge refuses. Its token: vault remote_runner.token (FPT_SECRET_REMOTE_RUNNER_TOKEN).
|
| 156 |
+
remote_runner_url: str = Field("", validation_alias=_alias("fpt_remote_runner_url", "remote_runner_url"))
|
| 157 |
executor_backend: Literal["local"] = "local" # "docker" is not implemented: rejected at startup, never mid-run
|
| 158 |
llm_local: Literal["stub", "ollama"] = "stub"
|
| 159 |
ollama_url: str = "http://127.0.0.1:11434"
|
coworker/graph/nodes/execute.py
CHANGED
|
@@ -106,6 +106,17 @@ def plan_attempt(state, svc, clean: bool = True) -> dict:
|
|
| 106 |
|
| 107 |
def run_planned(plan: dict, svc, **extra) -> dict:
|
| 108 |
"""Default runner: one Playwright invocation for the whole attempt (LangGraph path)."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
if plan["mode"] == "live" and not plan.get("config"):
|
| 110 |
pw.ensure_mock(svc.egress, svc.cfg.pod_base_url, svc.cfg.path("logs"))
|
| 111 |
if plan.get("config"):
|
|
|
|
| 106 |
|
| 107 |
def run_planned(plan: dict, svc, **extra) -> dict:
|
| 108 |
"""Default runner: one Playwright invocation for the whole attempt (LangGraph path)."""
|
| 109 |
+
remote = (svc.cfg.remote_runner_url or "").strip()
|
| 110 |
+
if remote and plan["mode"] == "live" and plan.get("config") == "playwright.fusion.config.ts":
|
| 111 |
+
from ...adapters.remote_runner import run_attempt_remote # Oracle's edge refuses this host: the browser runs there
|
| 112 |
+
token = svc.vault.get("remote_runner.token") or ""
|
| 113 |
+
if token:
|
| 114 |
+
svc.redactor.add_secrets([token])
|
| 115 |
+
return run_attempt_remote(svc.egress, remote, token, run_id=plan["run_id"], ids=plan["ids"], attempt=plan["attempt"],
|
| 116 |
+
out_file=Path(plan["out_file"]), cred_env=plan["cred_env"], drafts_dir=Path(plan["drafts_dir"]),
|
| 117 |
+
library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
|
| 118 |
+
overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, log_dir=Path(plan["run_dir"]),
|
| 119 |
+
config=plan["config"], kill=lambda: svc.kill.check("executor.remote"))
|
| 120 |
if plan["mode"] == "live" and not plan.get("config"):
|
| 121 |
pw.ensure_mock(svc.egress, svc.cfg.pod_base_url, svc.cfg.path("logs"))
|
| 122 |
if plan.get("config"):
|
coworker/tests/test_remote_runner.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Browser attempts on a remote runner (automation/remote_runner): the attempt goes out through the egress gate without
|
| 2 |
+
the password in the audit, is polled, and its bundle is unpacked where a local attempt leaves its files; a path that
|
| 3 |
+
climbs out of the run directory is dropped; the runner checks its token and never ships the session cookies."""
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import importlib.util
|
| 7 |
+
import io
|
| 8 |
+
import json
|
| 9 |
+
import tempfile
|
| 10 |
+
import unittest
|
| 11 |
+
import zipfile
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import httpx
|
| 15 |
+
|
| 16 |
+
from coworker.adapters import remote_runner as R
|
| 17 |
+
|
| 18 |
+
REPORT = {"suites": [{"specs": [{"title": "AP-FUS-001 x", "tags": ["@AP-FUS-001"], "tests": [{"results": [
|
| 19 |
+
{"status": "passed", "attachments": [{"name": "screenshot", "path": "artifacts/AP-FUS-001/test-finished-1.png", "contentType": "image/png"},
|
| 20 |
+
{"name": "evil", "path": "../../outside.txt"}]}]}]}]}]}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def bundle() -> bytes:
|
| 24 |
+
buf = io.BytesIO()
|
| 25 |
+
with zipfile.ZipFile(buf, "w") as z:
|
| 26 |
+
z.writestr("report.json", json.dumps(REPORT))
|
| 27 |
+
z.writestr("testdata-used.jsonl", '{"area":"AP"}\n')
|
| 28 |
+
z.writestr("created.jsonl", '{"invoice":"TEST_1"}\n')
|
| 29 |
+
z.writestr("playwright.log", "[1/1] AP-FUS-001\n")
|
| 30 |
+
z.writestr("run/artifacts/AP-FUS-001/test-finished-1.png", b"png")
|
| 31 |
+
z.writestr("run/../../escape.txt", b"nope")
|
| 32 |
+
return buf.getvalue()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class FakeEgress:
|
| 36 |
+
def __init__(self):
|
| 37 |
+
self.calls, self.polls = [], 0
|
| 38 |
+
|
| 39 |
+
def service_request(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None, timeout=30.0, log_url=None):
|
| 40 |
+
self.calls.append({"method": method, "url": url, "body": json_body, "log": log_body, "auth": (headers or {}).get("Authorization")})
|
| 41 |
+
assert kind == "remote_runner" and url.startswith(allowed_base)
|
| 42 |
+
if method == "POST" and url.endswith("/v1/attempts"):
|
| 43 |
+
return httpx.Response(202, json={"id": "job_0123456789ab", "state": "running"})
|
| 44 |
+
if url.endswith("/bundle"):
|
| 45 |
+
return httpx.Response(200, content=bundle())
|
| 46 |
+
self.polls += 1
|
| 47 |
+
return httpx.Response(200, json={"state": "done" if self.polls > 1 else "running", "exit_code": 0})
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class TestRemoteAttempt(unittest.TestCase):
|
| 51 |
+
def test_an_attempt_runs_remotely_and_lands_like_a_local_one(self):
|
| 52 |
+
eg = FakeEgress()
|
| 53 |
+
with tempfile.TemporaryDirectory() as d:
|
| 54 |
+
d = Path(d)
|
| 55 |
+
out = d / "attempt-0.json"
|
| 56 |
+
res = R.run_attempt_remote(eg, "https://runner.example", "tok-" + "x" * 30, run_id="r1", ids=["AP-FUS-001"], attempt=0,
|
| 57 |
+
out_file=out, cred_env={"FUSION_BASE_URL": "https://fa.example", "FUSION_USERNAME": "u",
|
| 58 |
+
"FUSION_PASSWORD": "s3cret", "UNRELATED": "x"},
|
| 59 |
+
drafts_dir=d / "none", library_dir=None, overrides_file=None, log_dir=d, config="playwright.fusion.config.ts",
|
| 60 |
+
poll_s=0.01)
|
| 61 |
+
post = eg.calls[0]
|
| 62 |
+
self.assertEqual(post["body"]["env"]["FUSION_PASSWORD"], "s3cret") # the runner needs it
|
| 63 |
+
self.assertNotIn("UNRELATED", post["body"]["env"])
|
| 64 |
+
self.assertNotIn("s3cret", json.dumps([c["log"] for c in eg.calls])) # the audit never sees it
|
| 65 |
+
self.assertEqual(post["auth"], "Bearer tok-" + "x" * 30)
|
| 66 |
+
self.assertEqual(res["pw_run_id"], "fpt-r1-a0")
|
| 67 |
+
rep = json.loads(out.read_text())
|
| 68 |
+
atts = rep["suites"][0]["specs"][0]["tests"][0]["results"][0]["attachments"]
|
| 69 |
+
shot = Path(atts[0]["path"])
|
| 70 |
+
self.assertTrue(shot.is_absolute() and shot.read_bytes() == b"png")
|
| 71 |
+
self.assertIsNone(atts[1]["path"]) # outside the run directory: dropped
|
| 72 |
+
self.assertTrue((d / "testdata-used.jsonl").exists() and (d / "created-test-data.jsonl").exists())
|
| 73 |
+
run_dir = Path(res["run_dir"])
|
| 74 |
+
self.assertFalse((run_dir.parent.parent / "escape.txt").exists())
|
| 75 |
+
import shutil
|
| 76 |
+
shutil.rmtree(Path(res["run_dir"]), ignore_errors=True)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def load_server():
|
| 80 |
+
p = Path(__file__).resolve().parents[2] / "automation" / "remote_runner" / "server.py"
|
| 81 |
+
spec = importlib.util.spec_from_file_location("pw_remote_runner", p)
|
| 82 |
+
m = importlib.util.module_from_spec(spec)
|
| 83 |
+
spec.loader.exec_module(m)
|
| 84 |
+
return m
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class TestRunnerServer(unittest.TestCase):
|
| 88 |
+
def test_reports_become_relative_and_the_session_is_never_shipped(self):
|
| 89 |
+
S = load_server()
|
| 90 |
+
with tempfile.TemporaryDirectory() as d:
|
| 91 |
+
d = Path(d)
|
| 92 |
+
run = d / "run"
|
| 93 |
+
(run / "artifacts").mkdir(parents=True)
|
| 94 |
+
(run / "artifacts" / "a.png").write_bytes(b"png")
|
| 95 |
+
(run / ".fusion-session.json").write_text("{cookies}")
|
| 96 |
+
rep = d / "report.json"
|
| 97 |
+
rep.write_text(json.dumps({"suites": [{"specs": [{"tests": [{"results": [{"attachments": [
|
| 98 |
+
{"path": str(run / "artifacts" / "a.png")}, {"path": str(d.parent / "elsewhere.png")}]}]}]}]}]}))
|
| 99 |
+
S._relativize(rep, run)
|
| 100 |
+
atts = json.loads(rep.read_text())["suites"][0]["specs"][0]["tests"][0]["results"][0]["attachments"]
|
| 101 |
+
self.assertEqual([a["path"] for a in atts], ["artifacts/a.png", None])
|
| 102 |
+
names = zipfile.ZipFile(io.BytesIO(S.bundle({"dir": d}))).namelist()
|
| 103 |
+
self.assertIn("run/artifacts/a.png", names)
|
| 104 |
+
self.assertNotIn("run/.fusion-session.json", names)
|
| 105 |
+
|
| 106 |
+
def test_attempts_are_checked(self):
|
| 107 |
+
S = load_server()
|
| 108 |
+
for bad in ({"ids": [], "pw_run_id": "x"}, {"ids": ["AP-1; rm -rf /"], "pw_run_id": "x"},
|
| 109 |
+
{"ids": ["AP-FUS-001"], "pw_run_id": "x", "config": "/etc/passwd"}):
|
| 110 |
+
with self.assertRaises(ValueError):
|
| 111 |
+
S.start(bad)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
unittest.main()
|
docs/REMOTE_RUNNER.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Remote browser runner
|
| 2 |
+
|
| 3 |
+
Use the remote runner when the Patchwise server's network is refused by Oracle's edge. For example, Hugging Face Spaces
|
| 4 |
+
get "Access Denied" from Akamai on Oracle demo pods. With the runner, the browser part of runs on an Oracle Fusion pod
|
| 5 |
+
happens on another host. Everything else stays where it is: approvals, AI agents, triage, reports and evidence.
|
| 6 |
+
|
| 7 |
+
- **Server side:** `coworker/adapters/remote_runner.py`, wired in `coworker/graph/nodes/execute.py` (`run_planned`).
|
| 8 |
+
- **Runner side:** `automation/remote_runner/server.py` (standard library only).
|
| 9 |
+
- **Scope:** only browser attempts on a Fusion pod (`playwright.fusion.config.ts`) go to the runner. The practice pod
|
| 10 |
+
and stub runs stay local.
|
| 11 |
+
|
| 12 |
+
## How it works
|
| 13 |
+
|
| 14 |
+
1. **The attempt is sent.** Patchwise posts it through the egress gate (https, the runner's host only) to
|
| 15 |
+
`POST /v1/attempts`. The body holds:
|
| 16 |
+
- the case ids and the Playwright config;
|
| 17 |
+
- the pod environment (address, test user, test data);
|
| 18 |
+
- AI-written draft specs and approved library specs;
|
| 19 |
+
- locator overrides from self-heal.
|
| 20 |
+
|
| 21 |
+
The audit log records the ids and the config, never the password.
|
| 22 |
+
2. **It is polled.** Patchwise asks `GET /v1/attempts/{id}` every few seconds. The emergency stop cancels the attempt
|
| 23 |
+
on the runner.
|
| 24 |
+
3. **The results come back.** `GET /v1/attempts/{id}/bundle` returns one zip with:
|
| 25 |
+
- the Playwright JSON report, with attachment paths relative to the run directory;
|
| 26 |
+
- the run directory (screenshots, videos, traces);
|
| 27 |
+
- the pod values tried;
|
| 28 |
+
- the ledger of created test records;
|
| 29 |
+
- the log.
|
| 30 |
+
|
| 31 |
+
Patchwise unpacks it where a local attempt leaves its files, so evidence, triage, clean-up and reports work unchanged.
|
| 32 |
+
|
| 33 |
+
**The runner's safeguards:**
|
| 34 |
+
|
| 35 |
+
- It runs one attempt at a time.
|
| 36 |
+
- Every call needs `Authorization: Bearer <RUNNER_TOKEN>`, compared in constant time.
|
| 37 |
+
- It accepts only known environment keys, the Patchwise configs, plain case ids and plain spec names.
|
| 38 |
+
- It never ships the Fusion session cookies.
|
| 39 |
+
- It deletes finished attempts after 24 hours.
|
| 40 |
+
- The password exists only in the Playwright process's environment, never on disk.
|
| 41 |
+
|
| 42 |
+
## Set up a runner (Ubuntu 22.04)
|
| 43 |
+
|
| 44 |
+
**1. Install the tools and the test suite.** Install Node 22 and Python 3, then copy the same version of the code that
|
| 45 |
+
the Patchwise server runs:
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
git archive main automation tests | tar -x -C ~/pw # from the repository
|
| 49 |
+
cd ~/pw/automation && npm ci && npx playwright install --with-deps chromium
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
**2. Store the token.** It needs at least 24 random characters. Keep it in a root-only file, `/etc/patchwise/runner.env`:
|
| 53 |
+
|
| 54 |
+
```
|
| 55 |
+
RUNNER_TOKEN=<random>
|
| 56 |
+
AUTOMATION_DIR=/home/ubuntu/pw/automation
|
| 57 |
+
RUNNER_HOME=/home/ubuntu/runner-data
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
**3. Run the service.** It listens on `127.0.0.1:8899`. Use a systemd unit with `User=ubuntu`, the environment file,
|
| 61 |
+
`ExecStart=/usr/bin/python3 -I /home/ubuntu/pw/automation/remote_runner/server.py` and `Restart=always`.
|
| 62 |
+
|
| 63 |
+
**4. Put HTTPS in front.** Caddy can serve a real certificate for an IP using `<ip-with-dashes>.sslip.io`:
|
| 64 |
+
|
| 65 |
+
```
|
| 66 |
+
129-225-117-95.sslip.io {
|
| 67 |
+
reverse_proxy 127.0.0.1:8899
|
| 68 |
+
}
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Open ports 80 and 443 in the cloud firewall. On Oracle's Ubuntu images, also open them in iptables.
|
| 72 |
+
|
| 73 |
+
**5. Point the Patchwise server at the runner.** Set:
|
| 74 |
+
|
| 75 |
+
- `FPT_REMOTE_RUNNER_URL=https://<host>`, as an environment variable;
|
| 76 |
+
- `FPT_SECRET_REMOTE_RUNNER_TOKEN=<the token>`, as a secret.
|
| 77 |
+
|
| 78 |
+
Remove `FPT_REMOTE_RUNNER_URL` to run browsers on the server itself again.
|
| 79 |
+
|
| 80 |
+
The first runner is the OCI Always Free AMD Micro VM `patchwise-watcher` (1 GB RAM plus 2 GB swap): enough for one
|
| 81 |
+
browser. Keep `FPT_FUSION_WORKERS=1` there.
|