diff --git a/automation/playwright.fusion.config.ts b/automation/playwright.fusion.config.ts index 903f00cbb439041e76a8fc32c39b8179643072c6..e354ee215520fcdfb4c86458e6e67d9c111064d4 100644 --- a/automation/playwright.fusion.config.ts +++ b/automation/playwright.fusion.config.ts @@ -1,59 +1,62 @@ -import { defineConfig, devices } from '@playwright/test'; -import * as path from 'path'; - -/* - * Runs against a REAL Oracle Fusion pod (tests/fusion). The pod address and its test user come from the environment - * (FUSION_BASE_URL, FUSION_USERNAME, FUSION_PASSWORD), set by the co-worker from the pod registration and its vault. - * Fusion pages are slow, so timeouts are far longer than for the practice pod. The test user signs in ONCE for the run - * (src/fusion/session.ts) and every test starts from that session; FPT_FUSION_WORKERS tests run at once (default 1). - */ -if (!process.env.PW_RUN_ID) { - const d = new Date(); const p2 = (n: number) => String(n).padStart(2, '0'); - process.env.PW_RUN_ID = `fusion-${d.getFullYear()}${p2(d.getMonth() + 1)}${p2(d.getDate())}-${p2(d.getHours())}${p2(d.getMinutes())}${p2(d.getSeconds())}`; -} -const RUN_DIR = path.join(__dirname, 'results', 'runs', process.env.PW_RUN_ID); -const DRAFTS = process.env.FPT_DRAFTS_DIR; -const LIBRARY = process.env.FPT_LIBRARY_DIR; // approved scenarios kept in FPT_HOME/library (they survive redeploys) -// the run's one sign-in: written by the global setup, deleted by the teardown (it holds session cookies) -const SESSION = path.join(RUN_DIR, '.fusion-session.json'); -process.env.FPT_FUSION_SESSION_FILE = SESSION; -// Fusion's own server is the slow part: a few browsers at once finish far sooner, even on a small machine -const WORKERS = Math.max(1, Math.min(4, Number(process.env.FPT_FUSION_WORKERS) || 1)); -const SLOW_MO = process.env.FPT_LIVE_VIEW_DIR ? Math.max(0, Math.min(3000, Number(process.env.FPT_BROWSER_SLOWMO_MS) || 0)) : 0; - -export default defineConfig({ - testDir: './tests/fusion', - outputDir: path.join(RUN_DIR, 'artifacts'), - fullyParallel: false, - workers: WORKERS, - globalSetup: require.resolve('./src/fusion/session-setup'), - globalTeardown: require.resolve('./src/fusion/session-teardown'), - retries: 0, // the co-worker owns the single retry - timeout: 600_000 + SLOW_MO * 400, - expect: { timeout: 30_000 }, - metadata: { target: `Oracle Fusion pod ${process.env.FUSION_BASE_URL || '(not set)'}`, runId: process.env.PW_RUN_ID }, - reporter: [ - ['list'], - ['json', { outputFile: process.env.PLAYWRIGHT_JSON_OUTPUT_NAME || path.join(RUN_DIR, 'results.pwjson') }], - ], - use: { - // a trace taken after sign-in holds the Fusion session cookies in its network log: kept only when a test fails, - // where it is needed to see why (screenshots are kept for every test) - trace: 'retain-on-failure', - screenshot: 'on', - video: 'retain-on-failure', - actionTimeout: 60_000, - navigationTimeout: 120_000, - viewport: { width: 1440, height: 900 }, - launchOptions: { slowMo: SLOW_MO }, - storageState: SESSION, - }, - projects: [ - { name: 'chromium', use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }, - // AI-written steps scenarios staged by the co-worker (FPT_DRAFTS_DIR, outside automation/): their dry run before - // the consultant approves them, and runs from staging. Invisible to `npm test` and to qa/audit.py. - ...(DRAFTS ? [{ name: 'drafts', testDir: DRAFTS, testIgnore: [] as string[], use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }] : []), - // the persistent library: AI-written and client scenarios a person approved, re-run in every later run - ...(LIBRARY ? [{ name: 'library', testDir: LIBRARY, testIgnore: [] as string[], use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }] : []), - ], -}); +import { defineConfig, devices } from '@playwright/test'; +import * as path from 'path'; + +/* + * Runs against a REAL Oracle Fusion pod (tests/fusion). The pod address and its test user come from the environment + * (FUSION_BASE_URL, FUSION_USERNAME, FUSION_PASSWORD), set by the co-worker from the pod registration and its vault. + * Fusion pages are slow, so timeouts are far longer than for the practice pod. The test user signs in ONCE for the run + * (src/fusion/session.ts) and every test starts from that session; FPT_FUSION_WORKERS tests run at once (default 1). + */ +if (!process.env.PW_RUN_ID) { + const d = new Date(); const p2 = (n: number) => String(n).padStart(2, '0'); + process.env.PW_RUN_ID = `fusion-${d.getFullYear()}${p2(d.getMonth() + 1)}${p2(d.getDate())}-${p2(d.getHours())}${p2(d.getMinutes())}${p2(d.getSeconds())}`; +} +const RUN_DIR = path.join(__dirname, 'results', 'runs', process.env.PW_RUN_ID); +const DRAFTS = process.env.FPT_DRAFTS_DIR; +const LIBRARY = process.env.FPT_LIBRARY_DIR; // approved scenarios kept in FPT_HOME/library (they survive redeploys) +// the run's one sign-in: written by the global setup, deleted by the teardown (it holds session cookies) +const SESSION = path.join(RUN_DIR, '.fusion-session.json'); +process.env.FPT_FUSION_SESSION_FILE = SESSION; +// assisted sign-in: the pass's marker that the session a person signed in has expired (src/fusion/ui.ts, fixtures.ts); +// a provided session (FPT_FUSION_STORAGE_STATE) becomes SESSION in the global setup instead of a sign-in +process.env.FPT_SIGN_IN_EXPIRED_FILE = path.join(RUN_DIR, '.sign-in-expired'); +// Fusion's own server is the slow part: a few browsers at once finish far sooner, even on a small machine +const WORKERS = Math.max(1, Math.min(4, Number(process.env.FPT_FUSION_WORKERS) || 1)); +const SLOW_MO = process.env.FPT_LIVE_VIEW_DIR ? Math.max(0, Math.min(3000, Number(process.env.FPT_BROWSER_SLOWMO_MS) || 0)) : 0; + +export default defineConfig({ + testDir: './tests/fusion', + outputDir: path.join(RUN_DIR, 'artifacts'), + fullyParallel: false, + workers: WORKERS, + globalSetup: require.resolve('./src/fusion/session-setup'), + globalTeardown: require.resolve('./src/fusion/session-teardown'), + retries: 0, // the co-worker owns the single retry + timeout: 600_000 + SLOW_MO * 400, + expect: { timeout: 30_000 }, + metadata: { target: `Oracle Fusion pod ${process.env.FUSION_BASE_URL || '(not set)'}`, runId: process.env.PW_RUN_ID }, + reporter: [ + ['list'], + ['json', { outputFile: process.env.PLAYWRIGHT_JSON_OUTPUT_NAME || path.join(RUN_DIR, 'results.pwjson') }], + ], + use: { + // a trace taken after sign-in holds the Fusion session cookies in its network log: kept only when a test fails, + // where it is needed to see why (screenshots are kept for every test) + trace: 'retain-on-failure', + screenshot: 'on', + video: 'retain-on-failure', + actionTimeout: 60_000, + navigationTimeout: 120_000, + viewport: { width: 1440, height: 900 }, + launchOptions: { slowMo: SLOW_MO }, + storageState: SESSION, + }, + projects: [ + { name: 'chromium', use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }, + // AI-written steps scenarios staged by the co-worker (FPT_DRAFTS_DIR, outside automation/): their dry run before + // the consultant approves them, and runs from staging. Invisible to `npm test` and to qa/audit.py. + ...(DRAFTS ? [{ name: 'drafts', testDir: DRAFTS, testIgnore: [] as string[], use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }] : []), + // the persistent library: AI-written and client scenarios a person approved, re-run in every later run + ...(LIBRARY ? [{ name: 'library', testDir: LIBRARY, testIgnore: [] as string[], use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }] : []), + ], +}); diff --git a/automation/remote_runner/server.py b/automation/remote_runner/server.py index 6f3f4d87ad080d7b3dc674206aace8dc484ab64f..6abf96bbf8c95c51b4723181ab7e887b1209db5a 100644 --- a/automation/remote_runner/server.py +++ b/automation/remote_runner/server.py @@ -1,457 +1,710 @@ -"""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). - -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. 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).""" -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"} -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 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)} - 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",)} - env.update(env_in) - 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: - save_meta(job) - LOCK.release() - - -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" - - 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", "") - ok = bool(TOKEN) and h.startswith("Bearer ") and hmac.compare_digest(h[7:].strip(), TOKEN) - 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 - 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 - n = int(self.headers.get("Content-Length") or 0) - 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)}) - 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) - 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() +"""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"} +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")} + 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" + + 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", "") + ok = bool(TOKEN) and h.startswith("Bearer ") and hmac.compare_digest(h[7:].strip(), TOKEN) + 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 + n = int(self.headers.get("Content-Length") or 0) + 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() diff --git a/automation/scripts/check-heal.ts b/automation/scripts/check-heal.ts new file mode 100644 index 0000000000000000000000000000000000000000..44dbe3fc9e7f326a948eee1d37d402e9029b323d --- /dev/null +++ b/automation/scripts/check-heal.ts @@ -0,0 +1,33 @@ +/* Checks the control-name healing logic (src/fusion/heal.ts) without a browser: `npx tsx scripts/check-heal.ts`. */ +import assert from 'node:assert/strict'; +import { closeMatch, normalise, normalisedMatch, parseHeals, pick } from '../src/fusion/heal'; + +assert.equal(normalise(' Invoice Number (Required) '), 'invoice number'); +assert.equal(normalise('Amount: 3'), 'amount'); +assert.equal(normalisedMatch('Invoice Number', ['Amount', 'invoice number', 'Supplier']), 'invoice number'); +assert.equal(normalisedMatch('Save', ['Save', 'SAVE']), null); // two ways to write it: not unambiguous +// close names: one clear candidate only +assert.equal(closeMatch('Business Unit', ['Business Units', 'Supplier']), 'Business Units'); +assert.equal(closeMatch('Validate', ['Invalidate']), null); // a different action, not a relabel +assert.equal(closeMatch('Amount 1', ['Amount 2']), null); // a different row +assert.equal(closeMatch('Cancel', ['Cancel Invoice']), null); +assert.equal(closeMatch('Add Row', ['Add Rows', 'Add Rowz']), null); // two candidates, no clear winner +assert.equal(closeMatch('UOM', ['UOMs']), null); // too short to guess +assert.equal(closeMatch('Supplier', []), null); +// order: approved, then same name, then close +const rules = [{ kind: 'button' as const, wanted: 'Submit', to: 'Send for Approval', where: 'Purchasing > Orders > Create Order' }]; +assert.deepEqual(pick(rules, 'button', 'Submit', 'Purchasing > Orders > Create Order', ['Send for Approval', 'Cancel']), { used: 'Send for Approval', how: 'approved' }); +assert.equal(pick(rules, 'button', 'Submit', 'Payables > Invoices > Create Invoice', ['Send for Approval']), null); // another task: not that heal +assert.equal(pick(rules, 'field', 'Submit', 'Purchasing > Orders > Create Order', ['Send for Approval']), null); // another kind +assert.equal(pick(rules, 'button', 'Submit', 'Purchasing > Orders > Create Order', ['Cancel']), null); // approved name gone: no guess +assert.deepEqual(pick([], 'field', 'Invoice Date', '', ['invoice date']), { used: 'invoice date', how: 'normalised' }); +assert.deepEqual(pick([], 'menu', 'Cancel Document', '', ['Cancel Documents']), { used: 'Cancel Documents', how: 'close' }); +// a heal a person rejected is never picked on the spot (that place only), and is not an approval +const no = [{ kind: 'menu' as const, wanted: 'Cancel Document', to: 'Cancel Documents', where: 'Purchasing > Orders', rejected: true }]; +assert.equal(pick(no, 'menu', 'Cancel Document', 'Purchasing > Orders', ['Cancel Documents']), null); +assert.deepEqual(pick(no, 'menu', 'Cancel Document', 'Payables > Invoices', ['Cancel Documents']), { used: 'Cancel Documents', how: 'close' }); +// FPT_HEALS: bad input is ignored +assert.deepEqual(parseHeals(undefined), []); +assert.deepEqual(parseHeals('not json'), []); +assert.deepEqual(parseHeals('[{"kind":"field","wanted":"A","to":"B"},{"kind":"x"},5]'), [{ kind: 'field', wanted: 'A', to: 'B' }]); +console.log('heal: all checks pass'); diff --git a/automation/scripts/sign-in-session.ts b/automation/scripts/sign-in-session.ts new file mode 100644 index 0000000000000000000000000000000000000000..03b8914da43ecb12b8e4becbcad5ea8b7cef2cd5 --- /dev/null +++ b/automation/scripts/sign-in-session.ts @@ -0,0 +1,127 @@ +// Assisted sign-in: a browser a PERSON signs in with, for a pod whose sign-in goes through the company's identity provider +// (Entra, Okta, with MFA), which no unattended browser can complete. Started by Astra on this server or by the remote +// runner (automation/remote_runner/server.py); both drive it through one folder: +// +// FUSION_BASE_URL=https://pod.example npx tsx scripts/sign-in-session.ts +// +// /frame.jpg the page as it looks now (replaced about twice a second) +// /status.json {state: starting | open | signed_in | saved | closed | failed, page: pod | identity provider | blank, +// at, error?}: never the page address (a sign-in address can carry one-time codes) +// /input.jsonl what the person does, one JSON event per line, appended by the controller: +// {"type": "click", "x", "y"} | {"type": "type", "text"} | {"type": "press", "key"} | +// {"type": "scroll", "dy"} | {"type": "finish"} | {"type": "cancel"} +// /state.json the signed-in session (Playwright storage state: the pod's cookies), mode 0600, written once +// the Fusion home page opens (the same check FusionUi.signIn() uses) or on "finish" +// +// Nothing the person types is printed, recorded or kept: no trace, no video, no log line with an event's content. The +// browser stops after FPT_SIGN_IN_MAX_S seconds (default 1800) whatever happens; the controller stops it sooner when +// nobody uses it (15 minutes). +import * as fs from 'fs'; +import * as path from 'path'; +import { chromium, type Page } from '@playwright/test'; + +export const VIEWPORT = { width: 1280, height: 800 }; +/** The Fusion home page: where signIn() knows a sign-in has worked (src/fusion/ui.ts). */ +export const HOME = /AtkHomePageWelcome|FuseWelcome/; +const KEY = /^(?:(?:Control|Shift|Alt|Meta)\+)*(?:[A-Za-z0-9]|Enter|Tab|Backspace|Delete|Escape|ArrowUp|ArrowDown|ArrowLeft|ArrowRight|Home|End|PageUp|PageDown|Space)$/; + +type Event = { type: string; x?: number; y?: number; text?: string; key?: string; dy?: number }; + +function write(folder: string, name: string, data: string | Buffer, mode?: number) { + const tmp = path.join(folder, `.${name}.tmp`); + fs.writeFileSync(tmp, data, mode ? { mode } : undefined); + fs.renameSync(tmp, path.join(folder, name)); +} + +/** Which kind of page is open, never its address: the pod itself, the identity provider, or nothing yet. */ +export function pageKind(url: string, podHost: string): 'pod' | 'identity provider' | 'blank' { + try { + const u = new URL(url); + if (u.protocol === 'about:' || !u.hostname) return 'blank'; + return u.hostname === podHost ? 'pod' : 'identity provider'; + } catch { return 'blank'; } +} + +/** The Fusion home page of the pod, so the session holds what the tests need. */ +export function onHome(url: string, podHost: string): boolean { + try { + const u = new URL(url); + return u.hostname === podHost && HOME.test(u.pathname); + } catch { return false; } +} + +async function apply(page: Page, e: Event): Promise { + if (e.type === 'click' && Number.isFinite(e.x) && Number.isFinite(e.y)) { + await page.mouse.click(Math.max(0, Math.min(VIEWPORT.width, Number(e.x))), Math.max(0, Math.min(VIEWPORT.height, Number(e.y)))); + } else if (e.type === 'type' && typeof e.text === 'string') { + await page.keyboard.type(e.text.slice(0, 500)); + } else if (e.type === 'press' && typeof e.key === 'string' && KEY.test(e.key)) { + await page.keyboard.press(e.key === 'Space' ? ' ' : e.key); + } else if (e.type === 'scroll' && Number.isFinite(e.dy)) { + await page.mouse.wheel(0, Math.max(-2000, Math.min(2000, Number(e.dy)))); + } +} + +async function main() { + const folder = path.resolve(process.argv[2] || ''); + const base = (process.env.FUSION_BASE_URL || '').replace(/\/$/, ''); + if (!process.argv[2] || !fs.existsSync(folder)) throw new Error('usage: sign-in-session.ts (FUSION_BASE_URL set)'); + if (!/^https:\/\//.test(base)) throw new Error('FUSION_BASE_URL must be the pod address (https)'); + const host = new URL(base).hostname; + const maxMs = Math.max(60, Math.min(3600, Number(process.env.FPT_SIGN_IN_MAX_S) || 1800)) * 1000; + const end = Date.now() + maxMs; + const status = (state: string, extra: Record = {}) => + write(folder, 'status.json', JSON.stringify({ state, at: new Date().toISOString(), ...extra })); + status('starting', { page: 'blank' }); + const browser = await chromium.launch({ headless: true }); + let state = 'closed'; + try { + const context = await browser.newContext({ viewport: VIEWPORT }); + const page = await context.newPage(); + page.setDefaultTimeout(30_000); + await page.goto(`${base}/`, { waitUntil: 'domcontentloaded', timeout: 120_000 }).catch(() => {}); + const inbox = path.join(folder, 'input.jsonl'); + let offset = 0; + let finish = false; + while (Date.now() < end) { + // what the person did since the last look (a partial last line waits for the next round) + let events: Event[] = []; + try { + const buf = fs.readFileSync(inbox); + const upto = buf.lastIndexOf(10) + 1; + if (upto > offset) { + events = buf.subarray(offset, upto).toString('utf-8').split('\n').filter(Boolean).flatMap((l) => { + try { return [JSON.parse(l) as Event]; } catch { return []; } + }); + offset = upto; + } + } catch { /* nothing sent yet */ } + if (events.some((e) => e.type === 'cancel')) { state = 'closed'; break; } + for (const e of events) { + if (e.type === 'finish') { finish = true; break; } + await apply(page, e).catch(() => {}); // a click that lands nowhere is the person's to repeat + } + const url = page.url(); + if (finish || onHome(url, host)) { + await page.waitForLoadState('domcontentloaded').catch(() => {}); + write(folder, 'state.json', JSON.stringify(await context.storageState()), 0o600); + state = finish && !onHome(url, host) ? 'saved' : 'signed_in'; + break; + } + const shot = await page.screenshot({ type: 'jpeg', quality: 60, timeout: 10_000 }).catch(() => null); + if (shot) write(folder, 'frame.jpg', shot); + status('open', { page: pageKind(url, host) }); + await page.waitForTimeout(events.length ? 150 : 450); + } + } catch (e) { + state = 'failed'; + status('failed', { page: 'blank', error: String((e as Error).message || e).split('\n')[0].slice(0, 200) }); + } finally { + await browser.close().catch(() => {}); + } + if (state !== 'failed') status(state, { page: state === 'closed' ? 'blank' : 'pod' }); +} + +if (require.main === module) { + main().catch((e) => { console.error(`[sign-in] ${String((e as Error).message || e).split('\n')[0]}`); process.exit(1); }); +} diff --git a/automation/src/fusion/fixtures.ts b/automation/src/fusion/fixtures.ts index 3dc02be25c278dc24d89249c7e833d3df64ca0fc..a58e27b9848a4e3dc8c5107e804e06c2fb05683a 100644 --- a/automation/src/fusion/fixtures.ts +++ b/automation/src/fusion/fixtures.ts @@ -1,64 +1,142 @@ -import { appendFileSync } from 'node:fs'; -import { test as base, expect } from '@playwright/test'; -import { beginLiveStatus, liveViewDir, startLiveView } from '../live-view'; -import { FusionRest } from './rest'; -import { apData, FusionUi } from './ui'; - -/** Payables test invoices of one test: REST for checks, and every number registered here is cancelled afterwards. */ -export interface ApInvoices { - rest: FusionRest; - /** Register a test invoice number BEFORE saving it, so it is cleaned up even if the test fails half-way. */ - track(number: string): string; -} - -/** - * The run's test-data ledger (FPT_CREATED_FILE, a JSON-lines file in the co-worker's run folder). A number is written - * here BEFORE the invoice is saved, and its clean-up result after; if the run is cancelled, killed, times out or the - * server restarts before the clean-up below runs, the co-worker cancels what is left through Fusion REST. - */ -function ledger(rec: Record): void { - const f = process.env.FPT_CREATED_FILE; - if (!f) return; - appendFileSync(f, JSON.stringify({ ...rec, ts: new Date().toISOString() }) + '\n', 'utf-8'); // synchronous: on disk before the save -} - -/** Live view follows ONE browser: with several tests at once (FPT_FUSION_WORKERS), the first worker's. The Live tab - * shows one picture, and frames from several browsers would only flicker between tests. */ -const watched = (testInfo: { parallelIndex: number }) => !!liveViewDir() && testInfo.parallelIndex === 0; - -/** Fixtures for tests against a real Oracle Fusion pod: the Fusion steps plus the same live view as mock runs. */ -export const test = base.extend<{ fusion: FusionUi; apInvoices: ApInvoices; liveStatus: void }>({ - page: async ({ page }, use, testInfo) => { - const stopLive = watched(testInfo) ? await startLiveView(page, testInfo) : null; - await use(page); - if (stopLive) await stopLive(); - }, - fusion: async ({ page }, use) => { await use(new FusionUi(page)); }, - apInvoices: async ({}, use, testInfo) => { - const rest = new FusionRest(); - const numbers: string[] = []; - const d = apData(); - await use({ - rest, - track: (n) => { - if (!numbers.includes(n)) { - ledger({ kind: 'ap_invoice', number: n, businessUnit: d.businessUnit, supplier: d.supplier, test: testInfo.title }); - numbers.push(n); - } - return n; - }, - }); - // Clean-up runs whether the test passed or failed; a clean-up failure fails the test (data left on the pod). - const errors: string[] = []; - for (const n of numbers) { - try { - const done = await rest.cancelIfPresent(n, d.businessUnit, d.supplier); - testInfo.annotations.push({ type: 'cleanup', description: done }); - ledger({ kind: 'ap_invoice', number: n, cleaned: done }); - } catch (e) { errors.push(String((e as Error).message || e)); } - } - if (errors.length) throw new Error(`Clean-up failed, test data may be left on the pod: ${errors.join('; ')}`); - }, - liveStatus: [async ({}, use, testInfo) => { const done = watched(testInfo) ? beginLiveStatus(testInfo) : null; await use(); if (done) done(); }, { auto: true }], -}); -export { expect }; +import { appendFileSync } from 'node:fs'; +import { test as base, expect } from '@playwright/test'; +import { beginLiveStatus, liveViewDir, startLiveView } from '../live-view'; +import { FusionRest, NeedsScreen, NO_REST_WHY, REST_SKIPPED } from './rest'; +import { apData, assistedSignIn, FusionUi, markSignInExpired, SIGN_IN_EXPIRED, signInExpiredReason } from './ui'; + +/** Payables test invoices of one test: REST for checks, and every number registered here is cancelled afterwards. */ +export interface ApInvoices { + rest: FusionRest; + /** Register a test invoice number BEFORE saving it, so it is cleaned up even if the test fails half-way. */ + track(number: string): string; + /** A check through Fusion REST: run when REST is available; on a pod with assisted sign-in (no password) skipped with + * a note on the test, and the screen result stands. */ + check(what: string, fn: () => Promise): Promise; +} + +/** The Purchasing and General Ledger test documents a test creates, by the reference registered BEFORE the save (the + * test's FPT- tag in a requisition's or an order's Description, a journal batch's name): Fusion gives a requisition + * or an order its number only when it is saved. */ +export type DocKind = 'po_requisition' | 'po_order' | 'gl_journal'; +export interface FusionDocs { + /** Register a test document BEFORE saving it, so it is cleaned up even if the test fails half-way. */ + track(kind: DocKind, ref: string): string; +} + +/** Clean-up of one test document over REST (rest.ts): a requisition or order cancelled or deleted, a journal deleted + * while unposted. What REST cannot do (a submitted requisition, an order pending approval) is done on the screens + * with the business action's own steps, then REST is asked again. */ +async function cleanDoc(rest: FusionRest, ui: FusionUi, kind: DocKind, ref: string): Promise { + const clean = () => (kind === 'po_requisition' ? rest.cleanRequisition(ref) : kind === 'po_order' ? rest.cleanPurchaseOrder(ref) : rest.cleanJournal(ref)); + try { + return await clean(); + } catch (e) { + if (!(e instanceof NeedsScreen)) throw e; + if (kind === 'po_requisition') await ui.cancelRequisition(ref); + else if (kind === 'po_order') await ui.cancelPurchaseOrder(ref); + else throw e; + return `${await clean()} (on the screens: ${e.message})`; + } +} + +/** + * The run's test-data ledger (FPT_CREATED_FILE, a JSON-lines file in the co-worker's run folder). A number is written + * here BEFORE the invoice is saved, and its clean-up result after; if the run is cancelled, killed, times out or the + * server restarts before the clean-up below runs, the co-worker cancels what is left through Fusion REST. + */ +function ledger(rec: Record): void { + const f = process.env.FPT_CREATED_FILE; + if (!f) return; + appendFileSync(f, JSON.stringify({ ...rec, ts: new Date().toISOString() }) + '\n', 'utf-8'); // synchronous: on disk before the save +} + +/** Live view follows ONE browser: with several tests at once (FPT_FUSION_WORKERS), the first worker's. The Live tab + * shows one picture, and frames from several browsers would only flicker between tests. */ +const watched = (testInfo: { parallelIndex: number }) => !!liveViewDir() && testInfo.parallelIndex === 0; + +/** Fixtures for tests against a real Oracle Fusion pod: the Fusion steps plus the same live view as mock runs. */ +export const test = base.extend<{ fusion: FusionUi; apInvoices: ApInvoices; fusionDocs: FusionDocs; liveStatus: void; signInGuard: void }>({ + page: async ({ page }, use, testInfo) => { + const stopLive = watched(testInfo) ? await startLiveView(page, testInfo) : null; + await use(page); + if (stopLive) await stopLive(); + }, + fusion: async ({ page }, use) => { await use(new FusionUi(page)); }, + apInvoices: async ({}, use, testInfo) => { + const rest = new FusionRest(); + const numbers: string[] = []; + const d = apData(); + await use({ + rest, + track: (n) => { + if (!numbers.includes(n)) { + ledger({ kind: 'ap_invoice', number: n, businessUnit: d.businessUnit, supplier: d.supplier, test: testInfo.title }); + numbers.push(n); + } + return n; + }, + check: async (what, fn) => { + if (rest.available) return fn(); + testInfo.annotations.push({ type: REST_SKIPPED, description: `${what}: ${NO_REST_WHY}` }); + }, + }); + if (!rest.available) { // assisted sign-in, no REST: the ledger keeps them listed, the run asks a person to cancel them + for (const n of numbers) testInfo.annotations.push({ type: 'cleanup', description: `${n}: not cancelled (no Fusion REST on this pod); cancel it by hand` }); + return; + } + // Clean-up runs whether the test passed or failed; a clean-up failure fails the test (data left on the pod). + const errors: string[] = []; + for (const n of numbers) { + try { + const done = await rest.cancelIfPresent(n, d.businessUnit, d.supplier); + testInfo.annotations.push({ type: 'cleanup', description: done }); + ledger({ kind: 'ap_invoice', number: n, cleaned: done }); + } catch (e) { errors.push(String((e as Error).message || e)); } + } + if (errors.length) throw new Error(`Clean-up failed, test data may be left on the pod: ${errors.join('; ')}`); + }, + // The same for requisitions, orders and journals. It uses the test's own browser for what REST cannot clean up, so + // it is torn down before the page (it depends on `fusion`). + fusionDocs: async ({ fusion }, use, testInfo) => { + const docs: [DocKind, string][] = []; + await use({ + track: (kind, ref) => { + if (!docs.some(([k, r]) => k === kind && r === ref)) { + ledger({ kind, number: ref, by: kind === 'gl_journal' ? 'name' : 'description', test: testInfo.title }); + docs.push([kind, ref]); + } + return ref; + }, + }); + if (!docs.length) return; + const rest = new FusionRest(); + const errors: string[] = []; + // the newest first: an order made from a requisition goes before the requisition + for (const [kind, ref] of [...docs].reverse()) { + try { + const done = await cleanDoc(rest, fusion, kind, ref); + testInfo.annotations.push({ type: 'cleanup', description: done }); + ledger({ kind, number: ref, cleaned: done }); + } catch (e) { errors.push(String((e as Error).message || e).split('\n')[0]); } + } + if (errors.length) throw new Error(`Clean-up failed, test data may be left on the pod: ${errors.join('; ')}`); + }, + // Assisted sign-in: a test after the session expired is skipped with the reason, and a test that stopped on a sign-in + // page is marked, so Astra runs both again after a new sign-in instead of reporting them as failures. + signInGuard: [async ({ page }, use, testInfo) => { + if (!assistedSignIn()) return use(); + const before = signInExpiredReason(); + if (before) { + testInfo.annotations.push({ type: SIGN_IN_EXPIRED, description: before }); + testInfo.skip(true, before); + } + await use(); + if (testInfo.status === testInfo.expectedStatus) return; + const why = signInExpiredReason() ?? (await new FusionUi(page).onSignInPage() + ? markSignInExpired('Sign-in expired: the test landed on the sign-in page mid-way (assisted sign-in). Astra asks for a new sign-in and runs it again.') + : null); + if (why) testInfo.annotations.push({ type: SIGN_IN_EXPIRED, description: why }); + }, { auto: true }], + liveStatus: [async ({}, use, testInfo) => { const done = watched(testInfo) ? beginLiveStatus(testInfo) : null; await use(); if (done) done(); }, { auto: true }], +}); +export { expect }; diff --git a/automation/src/fusion/heal.ts b/automation/src/fusion/heal.ts new file mode 100644 index 0000000000000000000000000000000000000000..7325790391545d6f6d86eddb52901612dc95e971 --- /dev/null +++ b/automation/src/fusion/heal.ts @@ -0,0 +1,103 @@ +/** + * Self-healing of control names, as pure functions (no browser): when Oracle relabels a field, button or menu entry, + * which of the names the page shows does the test mean? Deliberately strict: a heal that picks the wrong control would + * make a test pass for the wrong reason, so it takes a single, unambiguous candidate or nothing. Business assertions + * (statuses, amounts, messages) never come through here: ui.ts calls this only to LOCATE a control. + */ + +export type HealKind = 'field' | 'button' | 'menu'; +/** How the name was found, in the order tried: a person approved it, only case/space/punctuation differ, a close name. */ +export type HealHow = 'approved' | 'normalised' | 'close'; + +/** One decided heal (the run's FPT_HEALS, a JSON array): `wanted` is shown as `to` on this pod, optionally only on `where`. + * A rejected one says a person looked and `to` is NOT that control: no heal may pick it. */ +export interface HealRule { kind: HealKind; wanted: string; to: string; where?: string; rejected?: boolean } + +const applies = (r: HealRule, kind: HealKind, wanted: string, where: string) => + r.kind === kind && normalise(r.wanted) === normalise(wanted) && (!r.where || normalise(r.where) === normalise(where)); + +/** The closeness (0..1) two names must reach to count as the same control. 0.85 lets "Invoice Number" match "Invoice Num." + * but not "Validate" for "Invalidate" (0.8) or "Cancel" for "Cancel Invoice". */ +export const CLOSE = 0.85; +/** A name must be this much closer than the runner-up, so two similar controls ("Amount 1", "Amount 2") are never guessed. */ +export const GAP = 0.1; + +/** A name as a person reads it: no case, no punctuation, one space between words; Fusion's "(Required)" and a table + * cell's ": " suffix are not part of the name. */ +export function normalise(s: string): string { + return s.replace(/\(\s*required\s*\)/gi, ' ').replace(/:\s*\d+\s*$/, '') + .toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim(); +} + +/** 1 - (edit distance / longer length) of two names, 0..1. */ +export function similarity(a: string, b: string): number { + if (a === b) return 1; + const n = Math.max(a.length, b.length); + if (!n) return 1; + let prev = Array.from({ length: b.length + 1 }, (_, j) => j); + for (let i = 1; i <= a.length; i++) { + const row = [i]; + for (let j = 1; j <= b.length; j++) row.push(Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1))); + prev = row; + } + return 1 - prev[b.length] / n; +} + +const digits = (s: string) => (s.match(/\d+/g) ?? []).join(','); + +/** The one name among `names` that is `wanted` with only case, spaces or punctuation changed; null when none, or when + * two different names qualify. */ +export function normalisedMatch(wanted: string, names: string[]): string | null { + const w = normalise(wanted); + if (!w) return null; + const hits = unique(names.filter((n) => normalise(n) === w)); + return hits.length === 1 ? hits[0] : null; +} + +/** The one name among `names` closer than CLOSE to `wanted`, and GAP closer than any other; null otherwise. Names of + * fewer than 4 letters, and names that differ in a number ("Line 1" / "Line 2"), are never matched this way. */ +export function closeMatch(wanted: string, names: string[]): string | null { + const w = normalise(wanted); + if (w.length < 4) return null; + const scored = unique(names).map((n) => ({ n, k: normalise(n) })).filter(({ k }) => k && k !== w) + .map(({ n, k }) => ({ n, s: similarity(w, k), same: digits(w) === digits(k) })) + .sort((x, y) => y.s - x.s); + const [best, next] = scored; + if (!best || !best.same || best.s < CLOSE) return null; + return next && best.s - next.s < GAP ? null : best.n; +} + +/** The approved heal for `wanted` (this kind, and this place when the rule names one) that the page really shows now. */ +export function approvedMatch(rules: HealRule[], kind: HealKind, wanted: string, where: string, names: string[]): string | null { + for (const r of rules) { + if (r.rejected || !applies(r, kind, wanted, where)) continue; + const shown = names.find((n) => normalise(n) === normalise(r.to)); + if (shown) return shown; + } + return null; +} + +/** What to use instead of `wanted`: an approved heal, else the same name written differently, else a close name. */ +export function pick(rules: HealRule[], kind: HealKind, wanted: string, where: string, names: string[]): { used: string; how: HealHow } | null { + const approved = approvedMatch(rules, kind, wanted, where, names); + if (approved) return { used: approved, how: 'approved' }; + const refused = new Set(rules.filter((r) => r.rejected && applies(r, kind, wanted, where)).map((r) => normalise(r.to))); + const ok = (n: string | null) => (n && !refused.has(normalise(n)) ? n : null); + const same = ok(normalisedMatch(wanted, names)); + if (same) return { used: same, how: 'normalised' }; + const close = ok(closeMatch(wanted, names)); + return close ? { used: close, how: 'close' } : null; +} + +/** The approved heals of the run (FPT_HEALS): a JSON array; anything malformed is ignored, never an error. */ +export function parseHeals(raw: string | undefined): HealRule[] { + if (!raw) return []; + try { + const list = JSON.parse(raw); + return Array.isArray(list) + ? list.filter((r): r is HealRule => !!r && ['field', 'button', 'menu'].includes(r.kind) && typeof r.wanted === 'string' && typeof r.to === 'string') + : []; + } catch { return []; } +} + +const unique = (xs: string[]) => Array.from(new Set(xs)); diff --git a/automation/src/fusion/rest.ts b/automation/src/fusion/rest.ts index eb6eee41144aac45d413b777c99d5fd49a0dd72c..ce8f575cd14ee5dda2cb11f635b5c450a5530ac4 100644 --- a/automation/src/fusion/rest.ts +++ b/automation/src/fusion/rest.ts @@ -1,113 +1,329 @@ -import { fusionEnv } from './ui'; - -/* - * Fusion REST, used ONLY to check what a UI step did (precisely, without screen scraping) and to clean up test data. - * The step under test always runs through the Fusion screens. Credentials come from the environment, never from code. - * Node's own fetch is used on purpose, not Playwright's request context: Playwright traces record request headers, - * and the Basic authorization header carries the password. - */ -const API = '/fscmRestApi/resources/11.13.18.05'; - -export interface Invoice { - InvoiceId: number; InvoiceNumber: string; InvoiceAmount: number; ValidationStatus: string; CanceledFlag: boolean; - ActiveHoldFlag?: boolean; BusinessUnit: string; Supplier: string; [k: string]: unknown; -} -export interface InvoiceHold { HoldId: number; HoldName: string; HoldReason?: string; ReleaseName?: string | null; [k: string]: unknown } - -const q = (s: string) => s.replace(/'/g, "''"); - -/** What a step expects of an invoice in Fusion (business action expect_invoice). */ -export interface InvoiceExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean } - -/** A status as the page and REST both mean it: case, spacing and the British "Cancelled" do not matter. */ -const spelling = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' ').replace('cancelled', 'canceled'); - -/** Every way the invoice differs from what is expected, in words (empty: as expected). `amountAtLeast` is for the - * invoice total when the pod adds tax on top of the lines: the total is then the amount plus that tax. */ -export function invoiceProblems(number: string, inv: Invoice | null, want: InvoiceExpectation): string[] { - if (!inv) return [`invoice ${number} is not in Fusion`]; - const out: string[] = []; - const amount = Number(inv.InvoiceAmount); - if (want.status && spelling(String(inv.ValidationStatus ?? '')) !== spelling(want.status) - && !(spelling(want.status) === 'canceled' && inv.CanceledFlag)) { - out.push(`its status is "${inv.ValidationStatus ?? ''}", expected "${want.status}"`); - } - if (want.amount !== undefined && !(Math.abs(amount - want.amount) < 0.005)) out.push(`its amount is ${inv.InvoiceAmount}, expected ${want.amount}`); - if (want.amountAtLeast !== undefined && !(amount >= want.amountAtLeast - 0.005)) { - out.push(`its amount is ${inv.InvoiceAmount}, expected at least ${want.amountAtLeast}`); - } - if (want.canceled !== undefined && !!inv.CanceledFlag !== want.canceled) out.push(want.canceled ? 'it is not canceled' : 'it is canceled'); - return out; -} - -/** The holds still on the invoice: a released hold carries the name of its release. */ -export const activeHolds = (holds: InvoiceHold[]) => holds.filter((h) => !h.ReleaseName); - -export class FusionRest { - private readonly baseUrl: string; - - constructor() { - const { baseUrl, username, password } = fusionEnv(); - if (!baseUrl || !username || !password) throw new Error('FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD must be set for a Fusion run'); - this.baseUrl = baseUrl; - } - - private async call(method: 'GET' | 'POST', path: string, body?: unknown, contentType?: string): Promise<{ status: number; text: string }> { - const { username, password } = fusionEnv(); - const res = await fetch(`${this.baseUrl}${API}/${path}`, { - method, - headers: { - Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`, - Accept: 'application/json', - ...(contentType ? { 'Content-Type': contentType } : {}), - }, - body: body === undefined ? undefined : JSON.stringify(body), - signal: AbortSignal.timeout(120_000), - }); - return { status: res.status, text: await res.text() }; - } - - private async get(resource: string, query: string): Promise { - const params = new URLSearchParams({ q: query, onlyData: 'true', limit: '100' }); - const r = await this.call('GET', `${resource}?${params}`); - if (r.status !== 200) throw new Error(`GET ${resource} failed: HTTP ${r.status} ${r.text.slice(0, 300)}`); - return (JSON.parse(r.text).items || []) as T[]; - } - - /** Every invoice with this number for the supplier (more than one would mean a duplicate got through). */ - invoices(number: string, supplier: string): Promise { - return this.get('invoices', `InvoiceNumber='${q(number)}';Supplier='${q(supplier)}'`); - } - - async invoice(number: string, supplier: string): Promise { - return (await this.invoices(number, supplier))[0] || null; - } - - /** The invoice with this number, whatever its supplier (test numbers are unique per run). */ - async invoiceByNumber(number: string): Promise { - return (await this.get('invoices', `InvoiceNumber='${q(number)}'`))[0] || null; - } - - holds(number: string): Promise { - return this.get('invoiceHolds', `InvoiceNumber='${q(number)}'`); - } - - /** Run an invoice action (validateInvoice, cancelInvoice, ...) the way Fusion's REST service offers it. */ - async invoiceAction(action: string, body: Record): Promise { - const r = await this.call('POST', `invoices/action/${action}`, body, 'application/vnd.oracle.adf.action+json'); - if (r.status < 200 || r.status >= 300) throw new Error(`${action} failed: HTTP ${r.status} ${r.text.slice(0, 300)}`); - return r.text; - } - - /** Clean-up: cancel the test invoice if it exists and is not cancelled yet. Returns what was done. */ - async cancelIfPresent(number: string, businessUnit: string, supplier: string): Promise { - // a step may have saved it with another of the pod's suppliers than the first (the one Fusion offered): by number - const inv = await this.invoice(number, supplier) ?? await this.invoiceByNumber(number); - if (!inv) return `${number}: not saved, nothing to clean up`; - if (inv.CanceledFlag) return `${number}: already cancelled`; - await this.invoiceAction('cancelInvoice', { InvoiceNumber: number, BusinessUnit: inv.BusinessUnit || businessUnit, Supplier: inv.Supplier || supplier }); - const after = await this.invoice(number, inv.Supplier || supplier); - if (!after?.CanceledFlag) throw new Error(`${number}: cancelInvoice reported success but the invoice is not cancelled`); - return `${number}: cancelled by clean-up`; - } -} +import { fusionEnv } from './ui'; + +/* + * Fusion REST, used ONLY to check what a UI step did (precisely, without screen scraping) and to clean up test data. + * The step under test always runs through the Fusion screens. Credentials come from the environment, never from code. + * Node's own fetch is used on purpose, not Playwright's request context: Playwright traces record request headers, + * and the Basic authorization header carries the password. + * + * Where the Authorization header comes from is a RestAuth: Basic with the test user's password, or (later) an OAuth + * token source registered with useRestAuth(). A pod with assisted sign-in has no password and, until such a source + * exists, no REST: FusionRest.available is false, REST checks are skipped with a note (the screen result stands) and + * clean-up leaves its test records listed for a person. + */ +const API = '/fscmRestApi/resources/11.13.18.05'; + +/** A source of the Authorization header for Fusion REST. */ +export interface RestAuth { + readonly kind: 'basic' | 'oauth'; + header(): Promise; +} + +/** Basic authentication with the test user's name and password (read when needed, never kept in a string field). */ +export class BasicAuth implements RestAuth { + readonly kind = 'basic' as const; + async header(): Promise { + const { username, password } = fusionEnv(); + return `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`; + } +} + +let tokenSource: RestAuth | null = null; + +/** The seam for an OAuth client (a pod with assisted sign-in): a token source registered here is used for REST. */ +export function useRestAuth(source: RestAuth | null): void { tokenSource = source; } + +/** How this run reaches Fusion REST: a registered token source, else Basic with the test user's password, else none. */ +export function restAuth(): RestAuth | null { + if (tokenSource) return tokenSource; + const { username, password } = fusionEnv(); + return username && password ? new BasicAuth() : null; +} + +/** Fusion REST cannot be called on this run (no password and no token source). */ +export class RestUnavailable extends Error {} + +/** The annotation a test gets for each REST check it skipped. */ +export const REST_SKIPPED = 'rest-skipped'; +export const NO_REST_WHY = 'not checked through Fusion REST: this pod uses assisted sign-in, so there is no password for REST; ' + + 'the screen result stands'; + +export interface Invoice { + InvoiceId: number; InvoiceNumber: string; InvoiceAmount: number; ValidationStatus: string; CanceledFlag: boolean; + ActiveHoldFlag?: boolean; BusinessUnit: string; Supplier: string; [k: string]: unknown; +} +export interface InvoiceHold { HoldId: number; HoldName: string; HoldReason?: string; ReleaseName?: string | null; [k: string]: unknown } + +const q = (s: string) => s.replace(/'/g, "''"); + +/** What a step expects of an invoice in Fusion (business action expect_invoice). */ +export interface InvoiceExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean } + +/** A status as the page and REST both mean it: case, spacing and the British "Cancelled" do not matter. */ +const spelling = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' ').replace('cancelled', 'canceled'); + +/** Every way the invoice differs from what is expected, in words (empty: as expected). `amountAtLeast` is for the + * invoice total when the pod adds tax on top of the lines: the total is then the amount plus that tax. */ +export function invoiceProblems(number: string, inv: Invoice | null, want: InvoiceExpectation): string[] { + if (!inv) return [`invoice ${number} is not in Fusion`]; + const out: string[] = []; + const amount = Number(inv.InvoiceAmount); + if (want.status && spelling(String(inv.ValidationStatus ?? '')) !== spelling(want.status) + && !(spelling(want.status) === 'canceled' && inv.CanceledFlag)) { + out.push(`its status is "${inv.ValidationStatus ?? ''}", expected "${want.status}"`); + } + if (want.amount !== undefined && !(Math.abs(amount - want.amount) < 0.005)) out.push(`its amount is ${inv.InvoiceAmount}, expected ${want.amount}`); + if (want.amountAtLeast !== undefined && !(amount >= want.amountAtLeast - 0.005)) { + out.push(`its amount is ${inv.InvoiceAmount}, expected at least ${want.amountAtLeast}`); + } + if (want.canceled !== undefined && !!inv.CanceledFlag !== want.canceled) out.push(want.canceled ? 'it is not canceled' : 'it is canceled'); + return out; +} + +/** The holds still on the invoice: a released hold carries the name of its release. */ +export const activeHolds = (holds: InvoiceHold[]) => holds.filter((h) => !h.ReleaseName); + +/* + * Purchasing and General Ledger. Every test document carries the test's own FPT- tag where Fusion keeps a free text + * (a requisition's and an order's Description, a journal batch's name): the number Fusion gives a requisition or an + * order is only known after the save, so the tag is what clean-up registers BEFORE the save and what REST finds the + * document by. Attribute names are the documented ones of 11.13.18.05; where pods and releases differ, several are read. + */ +export interface Requisition { RequisitionHeaderId: number; Requisition: string; Description?: string; DocumentStatus?: string; + DocumentStatusCode?: string; RequisitioningBU?: string; [k: string]: unknown } +export interface PurchaseOrder { POHeaderId: number; OrderNumber: string; Description?: string; Status?: string; StatusCode?: string; + ProcurementBU?: string; Supplier?: string; Total?: number; Ordered?: number; [k: string]: unknown } +export interface JournalBatch { JeBatchId: number; BatchName: string; Status?: string; StatusMeaning?: string; [k: string]: unknown } + +/** What a step expects of a requisition, an order or a journal batch (expect_requisition, expect_purchase_order, + * expect_journal). */ +export interface DocExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean; posted?: boolean } + +/** A requisition's status in words (DocumentStatus; the code when a pod returns only that). */ +export const requisitionStatus = (r: Requisition) => String(r.DocumentStatus || r.DocumentStatusCode || '').trim(); + +/** An order's status in words ("Open", "Pending Approval", "Incomplete", "Canceled", ...). */ +export const orderStatus = (o: PurchaseOrder) => String(o.Status || o.StatusCode || '').trim(); + +/** An order's amount: its total, or the ordered amount on pods that return only that. NaN when it carries neither. */ +export const orderAmount = (o: PurchaseOrder) => Number(['Total', 'Ordered', 'TotalAmount', 'Amount'].map((k) => o[k]) + .find((v) => v !== undefined && v !== null && v !== '') ?? NaN); + +/** A journal batch's status in words: StatusMeaning, else Fusion's one-letter code (P posted, U unposted, S selected for + * posting, I posting in process; any other code is a posting error). */ +export function journalStatus(b: JournalBatch): string { + const said = String(b.StatusMeaning || '').trim(); + if (said) return said; + const code = String(b.Status || '').trim(); + return ({ P: 'Posted', U: 'Unposted', S: 'Selected for posting', I: 'Posting in process' } as Record)[code.toUpperCase()] ?? code; +} + +export const journalPosted = (b: JournalBatch) => String(b.Status || '').trim().toUpperCase() === 'P' || spelling(journalStatus(b)) === 'posted'; + +/** A requisition or order that is out of the way: cancelled, or (a requisition) withdrawn. */ +const canceledStatus = (s: string) => /^(canceled|withdrawn)$/.test(spelling(s)); + +/** Every way a document differs from what is expected, in words (empty: as expected). `what` names it ("order 1234"). */ +function docProblems(what: string, status: string, amount: number, posted: boolean | undefined, want: DocExpectation): string[] { + const out: string[] = []; + const shown = (n: number) => (Number.isNaN(n) ? 'not given by Fusion' : String(n)); + if (want.status && spelling(status) !== spelling(want.status)) out.push(`its status is "${status}", expected "${want.status}"`); + if (want.amount !== undefined && !(Math.abs(amount - want.amount) < 0.005)) out.push(`its amount is ${shown(amount)}, expected ${want.amount}`); + if (want.amountAtLeast !== undefined && !(amount >= want.amountAtLeast - 0.005)) { + out.push(`its amount is ${shown(amount)}, expected at least ${want.amountAtLeast}`); + } + if (want.canceled !== undefined && canceledStatus(status) !== want.canceled) out.push(want.canceled ? 'it is not canceled' : 'it is canceled'); + if (want.posted !== undefined && posted !== want.posted) out.push(want.posted ? `it is not posted (${status || 'no status'})` : 'it is posted'); + return out.map((p) => `${what}: ${p}`); +} + +export function requisitionProblems(number: string, r: Requisition | null, want: DocExpectation): string[] { + if (!r) return [`requisition ${number} is not in Fusion`]; + return docProblems(`requisition ${number}`, requisitionStatus(r), NaN, undefined, want); +} + +export function purchaseOrderProblems(number: string, o: PurchaseOrder | null, want: DocExpectation): string[] { + if (!o) return [`purchase order ${number} is not in Fusion`]; + return docProblems(`purchase order ${number}`, orderStatus(o), orderAmount(o), undefined, want); +} + +export function journalProblems(name: string, b: JournalBatch | null, want: DocExpectation): string[] { + if (!b) return [`journal batch ${name} is not in Fusion`]; + return docProblems(`journal batch ${name}`, journalStatus(b), NaN, journalPosted(b), want); +} + +/** Clean-up that REST cannot do (a submitted requisition: Fusion's REST service offers no cancel for it): the fixture + * does it on the screens instead, then asks REST again. */ +export class NeedsScreen extends Error {} + +export class FusionRest { + private readonly baseUrl: string; + private readonly auth: RestAuth | null; + + constructor(auth: RestAuth | null = restAuth()) { + const { baseUrl } = fusionEnv(); + if (!baseUrl) throw new Error('FUSION_BASE_URL must be set for a Fusion run'); + if (!auth && !process.env.FPT_SIGN_IN_MODE) throw new Error('FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD must be set for a Fusion run'); + this.baseUrl = baseUrl; + this.auth = auth; + } + + /** REST can be called on this run (false on a pod with assisted sign-in until an OAuth token source exists). */ + get available(): boolean { return !!this.auth; } + + private async call(method: 'GET' | 'POST' | 'DELETE', path: string, body?: unknown, contentType?: string): Promise<{ status: number; text: string }> { + if (!this.auth) throw new RestUnavailable(NO_REST_WHY); + const res = await fetch(`${this.baseUrl}${API}/${path}`, { + method, + headers: { + Authorization: await this.auth.header(), + Accept: 'application/json', + ...(contentType ? { 'Content-Type': contentType } : {}), + }, + body: body === undefined ? undefined : JSON.stringify(body), + signal: AbortSignal.timeout(120_000), + }); + return { status: res.status, text: await res.text() }; + } + + private async get(resource: string, query: string): Promise { + const params = new URLSearchParams({ q: query, onlyData: 'true', limit: '100' }); + const r = await this.call('GET', `${resource}?${params}`); + if (r.status !== 200) throw new Error(`GET ${resource} failed: HTTP ${r.status} ${r.text.slice(0, 300)}`); + return (JSON.parse(r.text).items || []) as T[]; + } + + /** Every invoice with this number for the supplier (more than one would mean a duplicate got through). */ + invoices(number: string, supplier: string): Promise { + return this.get('invoices', `InvoiceNumber='${q(number)}';Supplier='${q(supplier)}'`); + } + + async invoice(number: string, supplier: string): Promise { + return (await this.invoices(number, supplier))[0] || null; + } + + /** The invoice with this number, whatever its supplier (test numbers are unique per run). */ + async invoiceByNumber(number: string): Promise { + return (await this.get('invoices', `InvoiceNumber='${q(number)}'`))[0] || null; + } + + holds(number: string): Promise { + return this.get('invoiceHolds', `InvoiceNumber='${q(number)}'`); + } + + /** Run an invoice action (validateInvoice, cancelInvoice, ...) the way Fusion's REST service offers it. */ + async invoiceAction(action: string, body: Record): Promise { + const r = await this.call('POST', `invoices/action/${action}`, body, 'application/vnd.oracle.adf.action+json'); + if (r.status < 200 || r.status >= 300) throw new Error(`${action} failed: HTTP ${r.status} ${r.text.slice(0, 300)}`); + return r.text; + } + + /** Clean-up: cancel the test invoice if it exists and is not cancelled yet. Returns what was done. */ + async cancelIfPresent(number: string, businessUnit: string, supplier: string): Promise { + // a step may have saved it with another of the pod's suppliers than the first (the one Fusion offered): by number + const inv = await this.invoice(number, supplier) ?? await this.invoiceByNumber(number); + if (!inv) return `${number}: not saved, nothing to clean up`; + if (inv.CanceledFlag) return `${number}: already cancelled`; + await this.invoiceAction('cancelInvoice', { InvoiceNumber: number, BusinessUnit: inv.BusinessUnit || businessUnit, Supplier: inv.Supplier || supplier }); + const after = await this.invoice(number, inv.Supplier || supplier); + if (!after?.CanceledFlag) throw new Error(`${number}: cancelInvoice reported success but the invoice is not cancelled`); + return `${number}: cancelled by clean-up`; + } + + /** The first item of a resource matching `query`, or null. A query the resource refuses (an attribute this pod does not + * have: HTTP 400) answers null, so the caller's next way of finding it is tried. */ + private async first(resource: string, query: string): Promise { + try { return (await this.get(resource, query))[0] || null; } catch (e) { + if (/HTTP 400\b/.test(String((e as Error).message))) return null; + throw e; + } + } + + /** The requisition with this number (Requisition), else the one whose Description starts with the test's tag. */ + async requisition(numberOrTag: string): Promise { + return await this.first('purchaseRequisitions', `Requisition='${q(numberOrTag)}'`) + ?? await this.first('purchaseRequisitions', `Description LIKE '${q(numberOrTag)}%'`); + } + + /** The order with this number, else the one whose Description starts with the test's tag. Orders not submitted yet + * (Incomplete) are drafts: on pods that keep them out of purchaseOrders, draftPurchaseOrders has them. */ + async purchaseOrder(numberOrTag: string): Promise<(PurchaseOrder & { draft?: boolean }) | null> { + for (const resource of ['purchaseOrders', 'draftPurchaseOrders']) { + const o = await this.first(resource, `OrderNumber='${q(numberOrTag)}'`) + ?? await this.first(resource, `Description LIKE '${q(numberOrTag)}%'`); + if (o) return resource === 'draftPurchaseOrders' ? { ...o, draft: true } : o; + } + return null; + } + + async journalBatch(name: string): Promise { + return this.first('journalBatches', `BatchName='${q(name)}'`); + } + + /** The batches whose name holds the test's batch name: the batch itself and the reversal Fusion makes of it (Fusion + * names a reversal after the batch it reverses). Null when this pod refuses the LIKE query. */ + async journalBatchesNamed(name: string): Promise { + try { return await this.get('journalBatches', `BatchName LIKE '%${q(name)}%'`); } catch (e) { + if (/HTTP 400\b/.test(String((e as Error).message))) return null; + throw e; + } + } + + private async remove(path: string, what: string): Promise { + const r = await this.call('DELETE', path); + if (r.status < 200 || r.status >= 300) throw new Error(`${what}: Fusion refused the delete (HTTP ${r.status} ${r.text.slice(0, 200)})`); + } + + /** Clean-up of a test requisition (found by its tag): an Incomplete one is deleted; a canceled, withdrawn or rejected + * one needs nothing. A submitted one has no cancel over REST: NeedsScreen, and the fixture cancels it on the screens. */ + async cleanRequisition(tag: string): Promise { + const r = await this.requisition(tag); + if (!r) return `${tag}: no requisition saved, nothing to clean up`; + const status = requisitionStatus(r); + if (/^(canceled|withdrawn|rejected)$/.test(spelling(status))) return `requisition ${r.Requisition}: already ${status.toLowerCase()}`; + if (spelling(status) === 'incomplete') { + await this.remove(`purchaseRequisitions/${r.RequisitionHeaderId}`, `requisition ${r.Requisition}`); + if (await this.requisition(tag)) throw new Error(`requisition ${r.Requisition}: Fusion accepted the delete but it is still there`); + return `requisition ${r.Requisition}: deleted by clean-up (never submitted)`; + } + throw new NeedsScreen(`requisition ${r.Requisition} is ${status}: it is cancelled on Manage Requisitions`); + } + + /** Clean-up of a test order (found by its tag): an Incomplete draft is deleted, an open one cancelled with Fusion's + * cancel action; canceled and closed ones need nothing. One pending approval cannot be cancelled until it is + * withdrawn, and a cancel action this pod does not offer is done on the screens: NeedsScreen for both. */ + async cleanPurchaseOrder(tag: string): Promise { + const o = await this.purchaseOrder(tag); + if (!o) return `${tag}: no purchase order saved, nothing to clean up`; + const status = orderStatus(o); + const s = spelling(status); + if (s === 'canceled' || s.includes('closed')) return `purchase order ${o.OrderNumber}: already ${status.toLowerCase()}`; + if (s === 'incomplete') { + await this.remove(`draftPurchaseOrders/${o.POHeaderId}`, `purchase order ${o.OrderNumber}`); + return `purchase order ${o.OrderNumber}: deleted by clean-up (never submitted)`; + } + if (s.includes('pending')) throw new NeedsScreen(`purchase order ${o.OrderNumber} is ${status}: it is withdrawn and deleted on the screens`); + const r = await this.call('POST', `purchaseOrders/${o.POHeaderId}/action/cancel`, {}, 'application/vnd.oracle.adf.action+json'); + if (r.status < 200 || r.status >= 300) throw new NeedsScreen(`purchase order ${o.OrderNumber}: the cancel action answered HTTP ${r.status}`); + const after = await this.purchaseOrder(o.OrderNumber); + if (after && spelling(orderStatus(after)) !== 'canceled') { + throw new Error(`purchase order ${o.OrderNumber}: the cancel action answered but its status is ${orderStatus(after)}`); + } + return `purchase order ${o.OrderNumber}: cancelled by clean-up`; + } + + /** Clean-up of a test journal batch and of the reversal Fusion made of it: an unposted one is deleted. A posted one + * stays (Fusion never deletes a posted journal): the test's journals debit and credit the same amount on the same + * account, so a posted one leaves every balance as it was. */ + async cleanJournal(name: string): Promise { + const batches = (await this.journalBatchesNamed(name)) ?? [await this.journalBatch(name)].filter((b): b is JournalBatch => !!b); + if (!batches.length) return `${name}: no journal saved, nothing to clean up`; + const done: string[] = []; + for (const b of batches) { + if (journalPosted(b)) { done.push(`${b.BatchName}: posted (debit and credit on one account, balances unchanged)`); continue; } + await this.remove(`journalBatches/${b.JeBatchId}`, `journal batch ${b.BatchName}`); + done.push(`${b.BatchName}: deleted by clean-up (unposted)`); + } + return done.join('; '); + } +} diff --git a/automation/src/fusion/session.ts b/automation/src/fusion/session.ts index a6154519ca382d13bd461e22d4d71bbe86832525..704e3592683ed13903c8e2b35b26eefbca3204f8 100644 --- a/automation/src/fusion/session.ts +++ b/automation/src/fusion/session.ts @@ -1,42 +1,73 @@ -// One sign-in for the whole run (playwright.fusion.config.ts globalSetup / globalTeardown): the test user signs in once, -// and every test starts from that session instead of signing in again (20-60 s each). The session file holds Fusion's -// session cookies (never the password), sits in the run's own folder and is deleted when the run ends. When the -// sign-in here fails, an empty session is written and each test signs in by itself, as before. -import * as fs from 'fs'; -import * as path from 'path'; -import { chromium } from '@playwright/test'; -import { FusionUi } from './ui'; - -const EMPTY = { cookies: [], origins: [] }; - -export function sessionFile(): string { - const f = process.env.FPT_FUSION_SESSION_FILE; - if (!f) throw new Error('FPT_FUSION_SESSION_FILE is not set (playwright.fusion.config.ts sets it)'); - return f; -} - -export async function setup(): Promise { - const file = sessionFile(); - fs.mkdirSync(path.dirname(file), { recursive: true }); - fs.writeFileSync(file, JSON.stringify(EMPTY), { mode: 0o600 }); - if (!process.env.FUSION_BASE_URL || !process.env.FUSION_USERNAME || !process.env.FUSION_PASSWORD) return; - const browser = await chromium.launch({ headless: true }); - try { - const context = await browser.newContext({ viewport: { width: 1440, height: 900 } }); - const page = await context.newPage(); - page.setDefaultTimeout(60_000); - page.setDefaultNavigationTimeout(120_000); - await new FusionUi(page).signIn(); - await context.storageState({ path: file }); - fs.chmodSync(file, 0o600); - console.log('[session] signed in once for this run; every test reuses the session'); - } catch (e) { - console.log(`[session] one sign-in for the run failed, so each test signs in by itself: ${String((e as Error).message || e).split('\n')[0]}`); - } finally { - await browser.close().catch(() => {}); - } -} - -export async function teardown(): Promise { - try { fs.unlinkSync(sessionFile()); } catch { /* already gone */ } -} +// One sign-in for the whole run (playwright.fusion.config.ts globalSetup / globalTeardown): the test user signs in once, +// and every test starts from that session instead of signing in again (20-60 s each). The session file holds Fusion's +// session cookies (never the password), sits in the run's own folder and is deleted when the run ends. When the +// sign-in here fails, an empty session is written and each test signs in by itself, as before. +// +// Assisted sign-in (FPT_SIGN_IN_MODE=assisted: the pod signs in through the company's identity provider, with MFA): a +// person signed in on Astra's run page, and FPT_FUSION_STORAGE_STATE points to that session (written by Astra or the +// runner for this pass only). It is checked once here; when the pod no longer accepts it, every test of the pass is +// skipped as "sign-in expired" (fixtures.ts) and Astra asks for a new sign-in instead of failing them all. +import * as fs from 'fs'; +import * as path from 'path'; +import { chromium } from '@playwright/test'; +import { assistedSignIn, clearSignInExpired, FusionUi, markSignInExpired } from './ui'; + +const EMPTY = { cookies: [], origins: [] }; + +export function sessionFile(): string { + const f = process.env.FPT_FUSION_SESSION_FILE; + if (!f) throw new Error('FPT_FUSION_SESSION_FILE is not set (playwright.fusion.config.ts sets it)'); + return f; +} + +/** Assisted sign-in: the session a person signed in becomes this run's session, if the pod still accepts it. */ +async function provided(file: string): Promise { + const given = process.env.FPT_FUSION_STORAGE_STATE; + if (!given || !fs.existsSync(given)) { + markSignInExpired('Sign-in expired: no signed-in session was given for this pod (assisted sign-in); Astra asks a person to sign in.'); + return; + } + fs.writeFileSync(file, fs.readFileSync(given), { mode: 0o600 }); + if (!process.env.FUSION_BASE_URL) return; + const browser = await chromium.launch({ headless: true }); + try { + const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, storageState: file }); + const page = await context.newPage(); + page.setDefaultNavigationTimeout(120_000); + if (await new FusionUi(page).isSignedIn()) console.log('[session] the session a person signed in is accepted; every test reuses it'); + else markSignInExpired('Sign-in expired: the pod no longer accepts the session a person signed in (assisted sign-in); Astra asks for a new sign-in.'); + } catch (e) { + console.log(`[session] the signed-in session could not be checked, the tests try it: ${String((e as Error).message || e).split('\n')[0]}`); + } finally { + await browser.close().catch(() => {}); + } +} + +export async function setup(): Promise { + const file = sessionFile(); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify(EMPTY), { mode: 0o600 }); + clearSignInExpired(); + if (assistedSignIn()) return provided(file); + if (!process.env.FUSION_BASE_URL || !process.env.FUSION_USERNAME || !process.env.FUSION_PASSWORD) return; + const browser = await chromium.launch({ headless: true }); + try { + const context = await browser.newContext({ viewport: { width: 1440, height: 900 } }); + const page = await context.newPage(); + page.setDefaultTimeout(60_000); + page.setDefaultNavigationTimeout(120_000); + await new FusionUi(page).signIn(); + await context.storageState({ path: file }); + fs.chmodSync(file, 0o600); + console.log('[session] signed in once for this run; every test reuses the session'); + } catch (e) { + console.log(`[session] one sign-in for the run failed, so each test signs in by itself: ${String((e as Error).message || e).split('\n')[0]}`); + } finally { + await browser.close().catch(() => {}); + } +} + +export async function teardown(): Promise { + try { fs.unlinkSync(sessionFile()); } catch { /* already gone */ } + clearSignInExpired(); +} diff --git a/automation/src/fusion/steps.ts b/automation/src/fusion/steps.ts index 36351c5457f32f090bb0b026e08f75d427fada51..e192ce314ecbca771ba2d4f8e2d4bac2c632f03d 100644 --- a/automation/src/fusion/steps.ts +++ b/automation/src/fusion/steps.ts @@ -1,295 +1,511 @@ -import * as fs from 'fs'; -import * as path from 'path'; -import YAML from 'yaml'; -import { expect, test } from './fixtures'; -import { activeHolds, invoiceProblems, type FusionRest, type InvoiceExpectation } from './rest'; -import { apDataSets, fusionDate, podCandidates, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui'; - -/* - * Step runner: executes a scenario written as plain steps in tests/cases/.yaml (runner: steps), with no - * hand-written code. Each step names one proven Fusion action; the model (or a consultant) writes the steps, Playwright - * runs them the same way every time. Unknown actions fail the step with a clear message, never guess. - * - * Step fields: action, field, value, expected (shown in the report and the live view). - * Values may use {{pod..}} (the pod's test data, e.g. {{pod.ap.supplier}}), {{today}}, {{unique:TAG}}, - * {{tv.}} and {{saved.}} (a value remembered by an earlier `remember` step). - * - * Business actions (Payables first) do a whole piece of business the proven way, so a scenario made of them does not - * break on every Fusion quirk: create_invoice, validate_invoice, find_invoice, cancel_invoice, expect_invoice, - * expect_hold, expect_no_holds. Their extra fields: lines, status, amount, amount_at_least, canceled. A canary scenario - * per area (tests/cases/CANARY-.yaml) runs each of them once before a run, to prove they still work on the pod. - */ -export interface Step { n?: number; action: string; field?: string; value?: string | number; expected?: string; name?: string; fields?: string[]; - lines?: (string | number)[]; status?: string; amount?: string | number; amount_at_least?: string | number; canceled?: boolean } -export interface StepCase { id: string; title: string; runner?: string; steps: Step[]; test_values?: Record; - canary?: boolean } // a canary (tests/cases/CANARY-.yaml): create_invoice tries the pod's data sets in turn - -const CASES_DIR = path.join(__dirname, '..', '..', '..', 'tests', 'cases'); - -/** - * The scenario's YAML: from `dir` when given (a staged AI draft's own folder), else from FPT_STEPS_DIR when it holds - * that id (the co-worker's staging folder for drafts), else from the script library tests/cases/. - */ -export function stepCaseFile(id: string, dir?: string): string { - for (const d of [dir, process.env.FPT_STEPS_DIR]) { - if (d && fs.existsSync(path.join(d, `${id}.yaml`))) return path.join(d, `${id}.yaml`); - } - return path.join(CASES_DIR, `${id}.yaml`); -} - -export function loadStepCase(id: string, dir?: string): StepCase { - const f = stepCaseFile(id, dir); - const c = YAML.parse(fs.readFileSync(f, 'utf8')) as StepCase; - if (c.runner !== 'steps') throw new Error(`${id}: runner is not "steps"`); - return c; -} - -type Ctx = { ui: FusionUi; c: StepCase; saved: Record; uniques: Record; track: (n: string) => string; - chosen: Record; // the pod value Fusion accepted, per "area.key", used again for the rest of the test - rest: FusionRest }; // Fusion REST, for the business actions that check what the screens did - -function fill(raw: unknown, ctx: Ctx): string { - return String(raw ?? '').replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_m, key: string) => { - const pod = /^pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)$/i.exec(key); - if (pod) return ctx.chosen[`${pod[1]}.${pod[2]}`.toLowerCase()] ?? podValue(pod[1], pod[2]); // the pod's own test data - if (key === 'today') return fusionDate(); - if (key.startsWith('unique:')) { const t = key.slice(7); return (ctx.uniques[t] ??= testNumber(t)); } - if (key.startsWith('tv.')) return String(ctx.c.test_values?.[key.slice(3)] ?? ''); - if (key.startsWith('saved.')) return ctx.saved[key.slice(6)] ?? ''; - throw new Error(`unknown placeholder {{${key}}}`); - }); -} - -/** Enter a value. A value that is exactly one pod test data placeholder ({{pod.ap.business_unit}}) is tried with each - * value the pod has for it, in order, until Fusion accepts one (a business unit this user may use, a source that - * exists on this pod): the first that works is kept for the rest of the test and remembered for the next run. */ -async function putValue(s: Step, ctx: Ctx, put: (v: string) => Promise): Promise { - const ref = /^\s*\{\{\s*pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)\s*\}\}\s*$/i.exec(String(s.value ?? '')); - const key = ref ? `${ref[1]}.${ref[2]}`.toLowerCase() : ''; - if (!ref || ctx.chosen[key]) return put(fill(s.value, ctx)); - const tried: string[] = []; - for (const v of podCandidates(ref[1], ref[2])) { - try { - await put(v); - ctx.chosen[key] = v; - used(ref[1], ref[2], v, true); - return; - } catch (e) { - if (!(e instanceof ValueRefused)) throw e; - used(ref[1], ref[2], v, false); - tried.push(v); - } - } - throw new Error(`Fusion accepted none of the ${tried.length} value(s) this pod has for ${ref[2].replace(/_/g, ' ')} in ` + - `"${s.field}" (${tried.join(', ')}): this test user is not offered any of them; set one it may use on the Test environments page`); -} - -/** The invoice a business action works on: the number create_invoice (or a `remember` step) stored under the step's - * `name`, "invoice_number" when it names none. */ -function invoiceNumber(s: Step, ctx: Ctx): string { - const name = s.name || 'invoice_number'; - const n = ctx.saved[name]; - if (!n) throw new Error(`${s.action} needs an invoice: no invoice number is remembered as "${name}" (create_invoice or remember it first)`); - return n; -} - -/** A number a step gives (an amount), filled in from its placeholders. */ -function amountOf(raw: string | number, ctx: Ctx, what: string): number { - const v = Number(fill(raw, ctx).replace(/,/g, '')); - if (!Number.isFinite(v)) throw new Error(`${what} must be a number, got "${fill(raw, ctx)}"`); - return v; -} - -/** Ask Fusion (REST) until `problems` comes back empty: REST can lag a few seconds behind what the screen saved. Fails - * with the last problems in words. */ -async function untilRight(problems: () => Promise, what: string, timeoutMs = 60_000) { - const end = Date.now() + timeoutMs; - for (;;) { - const p = await problems(); - if (!p.length) return; - if (Date.now() > end) throw new Error(`${what}: ${p.join('; ')}`); - await new Promise((r) => setTimeout(r, 3000)); - } -} - -/** The pod values to try for an AP test data key: the one Fusion already took in this test, else the pod's candidates. */ -const apChoices = (ctx: Ctx, key: string) => ctx.chosen[`ap.${key}`] ? [ctx.chosen[`ap.${key}`]] : podCandidates('ap', key); - -/** The pod's supplier sites to try when Fusion leaves Supplier Site empty (none: the first site Fusion lists). */ -const apSites = (ctx: Ctx) => { try { return apChoices(ctx, 'supplier_site'); } catch { return []; } }; - -const errorText = (e: unknown) => String((e as Error)?.message || e).split('\n')[0].slice(0, 200); - -/** The canary's create_invoice: the pod's Payables data sets (apDataSets) in turn until one creates AND validates an - * invoice. A shared pod's sampled data can be whoever used it last (a supplier without a default site, an account of - * another ledger); the set that works is recorded as accepted (FPT_TESTDATA_USED), so the co-worker learns it and the - * run's other scenarios and the next run try it first. When no set validates, the first set that saved is kept, so - * the canary's own validate_invoice step shows what is broken; when none saves, create_invoice fails with each reason. */ -async function createWithDataSets(ctx: Ctx, h: { amount: string; lines: string[]; name: string }) { - const sets = apDataSets(); - const why: string[] = []; - let saved: ApDataSet | null = null; - let last = false; // the invoice the last set saved is the one on the page - const create = async (set: ApDataSet, k: number) => { - const number = ctx.track(testNumber(`${ctx.c.id.replace(/[^A-Za-z0-9]/g, '')}${k || ''}`)); - const got = await ctx.ui.createInvoice({ businessUnit: set.businessUnit, supplier: set.supplier, site: set.site, number, - amount: h.amount, lines: h.lines, account: set.account }); - ctx.saved[h.name] = number; - return got; - }; - for (const [k, set] of sets.entries()) { - const label = `${set.businessUnit} / ${set.supplier}`; - last = false; - let got; - try { got = await create(set, k); } catch (e) { why.push(`${label}: ${errorText(e)}`); continue; } - saved ??= set; - last = true; - try { - await ctx.ui.validateInvoice(); - await ctx.ui.expectStatus('Validated', ctx.saved[h.name]); - } catch (e) { why.push(`${label}: saved but did not validate (${errorText(e)})`); continue; } - for (const [key, v] of [['business_unit', got.businessUnit], ['supplier', got.supplier], ['supplier_site', got.site], ['account', got.account]]) { - if (v) { used('AP', key, v, true); ctx.chosen[`ap.${key}`] = v; } - } - if (k) console.log(`[canary] Payables data set ${k + 1} of ${sets.length} works (${label}); tried: ${why.join(' | ')}`); - return; - } - if (!saved) throw new Error(`create_invoice failed with each of the pod's ${sets.length} Payables data set(s): ${why.join(' | ')}`); - console.log(`[canary] no Payables data set validates: ${why.join(' | ')}`); - if (!last) await create(saved, sets.length); -} - -/** The proven actions. Optional ones call a FusionUi method only if that building block exists. */ -const ACTIONS: Record Promise> = { - sign_in: async (_s, { ui }) => ui.signIn(), - open_task: async (s, ctx) => { - await ctx.ui.openPath(fill(s.value, ctx)); // "Group > Page > Task", or "Group > Action" for a quick action - }, - enter: async (s, ctx) => { - if (!s.field) throw new Error('enter needs a field'); - if (s.field === 'Number') ctx.track(fill(s.value, ctx)); // a saved test invoice is cancelled after the test, pass or fail - await putValue(s, ctx, (v) => ctx.ui.put(s.field!, v)); - }, - expect_filled: async (s, ctx) => { for (const f of s.fields ?? (s.field ? [s.field] : [])) await ctx.ui.expectFilled(f); }, - expect_value: async (s, ctx) => { - if (!s.field) throw new Error('expect_value needs a field'); - await expect.poll(() => ctx.ui.value(s.field!), { message: `${s.field} should be "${fill(s.value, ctx)}"`, timeout: 30_000 }).toBe(fill(s.value, ctx)); - }, - remember: async (s, ctx) => { if (!s.field || !s.name) throw new Error('remember needs field and name'); ctx.saved[s.name] = await ctx.ui.value(s.field); }, - click: async (s, ctx) => { - const name = fill(s.value, ctx); - await ctx.ui.pressEnabled(ctx.ui.page.getByRole('button', { name, exact: true }).filter({ visible: true }).first(), name); - await ctx.ui.settle(); - }, - confirm_if_asked: async (_s, ctx) => { - const yes = ctx.ui.page.getByRole('button', { name: /^(Yes|OK)$/ }); - if (await yes.count()) { await yes.first().click(); await ctx.ui.settle(); } - }, - // any screen: tables, menus, messages, searches and statuses (the AI writes these for every business area) - add_row: async (s, ctx) => { if (!s.field) throw new Error('add_row needs the table section as field'); await ctx.ui.addRow(s.field); }, - enter_in_row: async (s, ctx) => { - if (!s.field) throw new Error('enter_in_row needs a field'); - await putValue(s, ctx, (v) => ctx.ui.putInRow(s.field!, v)); - }, - menu_action: async (s, ctx) => { - if (!s.field) throw new Error('menu_action needs the menu as field'); - await ctx.ui.menuAction(s.field, fill(s.value, ctx)); - }, - expect_no_error: async (_s, ctx) => ctx.ui.expectNoError(), - expect_message: async (s, ctx) => ctx.ui.expectMessage(fill(s.value, ctx)), - expect_results: async (_s, ctx) => ctx.ui.expectResults(), - cancel_without_saving: async (_s, ctx) => { - await ctx.ui.page.getByRole('button', { name: 'Cancel', exact: true }).first().click(); - await ctx.ui.settle(2000); - await ACTIONS.confirm_if_asked({ action: 'confirm_if_asked' }, ctx); - }, - // Payables business actions - /** Create and save a Payables invoice on its own screen (no open_task before it). value = the invoice amount (default - * {{tv.amount}}); lines = the line amounts (default one line of the whole amount; the amount defaults to their sum); - * name = what to remember the new FPT- number as (default invoice_number, used as {{saved.invoice_number}}). The - * number is registered for clean-up before the save, so the invoice is cancelled after the test, pass or fail. */ - create_invoice: async (s, ctx) => { - const lines = (s.lines ?? []).map((l) => fill(l, ctx)); - const amount = s.value !== undefined && s.value !== '' ? fill(s.value, ctx) - : lines.length ? lines.reduce((sum, l, i) => sum + amountOf(l, ctx, `line ${i + 1}`), 0).toFixed(2) - : ctx.c.test_values?.amount !== undefined ? fill('{{tv.amount}}', ctx) : ''; - if (!amount) throw new Error('create_invoice needs an amount: value, lines, or the test value "amount"'); - if (ctx.c.canary) return createWithDataSets(ctx, { amount, lines, name: s.name || 'invoice_number' }); - const number = ctx.track(testNumber(ctx.c.id.replace(/[^A-Za-z0-9]/g, ''))); - const got = await ctx.ui.createInvoice({ businessUnit: apChoices(ctx, 'business_unit'), supplier: apChoices(ctx, 'supplier'), number, amount, - lines, account: ctx.chosen['ap.account'] ?? podValue('ap', 'account'), site: apSites(ctx) }); - ctx.chosen['ap.business_unit'] = got.businessUnit; - ctx.chosen['ap.supplier'] = got.supplier; - ctx.saved[s.name || 'invoice_number'] = number; - }, - /** Check the invoice in Fusion (REST) by its number. status = the status it must have (Validated, Needs revalidation, - * Canceled ...: matched without regard to case); amount = its exact amount; amount_at_least = at least this amount - * (the pod may add tax on top); canceled = true or false. With none of them, it checks that the invoice exists. */ - expect_invoice: async (s, ctx) => { - const number = invoiceNumber(s, ctx); - const want: InvoiceExpectation = { - status: s.status ? fill(s.status, ctx) : undefined, - amount: s.amount !== undefined ? amountOf(s.amount, ctx, 'amount') : undefined, - amountAtLeast: s.amount_at_least !== undefined ? amountOf(s.amount_at_least, ctx, 'amount_at_least') : undefined, - canceled: s.canceled, - }; - await untilRight(async () => invoiceProblems(number, await ctx.rest.invoiceByNumber(number), want), `invoice ${number} in Fusion`); - }, - /** The invoice carries a hold that is not released: value = the hold's name as Fusion lists it (any case). */ - expect_hold: async (s, ctx) => { - const number = invoiceNumber(s, ctx); - const name = fill(s.value, ctx).trim().toLowerCase(); - if (!name) throw new Error('expect_hold needs the hold name as value'); - await untilRight(async () => { - const holds = activeHolds(await ctx.rest.holds(number)); - return holds.some((h) => String(h.HoldName || '').trim().toLowerCase() === name) ? [] - : [`no "${fill(s.value, ctx)}" hold (holds: ${holds.map((h) => h.HoldName).join(', ') || 'none'})`]; - }, `invoice ${number}`); - }, - /** The invoice carries no hold that is not released (the holds list: 26D no longer returns ActiveHoldFlag). */ - expect_no_holds: async (s, ctx) => { - const number = invoiceNumber(s, ctx); - await untilRight(async () => { - const holds = activeHolds(await ctx.rest.holds(number)); - return holds.length ? [`it is on hold: ${holds.map((h) => h.HoldName).join(', ')}`] : []; - }, `invoice ${number}`, 20_000); - }, -}; - -/** Building blocks that live on FusionUi (added module by module): action name -> method name and argument fields. */ -const UI_BLOCKS: Record unknown[] }> = { - add_line: { method: 'addLine', args: (s, ctx) => [Number((s as { line?: number }).line ?? 1), - { amount: fill(s.value, ctx), account: fill((s as { account?: string }).account ?? '{{pod.ap.account}}', ctx) }] }, - save: { method: 'save', args: () => [] }, - invoice_action: { method: 'invoiceAction', args: (s, ctx) => [fill(s.value, ctx)] }, - validate_invoice: { method: 'validateInvoice', args: () => [] }, - /** Find the invoice remembered as `name` (default invoice_number) on Manage Invoices: exactly it must be listed. */ - find_invoice: { method: 'findInvoice', args: (s, ctx) => [invoiceNumber(s, ctx)] }, - /** Invoice Actions > Cancel Invoice on the invoice remembered as `name`, confirmed: it must then show Canceled. */ - cancel_invoice: { method: 'cancelInvoice', args: (s, ctx) => [invoiceNumber(s, ctx)] }, - expect_status: { method: 'expectStatusText', args: (s, ctx) => [fill(s.value, ctx)] }, -}; - -export const supportedActions = () => [...Object.keys(ACTIONS), ...Object.keys(UI_BLOCKS)]; - -async function runStep(s: Step, ctx: Ctx) { - const direct = ACTIONS[s.action]; - if (direct) return direct(s, ctx); - const block = UI_BLOCKS[s.action]; - const fn = block && (ctx.ui as unknown as Record)[block.method]; - if (typeof fn !== 'function') throw new Error(`step action "${s.action}" is not supported yet (known: ${supportedActions().join(', ')})`); - await (fn as (...a: unknown[]) => Promise).apply(ctx.ui, block.args(s, ctx)); -} - -/** Registers one Playwright test for a steps scenario. Called from the generated tests/fusion/steps/.spec.ts, or - * from a staged draft's entry (opts.dir = the staging folder holding its YAML). */ -export function stepsTest(id: string, tags: string[], opts: { dir?: string } = {}) { - const c = loadStepCase(id, opts.dir); - test(`${id} ${c.title}`, { tag: tags }, async ({ fusion, apInvoices }) => { - const ctx: Ctx = { ui: fusion, c, saved: {}, uniques: {}, track: apInvoices.track, chosen: {}, rest: apInvoices.rest }; - for (const [i, s] of c.steps.entries()) { - const label = `${s.n ?? i + 1}. ${s.action}${s.field ? ` ${s.field}` : ''}${s.value !== undefined ? ` = ${fill(s.value, ctx)}` : ''}`; - await test.step(s.expected ? `${label} (expect: ${s.expected})` : label, () => runStep(s, ctx)); - } - }); -} +import * as fs from 'fs'; +import * as path from 'path'; +import YAML from 'yaml'; +import { expect, test, type DocKind, type FusionDocs } from './fixtures'; +import { activeHolds, invoiceProblems, journalPosted, journalProblems, journalStatus, NO_REST_WHY, purchaseOrderProblems, requisitionProblems, + REST_SKIPPED, type DocExpectation, type FusionRest, type InvoiceExpectation } from './rest'; +import { apDataSets, fusionDate, podCandidates, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui'; + +/* + * Step runner: executes a scenario written as plain steps in tests/cases/.yaml (runner: steps), with no + * hand-written code. Each step names one proven Fusion action; the model (or a consultant) writes the steps, Playwright + * runs them the same way every time. Unknown actions fail the step with a clear message, never guess. + * + * Step fields: action, field, value, expected (shown in the report and the live view). + * Values may use {{pod..}} (the pod's test data, e.g. {{pod.ap.supplier}}), {{today}}, {{unique:TAG}}, + * {{tv.}} and {{saved.}} (a value remembered by an earlier `remember` step). + * + * Business actions (Payables first) do a whole piece of business the proven way, so a scenario made of them does not + * break on every Fusion quirk: create_invoice, validate_invoice, find_invoice, cancel_invoice, expect_invoice, + * expect_hold, expect_no_holds. Their extra fields: lines, status, amount, amount_at_least, canceled. A canary scenario + * per area (tests/cases/CANARY-.yaml) runs each of them once before a run, to prove they still work on the pod. + * Purchasing: create_requisition, expect_requisition, cancel_requisition, create_purchase_order, submit_purchase_order, + * find_purchase_order, expect_purchase_order, cancel_purchase_order (extra fields quantity, price). General Ledger: + * create_journal, post_journal, find_journal, expect_journal, reverse_journal (extra field posted). + */ +export interface Step { n?: number; action: string; field?: string; value?: string | number; expected?: string; name?: string; fields?: string[]; + lines?: (string | number)[]; status?: string; amount?: string | number; amount_at_least?: string | number; canceled?: boolean; + quantity?: string | number; price?: string | number; posted?: boolean } +export interface StepCase { id: string; title: string; runner?: string; steps: Step[]; test_values?: Record; + canary?: boolean } // a canary (tests/cases/CANARY-.yaml): create_invoice tries the pod's data sets in turn + +const CASES_DIR = path.join(__dirname, '..', '..', '..', 'tests', 'cases'); + +/** + * The scenario's YAML: from `dir` when given (a staged AI draft's own folder), else from FPT_STEPS_DIR when it holds + * that id (the co-worker's staging folder for drafts), else from the script library tests/cases/. + */ +export function stepCaseFile(id: string, dir?: string): string { + for (const d of [dir, process.env.FPT_STEPS_DIR]) { + if (d && fs.existsSync(path.join(d, `${id}.yaml`))) return path.join(d, `${id}.yaml`); + } + return path.join(CASES_DIR, `${id}.yaml`); +} + +export function loadStepCase(id: string, dir?: string): StepCase { + const f = stepCaseFile(id, dir); + const c = YAML.parse(fs.readFileSync(f, 'utf8')) as StepCase; + if (c.runner !== 'steps') throw new Error(`${id}: runner is not "steps"`); + return c; +} + +type Ctx = { ui: FusionUi; c: StepCase; saved: Record; uniques: Record; track: (n: string) => string; + chosen: Record; // the pod value Fusion accepted, per "area.key", used again for the rest of the test + rest: FusionRest; // Fusion REST, for the business actions that check what the screens did + docs: FusionDocs }; // Purchasing and General Ledger test documents, cleaned up after the test + +function fill(raw: unknown, ctx: Ctx): string { + return String(raw ?? '').replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_m, key: string) => { + const pod = /^pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)$/i.exec(key); + if (pod) return ctx.chosen[`${pod[1]}.${pod[2]}`.toLowerCase()] ?? podValue(pod[1], pod[2]); // the pod's own test data + if (key === 'today') return fusionDate(); + if (key.startsWith('unique:')) { const t = key.slice(7); return (ctx.uniques[t] ??= testNumber(t)); } + if (key.startsWith('tv.')) return String(ctx.c.test_values?.[key.slice(3)] ?? ''); + if (key.startsWith('saved.')) return ctx.saved[key.slice(6)] ?? ''; + throw new Error(`unknown placeholder {{${key}}}`); + }); +} + +/** Enter a value. A value that is exactly one pod test data placeholder ({{pod.ap.business_unit}}) is tried with each + * value the pod has for it, in order, until Fusion accepts one (a business unit this user may use, a source that + * exists on this pod): the first that works is kept for the rest of the test and remembered for the next run. */ +async function putValue(s: Step, ctx: Ctx, put: (v: string) => Promise): Promise { + const ref = /^\s*\{\{\s*pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)\s*\}\}\s*$/i.exec(String(s.value ?? '')); + const key = ref ? `${ref[1]}.${ref[2]}`.toLowerCase() : ''; + if (!ref || ctx.chosen[key]) return put(fill(s.value, ctx)); + const tried: string[] = []; + for (const v of podCandidates(ref[1], ref[2])) { + try { + await put(v); + ctx.chosen[key] = v; + used(ref[1], ref[2], v, true); + return; + } catch (e) { + if (!(e instanceof ValueRefused)) throw e; + used(ref[1], ref[2], v, false); + tried.push(v); + } + } + throw new Error(`Fusion accepted none of the ${tried.length} value(s) this pod has for ${ref[2].replace(/_/g, ' ')} in ` + + `"${s.field}" (${tried.join(', ')}): this test user is not offered any of them; set one it may use on the Test environments page`); +} + +/** The invoice a business action works on: the number create_invoice (or a `remember` step) stored under the step's + * `name`, "invoice_number" when it names none. */ +function invoiceNumber(s: Step, ctx: Ctx): string { + const name = s.name || 'invoice_number'; + const n = ctx.saved[name]; + if (!n) throw new Error(`${s.action} needs an invoice: no invoice number is remembered as "${name}" (create_invoice or remember it first)`); + return n; +} + +/** A number a step gives (an amount), filled in from its placeholders. */ +function amountOf(raw: string | number, ctx: Ctx, what: string): number { + const v = Number(fill(raw, ctx).replace(/,/g, '')); + if (!Number.isFinite(v)) throw new Error(`${what} must be a number, got "${fill(raw, ctx)}"`); + return v; +} + +/** Ask Fusion (REST) until `problems` comes back empty: REST can lag a few seconds behind what the screen saved. Fails + * with the last problems in words. */ +async function untilRight(problems: () => Promise, what: string, timeoutMs = 60_000) { + const end = Date.now() + timeoutMs; + for (;;) { + const p = await problems(); + if (!p.length) return; + if (Date.now() > end) throw new Error(`${what}: ${p.join('; ')}`); + await new Promise((r) => setTimeout(r, 3000)); + } +} + +/** A business action's check through Fusion REST. On a pod with assisted sign-in there is no password for REST: the + * check is skipped with a note on the test (the screen steps before it already ran and stand). */ +async function restCheck(ctx: Ctx, what: string, fn: () => Promise): Promise { + if (ctx.rest.available) return fn(); + test.info().annotations.push({ type: REST_SKIPPED, description: `${what}: ${NO_REST_WHY}` }); +} + +/** The pod values to try for an AP test data key: the one Fusion already took in this test, else the pod's candidates. */ +const apChoices = (ctx: Ctx, key: string) => ctx.chosen[`ap.${key}`] ? [ctx.chosen[`ap.${key}`]] : podCandidates('ap', key); + +/** The pod's supplier sites to try when Fusion leaves Supplier Site empty (none: the first site Fusion lists). */ +const apSites = (ctx: Ctx) => { try { return apChoices(ctx, 'supplier_site'); } catch { return []; } }; + +const errorText = (e: unknown) => String((e as Error)?.message || e).split('\n')[0].slice(0, 200); + +/** The canary's create_invoice: the pod's Payables data sets (apDataSets) in turn until one creates AND validates an + * invoice. A shared pod's sampled data can be whoever used it last (a supplier without a default site, an account of + * another ledger); the set that works is recorded as accepted (FPT_TESTDATA_USED), so the co-worker learns it and the + * run's other scenarios and the next run try it first. When no set validates, the first set that saved is kept, so + * the canary's own validate_invoice step shows what is broken; when none saves, create_invoice fails with each reason. */ +async function createWithDataSets(ctx: Ctx, h: { amount: string; lines: string[]; name: string }) { + const sets = apDataSets(); + const why: string[] = []; + let saved: ApDataSet | null = null; + let last = false; // the invoice the last set saved is the one on the page + const create = async (set: ApDataSet, k: number) => { + const number = ctx.track(testNumber(`${ctx.c.id.replace(/[^A-Za-z0-9]/g, '')}${k || ''}`)); + const got = await ctx.ui.createInvoice({ businessUnit: set.businessUnit, supplier: set.supplier, site: set.site, number, + amount: h.amount, lines: h.lines, account: set.account }); + ctx.saved[h.name] = number; + return got; + }; + for (const [k, set] of sets.entries()) { + const label = `${set.businessUnit} / ${set.supplier}`; + last = false; + let got; + try { got = await create(set, k); } catch (e) { why.push(`${label}: ${errorText(e)}`); continue; } + saved ??= set; + last = true; + try { + await ctx.ui.validateInvoice(); + await ctx.ui.expectStatus('Validated', ctx.saved[h.name]); + } catch (e) { why.push(`${label}: saved but did not validate (${errorText(e)})`); continue; } + for (const [key, v] of [['business_unit', got.businessUnit], ['supplier', got.supplier], ['supplier_site', got.site], ['account', got.account]]) { + if (v) { used('AP', key, v, true); ctx.chosen[`ap.${key}`] = v; } + } + if (k) console.log(`[canary] Payables data set ${k + 1} of ${sets.length} works (${label}); tried: ${why.join(' | ')}`); + return; + } + if (!saved) throw new Error(`create_invoice failed with each of the pod's ${sets.length} Payables data set(s): ${why.join(' | ')}`); + console.log(`[canary] no Payables data set validates: ${why.join(' | ')}`); + if (!last) await create(saved, sets.length); +} + +/** The pod's values to try for one test data key, the one Fusion already took in this test first; none when the pod + * has no such test data (Fusion's own default is then kept, or its list's first choice taken). `also` = keys of other + * areas tried after it: a journal's account may be the Payables one, which belongs to a ledger of the same pod. */ +function choices(ctx: Ctx, area: string, key: string, ...also: [string, string][]): string[] { + const out: string[] = []; + for (const [a, k] of [[area, key] as [string, string], ...also]) { + const took = ctx.chosen[`${a}.${k}`.toLowerCase()]; + if (took) { out.push(took); continue; } + try { out.push(...podCandidates(a, k)); } catch { /* the pod has no such test data */ } + } + return out.filter((v, i, all) => v && all.indexOf(v) === i); +} + +/** A new test reference for a document of this scenario (FPT--