Screens read on the remote runner; pod release from settings (f786c75)
Browse files- automation/remote_runner/server.py +67 -5
- coworker/adapters/remote_runner.py +68 -0
- coworker/adapters/screens.py +77 -41
- coworker/api/routes/screens.py +1 -1
- coworker/config.py +2 -0
- coworker/platform/pods.py +11 -2
- coworker/tests/test_pods.py +11 -0
- coworker/tests/test_remote_screens.py +123 -0
- docs/REMOTE_RUNNER.md +20 -3
automation/remote_runner/server.py
CHANGED
|
@@ -125,6 +125,60 @@ def start(body: dict) -> dict:
|
|
| 125 |
raise
|
| 126 |
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
def _watch(job: dict) -> None:
|
| 129 |
p = job["proc"]
|
| 130 |
try:
|
|
@@ -156,6 +210,11 @@ def bundle(job: dict) -> bytes:
|
|
| 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("*"):
|
|
@@ -207,7 +266,7 @@ class H(BaseHTTPRequestHandler):
|
|
| 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))
|
|
@@ -217,8 +276,11 @@ class H(BaseHTTPRequestHandler):
|
|
| 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 |
-
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
def do_POST(self):
|
| 224 |
if not self._auth():
|
|
@@ -226,10 +288,10 @@ class H(BaseHTTPRequestHandler):
|
|
| 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
|
| 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:
|
|
|
|
| 125 |
raise
|
| 126 |
|
| 127 |
|
| 128 |
+
SCREEN_SCRIPTS = {"explore": "scripts/explore-fusion.ts", "capture": "scripts/capture-fusion.ts"}
|
| 129 |
+
SCREEN_ENV = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA")
|
| 130 |
+
TASK = re.compile(r"^[^\r\n<>]{5,250}$")
|
| 131 |
+
OUT_FILE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,160}\.(json|values)$")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def start_screens(body: dict) -> dict:
|
| 135 |
+
"""Read a pod's screens (labels only): "explore" with a plan of areas, or "capture" of one "Area > Page > Task".
|
| 136 |
+
Same lock as the attempts (one browser); the files land in the job's out/ folder and come back in the bundle."""
|
| 137 |
+
kind = str(body.get("kind") or "")
|
| 138 |
+
if kind not in SCREEN_SCRIPTS:
|
| 139 |
+
raise ValueError(f"kind is one of {sorted(SCREEN_SCRIPTS)}")
|
| 140 |
+
env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in SCREEN_ENV}
|
| 141 |
+
if not all(env_in.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):
|
| 142 |
+
raise ValueError("env needs FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD")
|
| 143 |
+
task = str(body.get("task") or "")
|
| 144 |
+
if kind == "capture" and not TASK.match(task):
|
| 145 |
+
raise ValueError('task is "Area > Page > Task"')
|
| 146 |
+
if kind == "explore" and not isinstance(body.get("plan"), dict):
|
| 147 |
+
raise ValueError("plan is the explorer's plan (an object)")
|
| 148 |
+
if not LOCK.acquire(blocking=False):
|
| 149 |
+
raise BlockingIOError("another attempt is running on this runner")
|
| 150 |
+
try:
|
| 151 |
+
jid = "job_" + secrets.token_hex(6)
|
| 152 |
+
jd = HOME / jid
|
| 153 |
+
(jd / "out").mkdir(parents=True)
|
| 154 |
+
arg = task
|
| 155 |
+
if kind == "explore":
|
| 156 |
+
(jd / "plan.json").write_text(json.dumps(body["plan"]), encoding="utf-8")
|
| 157 |
+
arg = str(jd / "plan.json")
|
| 158 |
+
env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)}
|
| 159 |
+
env.update(env_in)
|
| 160 |
+
cmd = ["node", str(AUTOMATION / "node_modules" / "tsx" / "dist" / "cli.mjs"), SCREEN_SCRIPTS[kind], arg, "--out-dir", str(jd / "out")]
|
| 161 |
+
log = open(jd / "playwright.log", "wb")
|
| 162 |
+
p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
| 163 |
+
job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": jid, "started": time.time(), "kind": kind,
|
| 164 |
+
"deadline": time.time() + min(float(body.get("timeout_s") or 5400), 4 * 3600), "state": "running", "exit_code": None}
|
| 165 |
+
JOBS[jid] = job
|
| 166 |
+
threading.Thread(target=_watch, args=(job,), daemon=True).start()
|
| 167 |
+
return {"id": jid, "state": "running"}
|
| 168 |
+
except BaseException:
|
| 169 |
+
LOCK.release()
|
| 170 |
+
raise
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _lines(log: Path, since: int) -> tuple[list[str], int]:
|
| 174 |
+
"""The log's lines from `since` on (at most 200), and how many lines it has."""
|
| 175 |
+
try:
|
| 176 |
+
lines = log.read_text(encoding="utf-8", errors="replace").splitlines()
|
| 177 |
+
except OSError:
|
| 178 |
+
return [], 0
|
| 179 |
+
return [ln[:500] for ln in lines[since:since + 200]], len(lines)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
def _watch(job: dict) -> None:
|
| 183 |
p = job["proc"]
|
| 184 |
try:
|
|
|
|
| 210 |
f = job["dir"] / name
|
| 211 |
if f.exists():
|
| 212 |
z.write(f, name)
|
| 213 |
+
out = job["dir"] / "out" # a screen read: the inventories (labels) and the list choices it found
|
| 214 |
+
if out.exists():
|
| 215 |
+
for f in out.iterdir():
|
| 216 |
+
if f.is_file() and OUT_FILE.match(f.name):
|
| 217 |
+
z.write(f, "out/" + f.name)
|
| 218 |
run = job["dir"] / "run"
|
| 219 |
if run.exists():
|
| 220 |
for f in run.rglob("*"):
|
|
|
|
| 266 |
return self._send(200, {"ok": bool(TOKEN), "busy": LOCK.locked(), "automation": AUTOMATION.exists()})
|
| 267 |
if not self._auth():
|
| 268 |
return
|
| 269 |
+
m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})(/bundle)?(?:\?since=(\d{1,7}))?", self.path)
|
| 270 |
if not m:
|
| 271 |
return self._send(404, {"error": "not found"})
|
| 272 |
job = self._job(m.group(1))
|
|
|
|
| 276 |
if job["state"] == "running":
|
| 277 |
return self._send(409, {"error": "the attempt is still running"})
|
| 278 |
return self._send(200, raw=bundle(job), ctype="application/zip")
|
| 279 |
+
st = {"id": job["id"], "state": job["state"], "exit_code": job["exit_code"], "timed_out": bool(job.get("timed_out")),
|
| 280 |
+
"progress": _progress(job["dir"] / "playwright.log"), "report": (job["dir"] / "report.json").exists()}
|
| 281 |
+
if m.group(3) is not None: # a screen read follows its log lines ("[explore] ...") for its progress
|
| 282 |
+
st["lines"], st["line_count"] = _lines(job["dir"] / "playwright.log", int(m.group(3)))
|
| 283 |
+
self._send(200, st)
|
| 284 |
|
| 285 |
def do_POST(self):
|
| 286 |
if not self._auth():
|
|
|
|
| 288 |
n = int(self.headers.get("Content-Length") or 0)
|
| 289 |
if n > MAX_BODY:
|
| 290 |
return self._send(413, {"error": "body too large"})
|
| 291 |
+
if self.path in ("/v1/attempts", "/v1/screens"):
|
| 292 |
try:
|
| 293 |
body = json.loads(self.rfile.read(n) or b"{}")
|
| 294 |
+
return self._send(202, start(body) if self.path == "/v1/attempts" else start_screens(body))
|
| 295 |
except BlockingIOError as e:
|
| 296 |
return self._send(409, {"error": str(e)})
|
| 297 |
except (ValueError, TypeError) as e:
|
coworker/adapters/remote_runner.py
CHANGED
|
@@ -70,6 +70,74 @@ def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: s
|
|
| 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:
|
|
|
|
| 70 |
return False
|
| 71 |
|
| 72 |
|
| 73 |
+
def runner_for(svc) -> tuple[str, str] | None:
|
| 74 |
+
"""(runner address, token) when this server sends Fusion browsers to a remote runner (FPT_REMOTE_RUNNER_URL), else None.
|
| 75 |
+
`svc` is anything with cfg and vault (Services, PodRegistry); its redactor, when it has one, learns the token."""
|
| 76 |
+
base = (getattr(svc.cfg, "remote_runner_url", "") or "").strip()
|
| 77 |
+
if not base:
|
| 78 |
+
return None
|
| 79 |
+
token = svc.vault.get("remote_runner.token") or ""
|
| 80 |
+
if token and getattr(svc, "redactor", None):
|
| 81 |
+
svc.redactor.add_secrets([token])
|
| 82 |
+
return base.rstrip("/"), token
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
SCREEN_ENV = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def run_screens_remote(egress, base_url: str, token: str, *, kind: str, env: dict, out_dir: Path, plan: dict | None = None,
|
| 89 |
+
task: str | None = None, timeout_s: int = 5400, on_line=None, poll_s: float = 5.0) -> tuple[int | None, list[str]]:
|
| 90 |
+
"""Read the pod's screens on the runner ("explore" with a plan, "capture" of one task). The files it wrote (inventories
|
| 91 |
+
and list choices) land in out_dir; returns (exit code, the log's lines). on_line gets each new line as it comes."""
|
| 92 |
+
base = base_url.rstrip("/")
|
| 93 |
+
hdr = {"Authorization": f"Bearer {token}"}
|
| 94 |
+
body = {"kind": kind, "env": {k: str(v) for k, v in (env or {}).items() if k in SCREEN_ENV and v}, "timeout_s": timeout_s,
|
| 95 |
+
**({"plan": plan} if plan is not None else {}), **({"task": task} if task else {})}
|
| 96 |
+
r = egress.service_request("remote_runner", "POST", base + "/v1/screens", allowed_base=base, json_body=body, headers=hdr,
|
| 97 |
+
log_body={"kind": kind, "task": task, "areas": [a.get("code") for a in (plan or {}).get("areas") or [] if isinstance(a, dict)]},
|
| 98 |
+
timeout=60)
|
| 99 |
+
if r.status_code != 202:
|
| 100 |
+
raise RemoteRunnerError(f"the remote browser runner refused the screen read (HTTP {r.status_code}: {r.text[:200]})")
|
| 101 |
+
jid = r.json()["id"]
|
| 102 |
+
deadline = time.time() + timeout_s + 300
|
| 103 |
+
seen, st = 0, {}
|
| 104 |
+
while True:
|
| 105 |
+
time.sleep(poll_s)
|
| 106 |
+
try:
|
| 107 |
+
st = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}?since={seen}", allowed_base=base, headers=hdr,
|
| 108 |
+
log_body=None, timeout=30).json()
|
| 109 |
+
except Exception: # noqa: BLE001 - a dropped poll is tried again; the read keeps going on the runner
|
| 110 |
+
st = {}
|
| 111 |
+
new = st.get("lines") or []
|
| 112 |
+
seen += len(new)
|
| 113 |
+
if on_line:
|
| 114 |
+
for line in new:
|
| 115 |
+
on_line(line)
|
| 116 |
+
if st.get("state") in ("done", "cancelled"):
|
| 117 |
+
break
|
| 118 |
+
if time.time() > deadline:
|
| 119 |
+
egress.service_request("remote_runner", "POST", f"{base}/v1/attempts/{jid}/cancel", allowed_base=base, headers=hdr,
|
| 120 |
+
log_body={"cancel": jid}, timeout=30)
|
| 121 |
+
raise RemoteRunnerError(f"the remote browser runner did not finish reading the screens in {timeout_s // 60} minutes")
|
| 122 |
+
z = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}/bundle", allowed_base=base, headers=hdr,
|
| 123 |
+
log_body=None, timeout=300)
|
| 124 |
+
if z.status_code != 200:
|
| 125 |
+
raise RemoteRunnerError(f"the remote browser runner did not return the screens (HTTP {z.status_code})")
|
| 126 |
+
out = Path(out_dir)
|
| 127 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 128 |
+
lines: list[str] = []
|
| 129 |
+
with zipfile.ZipFile(io.BytesIO(z.content)) as zf:
|
| 130 |
+
for info in zf.infolist():
|
| 131 |
+
name = info.filename
|
| 132 |
+
if name == "playwright.log":
|
| 133 |
+
lines = zf.read(info).decode("utf-8", "replace").splitlines()
|
| 134 |
+
elif name.startswith("out/") and "/" not in name[4:] and name.endswith((".json", ".values")) and not name[4:].startswith("."):
|
| 135 |
+
dest = (out / name[4:]).resolve()
|
| 136 |
+
if dest.is_relative_to(out.resolve()):
|
| 137 |
+
dest.write_bytes(zf.read(info))
|
| 138 |
+
return st.get("exit_code"), lines
|
| 139 |
+
|
| 140 |
+
|
| 141 |
def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: list[str], attempt: int, out_file: Path,
|
| 142 |
cred_env: dict | None, drafts_dir: Path | None, library_dir: Path | None, overrides_file: Path | None,
|
| 143 |
log_dir: Path, config: str, timeout_s: int = 3600, kill=None, poll_s: float = 5.0) -> dict:
|
coworker/adapters/screens.py
CHANGED
|
@@ -89,9 +89,18 @@ def _scrub(text: str, env: dict) -> str:
|
|
| 89 |
return text
|
| 90 |
|
| 91 |
|
| 92 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
"""Run the capture CLI against the pod in `env` (FUSION_BASE_URL/USERNAME/PASSWORD from PodRegistry.executor_env)
|
| 94 |
-
and return the stored inventory. Nothing is saved on the pod; the credentials go to the child process only.
|
|
|
|
| 95 |
task = normalize_task(task)
|
| 96 |
if not all(env.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):
|
| 97 |
raise ScreenError("NO_CREDENTIALS", "the pod's address and test user are needed to capture a screen", 409)
|
|
@@ -100,24 +109,34 @@ def capture(task: str, env: dict, *, out_dir: Path | None = None, timeout_s: int
|
|
| 100 |
try:
|
| 101 |
out = Path(out_dir or screens_dir())
|
| 102 |
out.mkdir(parents=True, exist_ok=True)
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
procs.
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
m = re.findall(r"^CAPTURED (.+)$", text, re.M)
|
| 118 |
-
if
|
| 119 |
tail = " | ".join(line for line in text.strip().splitlines()[-4:])
|
| 120 |
-
raise ScreenError("CAPTURE_FAILED", f"screen capture of {task} failed (exit {
|
| 121 |
f = out / f"{slug(task)}.json"
|
| 122 |
try:
|
| 123 |
inv = validate(json.loads(f.read_text(encoding="utf-8")))
|
|
@@ -132,10 +151,11 @@ def capture(task: str, env: dict, *, out_dir: Path | None = None, timeout_s: int
|
|
| 132 |
EXPLORE_SCRIPT = "scripts/explore-fusion.ts"
|
| 133 |
|
| 134 |
|
| 135 |
-
def explore(plan: dict, env: dict, out_dir: Path, *, timeout_s: int = 5400, on_line=None) -> dict:
|
| 136 |
"""Run the explorer (automation/scripts/explore-fusion.ts) on the pod in `env`: for each area of `plan`, list the
|
| 137 |
tasks of its work areas and capture the chosen ones into `out_dir`. Returns {"areas": [...]} with only the captured
|
| 138 |
-
files that pass the privacy check (any other is deleted). Nothing is saved on the pod.
|
|
|
|
| 139 |
if not all(env.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):
|
| 140 |
raise ScreenError("NO_CREDENTIALS", "the pod's address and test user are needed to read its screens", 409)
|
| 141 |
if not _busy.acquire(blocking=False):
|
|
@@ -144,34 +164,50 @@ def explore(plan: dict, env: dict, out_dir: Path, *, timeout_s: int = 5400, on_l
|
|
| 144 |
out = Path(out_dir)
|
| 145 |
out.mkdir(parents=True, exist_ok=True)
|
| 146 |
plan_file = out / "_plan.json"
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
procs.register(p, "screen-explore")
|
| 154 |
-
lines: list[str] = []
|
| 155 |
-
try:
|
| 156 |
-
timer = threading.Timer(timeout_s, lambda: procs.kill_tree(p.pid))
|
| 157 |
-
timer.start()
|
| 158 |
-
for raw in p.stdout:
|
| 159 |
-
line = _scrub(raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw), env).rstrip()
|
| 160 |
-
lines.append(line)
|
| 161 |
if on_line and line.startswith("[explore]"):
|
| 162 |
on_line(line[len("[explore] "):])
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
found = next((l[len("EXPLORED "):] for l in reversed(lines) if l.startswith("EXPLORED ")), None)
|
| 168 |
# each area is reported as it finishes ("AREA <json>"): a read cut off half-way keeps the areas it finished
|
| 169 |
done = [json.loads(l[len("AREA "):]) for l in lines if l.startswith("AREA ")]
|
| 170 |
-
if
|
| 171 |
tail = " | ".join(lines[-4:])
|
| 172 |
if not done:
|
| 173 |
-
raise ScreenError("EXPLORE_FAILED", f"reading the pod's screens failed (exit {
|
| 174 |
-
result = {"areas": done, "incomplete": f"the read stopped before the end (exit {
|
| 175 |
else:
|
| 176 |
result = json.loads(found)
|
| 177 |
for a in result.get("areas") or []:
|
|
|
|
| 89 |
return text
|
| 90 |
|
| 91 |
|
| 92 |
+
def _remote(svc):
|
| 93 |
+
"""(runner address, token) when Fusion browsers run on the remote runner (FPT_REMOTE_RUNNER_URL), else None."""
|
| 94 |
+
if svc is None:
|
| 95 |
+
return None
|
| 96 |
+
from .remote_runner import runner_for
|
| 97 |
+
return runner_for(svc)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def capture(task: str, env: dict, *, out_dir: Path | None = None, timeout_s: int = 1200, svc=None) -> dict:
|
| 101 |
"""Run the capture CLI against the pod in `env` (FUSION_BASE_URL/USERNAME/PASSWORD from PodRegistry.executor_env)
|
| 102 |
+
and return the stored inventory. Nothing is saved on the pod; the credentials go to the child process only. With a
|
| 103 |
+
remote runner (svc given, FPT_REMOTE_RUNNER_URL set) the browser runs there, since Oracle's edge may refuse this host."""
|
| 104 |
task = normalize_task(task)
|
| 105 |
if not all(env.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):
|
| 106 |
raise ScreenError("NO_CREDENTIALS", "the pod's address and test user are needed to capture a screen", 409)
|
|
|
|
| 109 |
try:
|
| 110 |
out = Path(out_dir or screens_dir())
|
| 111 |
out.mkdir(parents=True, exist_ok=True)
|
| 112 |
+
remote = _remote(svc)
|
| 113 |
+
if remote:
|
| 114 |
+
from .remote_runner import RemoteRunnerError, run_screens_remote
|
| 115 |
+
try:
|
| 116 |
+
rc, lines = run_screens_remote(svc.egress, *remote, kind="capture", env=env, out_dir=out, task=task, timeout_s=timeout_s)
|
| 117 |
+
except RemoteRunnerError as e:
|
| 118 |
+
raise ScreenError("CAPTURE_FAILED", f"screen capture of {task} failed on the remote runner: {e}", 502) from None
|
| 119 |
+
text = _scrub("\n".join(lines), env)
|
| 120 |
+
else:
|
| 121 |
+
child_env = procs.child_env(**{k: env[k] for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")})
|
| 122 |
+
for k in ("FPT_LIVE_VIEW_DIR", "PW_LOCATOR_OVERRIDES"):
|
| 123 |
+
child_env.pop(k, None)
|
| 124 |
+
p = _popen(command(task, out), cwd=str(AUTOMATION), env=child_env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
| 125 |
+
**procs.popen_kwargs())
|
| 126 |
+
procs.register(p, f"screen-capture:{slug(task)}")
|
| 127 |
+
try:
|
| 128 |
+
stdout, _ = p.communicate(timeout=timeout_s)
|
| 129 |
+
except subprocess.TimeoutExpired:
|
| 130 |
+
procs.kill_tree(p.pid)
|
| 131 |
+
raise ScreenError("CAPTURE_TIMEOUT", f"screen capture of {task} did not finish in {timeout_s}s", 504) from None
|
| 132 |
+
finally:
|
| 133 |
+
procs.unregister(p)
|
| 134 |
+
rc = p.returncode
|
| 135 |
+
text = _scrub((stdout or b"").decode("utf-8", "replace") if isinstance(stdout, bytes) else (stdout or ""), env)
|
| 136 |
m = re.findall(r"^CAPTURED (.+)$", text, re.M)
|
| 137 |
+
if rc != 0 or not m:
|
| 138 |
tail = " | ".join(line for line in text.strip().splitlines()[-4:])
|
| 139 |
+
raise ScreenError("CAPTURE_FAILED", f"screen capture of {task} failed (exit {rc}): {tail[:400]}", 502)
|
| 140 |
f = out / f"{slug(task)}.json"
|
| 141 |
try:
|
| 142 |
inv = validate(json.loads(f.read_text(encoding="utf-8")))
|
|
|
|
| 151 |
EXPLORE_SCRIPT = "scripts/explore-fusion.ts"
|
| 152 |
|
| 153 |
|
| 154 |
+
def explore(plan: dict, env: dict, out_dir: Path, *, timeout_s: int = 5400, on_line=None, svc=None) -> dict:
|
| 155 |
"""Run the explorer (automation/scripts/explore-fusion.ts) on the pod in `env`: for each area of `plan`, list the
|
| 156 |
tasks of its work areas and capture the chosen ones into `out_dir`. Returns {"areas": [...]} with only the captured
|
| 157 |
+
files that pass the privacy check (any other is deleted). Nothing is saved on the pod. With a remote runner (svc
|
| 158 |
+
given, FPT_REMOTE_RUNNER_URL set) the browser runs there, since Oracle's edge may refuse this host."""
|
| 159 |
if not all(env.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):
|
| 160 |
raise ScreenError("NO_CREDENTIALS", "the pod's address and test user are needed to read its screens", 409)
|
| 161 |
if not _busy.acquire(blocking=False):
|
|
|
|
| 164 |
out = Path(out_dir)
|
| 165 |
out.mkdir(parents=True, exist_ok=True)
|
| 166 |
plan_file = out / "_plan.json"
|
| 167 |
+
remote = _remote(svc)
|
| 168 |
+
if remote:
|
| 169 |
+
from .remote_runner import RemoteRunnerError, run_screens_remote
|
| 170 |
+
|
| 171 |
+
def relay(raw: str) -> None:
|
| 172 |
+
line = _scrub(raw, env).rstrip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
if on_line and line.startswith("[explore]"):
|
| 174 |
on_line(line[len("[explore] "):])
|
| 175 |
+
try:
|
| 176 |
+
rc, raw_lines = run_screens_remote(svc.egress, *remote, kind="explore", env=env, out_dir=out, plan=plan,
|
| 177 |
+
timeout_s=timeout_s, on_line=relay)
|
| 178 |
+
except RemoteRunnerError as e:
|
| 179 |
+
raise ScreenError("EXPLORE_FAILED", f"reading the pod's screens failed on the remote runner: {e}", 502) from None
|
| 180 |
+
lines = [_scrub(line, env).rstrip() for line in raw_lines]
|
| 181 |
+
else:
|
| 182 |
+
plan_file.write_text(json.dumps(plan), encoding="utf-8")
|
| 183 |
+
child_env = procs.child_env(**{k: env[k] for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA") if env.get(k)})
|
| 184 |
+
for k in ("FPT_LIVE_VIEW_DIR", "PW_LOCATOR_OVERRIDES"):
|
| 185 |
+
child_env.pop(k, None)
|
| 186 |
+
p = _popen(["node", str(TSX_CLI), EXPLORE_SCRIPT, str(plan_file), "--out-dir", str(out)], cwd=str(AUTOMATION), env=child_env,
|
| 187 |
+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **procs.popen_kwargs())
|
| 188 |
+
procs.register(p, "screen-explore")
|
| 189 |
+
lines = []
|
| 190 |
+
try:
|
| 191 |
+
timer = threading.Timer(timeout_s, lambda: procs.kill_tree(p.pid))
|
| 192 |
+
timer.start()
|
| 193 |
+
for raw in p.stdout:
|
| 194 |
+
line = _scrub(raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw), env).rstrip()
|
| 195 |
+
lines.append(line)
|
| 196 |
+
if on_line and line.startswith("[explore]"):
|
| 197 |
+
on_line(line[len("[explore] "):])
|
| 198 |
+
p.wait()
|
| 199 |
+
timer.cancel()
|
| 200 |
+
finally:
|
| 201 |
+
procs.unregister(p)
|
| 202 |
+
rc = p.returncode
|
| 203 |
found = next((l[len("EXPLORED "):] for l in reversed(lines) if l.startswith("EXPLORED ")), None)
|
| 204 |
# each area is reported as it finishes ("AREA <json>"): a read cut off half-way keeps the areas it finished
|
| 205 |
done = [json.loads(l[len("AREA "):]) for l in lines if l.startswith("AREA ")]
|
| 206 |
+
if rc != 0 or not found:
|
| 207 |
tail = " | ".join(lines[-4:])
|
| 208 |
if not done:
|
| 209 |
+
raise ScreenError("EXPLORE_FAILED", f"reading the pod's screens failed (exit {rc}): {tail[:400]}", 502)
|
| 210 |
+
result = {"areas": done, "incomplete": f"the read stopped before the end (exit {rc}); the areas it finished are kept"}
|
| 211 |
else:
|
| 212 |
result = json.loads(found)
|
| 213 |
for a in result.get("areas") or []:
|
coworker/api/routes/screens.py
CHANGED
|
@@ -73,7 +73,7 @@ def capture_screen(pod_id: int, body: ScreenCaptureIn, request: Request, user: P
|
|
| 73 |
if pod["kind"] != "fusion":
|
| 74 |
raise ApiError(409, "NOT_FUSION", "screens can only be captured on an Oracle Fusion pod")
|
| 75 |
env = pods.executor_env(pod_id)
|
| 76 |
-
inv = screens.capture(task, env or {})
|
| 77 |
except (screens.ScreenError, PodError) as e:
|
| 78 |
raise _err(e) from e
|
| 79 |
svc.audit.append("screen.captured", actor=user.username, summary=f"{task} on {pod['name']}",
|
|
|
|
| 73 |
if pod["kind"] != "fusion":
|
| 74 |
raise ApiError(409, "NOT_FUSION", "screens can only be captured on an Oracle Fusion pod")
|
| 75 |
env = pods.executor_env(pod_id)
|
| 76 |
+
inv = screens.capture(task, env or {}, svc=svc)
|
| 77 |
except (screens.ScreenError, PodError) as e:
|
| 78 |
raise _err(e) from e
|
| 79 |
svc.audit.append("screen.captured", actor=user.username, summary=f"{task} on {pod['name']}",
|
coworker/config.py
CHANGED
|
@@ -226,6 +226,8 @@ class Settings(BaseSettings):
|
|
| 226 |
fusion_name: str = Field("Oracle Fusion test pod", validation_alias=_alias("fpt_fusion_name", "fusion_name"))
|
| 227 |
fusion_environment: str = Field("test", validation_alias=_alias("fpt_fusion_environment", "fusion_environment"))
|
| 228 |
fusion_modules: Annotated[list[str], NoDecode] = Field(default_factory=lambda: ["AP"], validation_alias=_alias("fpt_fusion_modules", "fusion_modules"))
|
|
|
|
|
|
|
| 229 |
|
| 230 |
patch_watch_enabled: bool = True
|
| 231 |
patch_watch_interval_s: int = 300
|
|
|
|
| 226 |
fusion_name: str = Field("Oracle Fusion test pod", validation_alias=_alias("fpt_fusion_name", "fusion_name"))
|
| 227 |
fusion_environment: str = Field("test", validation_alias=_alias("fpt_fusion_environment", "fusion_environment"))
|
| 228 |
fusion_modules: Annotated[list[str], NoDecode] = Field(default_factory=lambda: ["AP"], validation_alias=_alias("fpt_fusion_modules", "fusion_modules"))
|
| 229 |
+
# its quarterly update (e.g. 26D): the research step reads that release's What's New. Applied when the pod has none.
|
| 230 |
+
fusion_release: str = Field("", validation_alias=_alias("fpt_fusion_release", "fusion_release"))
|
| 231 |
|
| 232 |
patch_watch_enabled: bool = True
|
| 233 |
patch_watch_interval_s: int = 300
|
coworker/platform/pods.py
CHANGED
|
@@ -98,7 +98,8 @@ class PodRegistry:
|
|
| 98 |
|
| 99 |
def ensure_from_env(self) -> None:
|
| 100 |
"""FPT_FUSION_BASE_URL: make sure that Fusion test pod is registered (matched by address, so a pod the person already
|
| 101 |
-
registered or restored is kept as it is)
|
|
|
|
| 102 |
url = (self.cfg.fusion_base_url or "").strip()
|
| 103 |
if not url:
|
| 104 |
return
|
|
@@ -120,6 +121,14 @@ class PodRegistry:
|
|
| 120 |
"created_by": "system", "created_at": now_iso(), "updated_at": now_iso()})
|
| 121 |
self.audit.append("pod.created", actor="system", summary=f"{name} (fusion, {self.cfg.fusion_environment}) {base} from the server settings",
|
| 122 |
payload={"pod_id": pid, "kind": "fusion", "base_url": base, "environment": self.cfg.fusion_environment})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
if self.env_auth() and not self.db.one("SELECT 1 AS x FROM pod_credentials WHERE pod_id=?", (pid,)):
|
| 124 |
# the user and password stay in the secrets; this row only records that the pod has a test user
|
| 125 |
self.db.x("INSERT OR REPLACE INTO pod_credentials (pod_id, module, set_by, set_at) VALUES (?,?,?,?)", (pid, "ALL", "system", now_iso()))
|
|
@@ -434,7 +443,7 @@ class PodRegistry:
|
|
| 434 |
self.db.update("pods", "id", pod_id, screens=json.dumps({**cur, "progress": progress[-6:]}))
|
| 435 |
cur = _json(self.db.one("SELECT screens FROM pods WHERE id=?", (pod_id,))["screens"], {}) or {}
|
| 436 |
try:
|
| 437 |
-
result = screen_adapter.explore(job["plan"], job["env"], self.screens_dir(pod_id), on_line=on_line)
|
| 438 |
areas = dict(cur.get("areas") or {})
|
| 439 |
release = (self.db.one("SELECT release FROM pods WHERE id=?", (pod_id,)) or {}).get("release")
|
| 440 |
for a in result.get("areas") or []: # the release they were read on: a new release reads them again
|
|
|
|
| 98 |
|
| 99 |
def ensure_from_env(self) -> None:
|
| 100 |
"""FPT_FUSION_BASE_URL: make sure that Fusion test pod is registered (matched by address, so a pod the person already
|
| 101 |
+
registered or restored is kept as it is), that it has a test user when the secrets hold one, and its release
|
| 102 |
+
(FPT_FUSION_RELEASE) when it has none yet: a release set in the app wins. Idempotent."""
|
| 103 |
url = (self.cfg.fusion_base_url or "").strip()
|
| 104 |
if not url:
|
| 105 |
return
|
|
|
|
| 121 |
"created_by": "system", "created_at": now_iso(), "updated_at": now_iso()})
|
| 122 |
self.audit.append("pod.created", actor="system", summary=f"{name} (fusion, {self.cfg.fusion_environment}) {base} from the server settings",
|
| 123 |
payload={"pod_id": pid, "kind": "fusion", "base_url": base, "environment": self.cfg.fusion_environment})
|
| 124 |
+
release = (self.cfg.fusion_release or "").strip().upper()
|
| 125 |
+
if release:
|
| 126 |
+
if not RELEASE_RE.fullmatch(release):
|
| 127 |
+
log.warning("FPT_FUSION_RELEASE ignored: write it as two digits and a letter, for example 26D")
|
| 128 |
+
elif not (self.db.one("SELECT release FROM pods WHERE id=?", (pid,)) or {}).get("release"):
|
| 129 |
+
self.db.update("pods", "id", pid, release=release, updated_at=now_iso())
|
| 130 |
+
self.audit.append("pod.updated", actor="system", summary=f"pod {pid} release {release} (from the server settings)",
|
| 131 |
+
payload={"pod_id": pid, "release": release})
|
| 132 |
if self.env_auth() and not self.db.one("SELECT 1 AS x FROM pod_credentials WHERE pod_id=?", (pid,)):
|
| 133 |
# the user and password stay in the secrets; this row only records that the pod has a test user
|
| 134 |
self.db.x("INSERT OR REPLACE INTO pod_credentials (pod_id, module, set_by, set_at) VALUES (?,?,?,?)", (pid, "ALL", "system", now_iso()))
|
|
|
|
| 443 |
self.db.update("pods", "id", pod_id, screens=json.dumps({**cur, "progress": progress[-6:]}))
|
| 444 |
cur = _json(self.db.one("SELECT screens FROM pods WHERE id=?", (pod_id,))["screens"], {}) or {}
|
| 445 |
try:
|
| 446 |
+
result = screen_adapter.explore(job["plan"], job["env"], self.screens_dir(pod_id), on_line=on_line, svc=self)
|
| 447 |
areas = dict(cur.get("areas") or {})
|
| 448 |
release = (self.db.one("SELECT release FROM pods WHERE id=?", (pod_id,)) or {}).get("release")
|
| 449 |
for a in result.get("areas") or []: # the release they were read on: a new release reads them again
|
coworker/tests/test_pods.py
CHANGED
|
@@ -139,6 +139,17 @@ class TestPodFromServerSettings(unittest.TestCase):
|
|
| 139 |
self.assertEqual([p["name"] for p in fusion], ["My own name"])
|
| 140 |
self.assertTrue(fusion[0]["runnable"])
|
| 141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
def test_without_the_secrets_the_pod_exists_but_asks_for_a_test_user(self):
|
| 143 |
import os
|
| 144 |
os.environ.pop("FPT_SECRET_FUSION_PASSWORD")
|
|
|
|
| 139 |
self.assertEqual([p["name"] for p in fusion], ["My own name"])
|
| 140 |
self.assertTrue(fusion[0]["runnable"])
|
| 141 |
|
| 142 |
+
def test_the_release_comes_from_the_settings_but_one_set_in_the_app_wins(self):
|
| 143 |
+
_, c, svc, _ = make_app(fusion_base_url=self.URL, fusion_release="26d")
|
| 144 |
+
p = [p for p in c.get("/api/pods", headers=bearer(c, "viewer")).json() if p["kind"] == "fusion"][0]
|
| 145 |
+
self.assertEqual(p["release"], "26D")
|
| 146 |
+
svc.db.x("UPDATE pods SET release='27A' WHERE kind='fusion'")
|
| 147 |
+
from coworker.platform.pods import PodRegistry
|
| 148 |
+
PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)
|
| 149 |
+
self.assertEqual(svc.db.one("SELECT release FROM pods WHERE kind='fusion'")["release"], "27A")
|
| 150 |
+
_, c2, _, _ = make_app(fusion_base_url=self.URL, fusion_release="latest") # not a release: ignored
|
| 151 |
+
self.assertIsNone([p for p in c2.get("/api/pods", headers=bearer(c2, "viewer")).json() if p["kind"] == "fusion"][0]["release"])
|
| 152 |
+
|
| 153 |
def test_without_the_secrets_the_pod_exists_but_asks_for_a_test_user(self):
|
| 154 |
import os
|
| 155 |
os.environ.pop("FPT_SECRET_FUSION_PASSWORD")
|
coworker/tests/test_remote_screens.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reading a pod's screens on the remote runner (Oracle's edge refuses the server's network): the read goes out through the
|
| 2 |
+
egress gate without the password in the audit, its progress lines reach the caller, its inventories land in the
|
| 3 |
+
screens folder and pass the same privacy check; a file name that climbs out is dropped; the runner checks the job."""
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import io
|
| 7 |
+
import json
|
| 8 |
+
import tempfile
|
| 9 |
+
import types
|
| 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 |
+
from coworker.adapters import screens
|
| 18 |
+
from coworker.tests.test_remote_runner import load_server
|
| 19 |
+
|
| 20 |
+
TASK = "Payables > Invoices > Create Invoice"
|
| 21 |
+
INV = {"task": TASK, "captured_at": "2026-11-15T00:00:00Z", "source": "captured", "sections": ["Header"],
|
| 22 |
+
"fields": [{"label": "Supplier", "kind": "lov", "required": True, "section": "Header"}], "buttons": ["Save"], "menus": {}}
|
| 23 |
+
LOG = ["[explore] signing in", "[explore] Payables: 1 task",
|
| 24 |
+
"AREA " + json.dumps({"code": "AP", "captured": [{"task": TASK}]}),
|
| 25 |
+
"EXPLORED " + json.dumps({"areas": [{"code": "AP", "captured": [{"task": TASK}]}]})]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def bundle(inv=INV) -> bytes:
|
| 29 |
+
buf = io.BytesIO()
|
| 30 |
+
with zipfile.ZipFile(buf, "w") as z:
|
| 31 |
+
z.writestr("playwright.log", "\n".join(LOG) + "\n")
|
| 32 |
+
z.writestr(f"out/{screens.slug(TASK)}.json", json.dumps(inv))
|
| 33 |
+
z.writestr(f"out/{screens.slug(TASK)}.values", json.dumps({"Supplier": ["TEST_SUPPLIER"]}))
|
| 34 |
+
z.writestr("out/../escape.json", "{}")
|
| 35 |
+
return buf.getvalue()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class FakeEgress:
|
| 39 |
+
def __init__(self, inv=INV):
|
| 40 |
+
self.calls, self.polls, self.inv = [], 0, inv
|
| 41 |
+
|
| 42 |
+
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):
|
| 43 |
+
self.calls.append({"method": method, "url": url, "body": json_body, "log": log_body})
|
| 44 |
+
assert kind == "remote_runner" and url.startswith(allowed_base)
|
| 45 |
+
if method == "POST" and url.endswith("/v1/screens"):
|
| 46 |
+
return httpx.Response(202, json={"id": "job_0123456789ab", "state": "running"})
|
| 47 |
+
if url.endswith("/bundle"):
|
| 48 |
+
return httpx.Response(200, content=bundle(self.inv))
|
| 49 |
+
self.polls += 1
|
| 50 |
+
since = int(url.rsplit("since=", 1)[1])
|
| 51 |
+
return httpx.Response(200, json={"state": "done" if self.polls > 1 else "running", "exit_code": 0,
|
| 52 |
+
"lines": LOG[since:since + 2], "line_count": len(LOG)})
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def svc_for(egress):
|
| 56 |
+
vault = types.SimpleNamespace(get=lambda k: "tok-" + "x" * 30 if k == "remote_runner.token" else None)
|
| 57 |
+
return types.SimpleNamespace(cfg=types.SimpleNamespace(remote_runner_url="https://runner.example"), vault=vault, egress=egress)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
ENV = {"FUSION_BASE_URL": "https://fa.example", "FUSION_USERNAME": "fin_impl", "FUSION_PASSWORD": "s3cret", "UNRELATED": "x"}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class TestRemoteScreens(unittest.TestCase):
|
| 64 |
+
def test_explore_runs_on_the_runner_and_lands_like_a_local_read(self):
|
| 65 |
+
eg = FakeEgress()
|
| 66 |
+
seen = []
|
| 67 |
+
with tempfile.TemporaryDirectory() as d:
|
| 68 |
+
res = screens.explore({"areas": [{"code": "AP"}]}, ENV, Path(d), on_line=seen.append, svc=svc_for(eg))
|
| 69 |
+
self.assertEqual(res["areas"][0]["captured"], [{"task": TASK, "slug": screens.slug(TASK)}])
|
| 70 |
+
self.assertEqual(res["areas"][0]["choices"], {"Supplier": ["TEST_SUPPLIER"]})
|
| 71 |
+
self.assertTrue((Path(d) / f"{screens.slug(TASK)}.json").exists())
|
| 72 |
+
self.assertFalse((Path(d) / f"{screens.slug(TASK)}.values").exists()) # choices are returned once, not kept
|
| 73 |
+
self.assertFalse((Path(d).parent / "escape.json").exists())
|
| 74 |
+
self.assertEqual(seen, ["signing in", "Payables: 1 task"])
|
| 75 |
+
post = eg.calls[0]
|
| 76 |
+
self.assertEqual((post["body"]["kind"], post["body"]["env"]["FUSION_PASSWORD"]), ("explore", "s3cret"))
|
| 77 |
+
self.assertNotIn("UNRELATED", post["body"]["env"])
|
| 78 |
+
self.assertNotIn("s3cret", json.dumps([c["log"] for c in eg.calls]))
|
| 79 |
+
|
| 80 |
+
def test_capture_runs_on_the_runner_and_a_file_with_values_is_refused(self):
|
| 81 |
+
with tempfile.TemporaryDirectory() as d:
|
| 82 |
+
log = list(LOG)
|
| 83 |
+
LOG[:] = ["CAPTURED " + TASK]
|
| 84 |
+
try:
|
| 85 |
+
inv = screens.capture(TASK, ENV, out_dir=Path(d), svc=svc_for(FakeEgress()))
|
| 86 |
+
self.assertEqual(inv["fields"][0]["label"], "Supplier")
|
| 87 |
+
with self.assertRaises(screens.ScreenError) as e:
|
| 88 |
+
screens.capture(TASK, ENV, out_dir=Path(d), svc=svc_for(FakeEgress({**INV, "value": "secret"})))
|
| 89 |
+
self.assertEqual(e.exception.code, "PRIVACY")
|
| 90 |
+
self.assertFalse((Path(d) / f"{screens.slug(TASK)}.json").exists())
|
| 91 |
+
finally:
|
| 92 |
+
LOG[:] = log
|
| 93 |
+
|
| 94 |
+
def test_without_a_runner_the_browser_stays_local(self):
|
| 95 |
+
svc = svc_for(FakeEgress())
|
| 96 |
+
svc.cfg.remote_runner_url = ""
|
| 97 |
+
self.assertIsNone(R.runner_for(svc))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class TestRunnerScreenJobs(unittest.TestCase):
|
| 101 |
+
def test_screen_jobs_are_checked(self):
|
| 102 |
+
S = load_server()
|
| 103 |
+
env = {"FUSION_BASE_URL": "https://fa.example", "FUSION_USERNAME": "u", "FUSION_PASSWORD": "p"}
|
| 104 |
+
for bad in ({"kind": "shell", "env": env}, {"kind": "explore", "env": {}, "plan": {}},
|
| 105 |
+
{"kind": "capture", "env": env, "task": "x\nrm -rf /"}, {"kind": "explore", "env": env, "plan": "nope"}):
|
| 106 |
+
with self.assertRaises(ValueError):
|
| 107 |
+
S.start_screens(bad)
|
| 108 |
+
|
| 109 |
+
def test_the_bundle_ships_only_inventory_files(self):
|
| 110 |
+
S = load_server()
|
| 111 |
+
with tempfile.TemporaryDirectory() as d:
|
| 112 |
+
out = Path(d) / "out"
|
| 113 |
+
out.mkdir()
|
| 114 |
+
(out / "a-b.json").write_text("{}")
|
| 115 |
+
(out / "a-b.values").write_text("{}")
|
| 116 |
+
(out / ".fusion-session.json").write_text("{cookies}")
|
| 117 |
+
(out / "notes.txt").write_text("x")
|
| 118 |
+
names = zipfile.ZipFile(io.BytesIO(S.bundle({"dir": Path(d)}))).namelist()
|
| 119 |
+
self.assertEqual(sorted(names), ["out/a-b.json", "out/a-b.values"])
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
if __name__ == "__main__":
|
| 123 |
+
unittest.main()
|
docs/REMOTE_RUNNER.md
CHANGED
|
@@ -4,10 +4,27 @@ Use the remote runner when the Patchwise server's network is refused by Oracle's
|
|
| 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:**
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
## How it works
|
| 13 |
|
|
|
|
| 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`) and
|
| 8 |
+
`coworker/adapters/screens.py` (`explore`, `capture`).
|
| 9 |
- **Runner side:** `automation/remote_runner/server.py` (standard library only).
|
| 10 |
+
- **Scope:** everything that opens a browser on a Fusion pod goes to the runner:
|
| 11 |
+
- test attempts (`playwright.fusion.config.ts`);
|
| 12 |
+
- reading the pod's screens before scenarios are written (the explorer and single-screen capture).
|
| 13 |
+
|
| 14 |
+
The practice pod and stub runs stay local.
|
| 15 |
+
|
| 16 |
+
## Reading screens on the runner
|
| 17 |
+
|
| 18 |
+
`POST /v1/screens` takes:
|
| 19 |
+
|
| 20 |
+
- `kind`: `explore` (with the explorer's `plan`) or `capture` (with a `task` such as "Payables > Invoices > Create
|
| 21 |
+
Invoice");
|
| 22 |
+
- `env`: the pod's address and test user only.
|
| 23 |
+
|
| 24 |
+
It shares the one-browser lock with the attempts, and is polled and cancelled the same way. The poll takes
|
| 25 |
+
`?since=<line>` to return the newest log lines, so the pod card shows the progress. The bundle holds the log and the
|
| 26 |
+
`out/` files: the inventories (`<slug>.json`, Oracle's labels only) and the list choices (`<slug>.values`). Patchwise
|
| 27 |
+
puts them in the pod's screens folder and checks them with the same privacy rule as a local read.
|
| 28 |
|
| 29 |
## How it works
|
| 30 |
|