← Files AICtrlARCHIVED FILE

skills/ux-testing/scripts/common.cjs

14.9 KB · Nov 21, 2026 · 12:23 UTC

↓ Download file

See the change to this file →

// Shared helpers for the ux-testing scripts: loading Playwright (and js-yaml), the harness token path,
// and the simulator backend (a "System One" model that returns probabilities over choices).
const fs = require('fs');
const os = require('os');
const path = require('path');

// Resolve a package only from the skill's own location (node_modules next to or above the scripts) or from
// NODE_PATH, which the operator sets explicitly. Never from the current directory: the target under test may be
// an untrusted prototype, and a planted node_modules/playwright there would run as you before any page opens.
function requireFrom(name) {
  try { return require(name); } catch (e) {
    // Absent only when the package itself is missing; a broken install (a missing dependency inside it) is
    // reported as it is, not as "not installed".
    if (e && e.code === 'MODULE_NOT_FOUND' && String(e.message).startsWith(`Cannot find module '${name}'`)) return null;
    throw e;
  }
}

function loadPlaywright() {
  for (const name of ['playwright', 'playwright-core']) {
    const mod = requireFrom(name);
    if (mod) return mod;
  }
  console.error('Playwright was not found next to the skill or on NODE_PATH. Install it in a directory you trust (`npm i -D playwright && npx playwright install chromium`) and run with NODE_PATH=<that directory>/node_modules.');
  process.exit(2);
}

// Reads a task model: JSON always works; YAML needs js-yaml (`npm i -D js-yaml`, or NODE_PATH).
function loadModel(file) {
  const text = fs.readFileSync(file, 'utf8');
  if (/\.json$/i.test(file)) return JSON.parse(text);
  const yaml = requireFrom('js-yaml');
  if (!yaml) {
    console.error(`Reading ${path.basename(file)} needs js-yaml next to the skill or on NODE_PATH (\`npm i -D js-yaml\` in a directory you trust), or write the task model as JSON.`);
    process.exit(2);
  }
  return yaml.load(text);
}

// The per-run access token lives in a private per-user directory; see server.cjs.
function tokenFile(port) {
  const uid = typeof process.getuid === 'function' ? process.getuid() : 'user';
  return path.join(os.tmpdir(), `ux-harness-${uid}`, `${port}.token`);
}

// ---------------------------------------------------------------- simulator backend
// Supported: TypeSafe's Jev (TYPESAFE_API_KEY), or any endpoint with the same request/response contract
// (UX_SIM_ENDPOINT + UX_SIM_API_KEY + UX_SIM_MODEL). Keys are read from the environment only; they are never
// printed, logged, cached or written to disk. The contract is documented in reference/simulator.md.
const TYPESAFE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone';
const NOT_CONFIGURED = `Simulator not configured. Simulated users need a fast "System One" model that returns probabilities over choices.
  - TypeSafe Jev: set TYPESAFE_API_KEY (get a key at https://typesafe.ai), or
  - a compatible endpoint: set UX_SIM_ENDPOINT, UX_SIM_API_KEY and UX_SIM_MODEL (contract: reference/simulator.md).
Local models are not supported yet. The simulator is optional: continue with agent testers only.`;

function simBackend() {
  const custom = process.env.UX_SIM_ENDPOINT;
  let endpoint; let key; let model; let label;
  if (custom) {
    endpoint = custom; key = process.env.UX_SIM_API_KEY; model = process.env.UX_SIM_MODEL;
    if (!key || !model) return { error: `UX_SIM_ENDPOINT is set, so UX_SIM_API_KEY and UX_SIM_MODEL are required too.\n${NOT_CONFIGURED}` };
    label = `custom endpoint (${model})`;
  } else if (process.env.TYPESAFE_API_KEY) {
    endpoint = TYPESAFE_ENDPOINT; key = process.env.TYPESAFE_API_KEY; model = process.env.UX_SIM_MODEL || 'jev-latest';
    label = `TypeSafe (${model})`;
  } else return { error: NOT_CONFIGURED };
  let url;
  try { url = new URL(endpoint); } catch { return { error: 'UX_SIM_ENDPOINT is not a valid URL.' }; }
  const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
  if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) return { error: 'UX_SIM_ENDPOINT must use https (plain http is allowed only for localhost), so the key is never sent in clear text.' };
  return { endpoint: url.href, model, label, ask: (state, questions) => ask(url.href, key, model, state, questions) };
}

// Exits (code 2) with the not-configured message when no backend is set up.
function requireSimBackend() {
  const b = simBackend();
  if (b.error) { console.error(b.error); process.exit(2); }
  return b;
}

async function ask(endpoint, key, model, state, questions) {
  let lastStatus = 'no response';
  for (let attempt = 0; attempt < 3; attempt++) {
    let r;
    try {
      r = await fetch(endpoint, { method: 'POST', headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model, state, questions }) });
    } catch (e) {
      lastStatus = `network error: ${e.code || e.name}`;
    }
    if (r && r.ok) {
      let j;
      try { j = await r.json(); } catch { throw new Error('simulator response is not JSON'); }
      return validate(j, questions);
    }
    if (r) {
      lastStatus = `HTTP ${r.status}`;
      // Auth and request errors will not fix themselves; only retry rate limits and server errors.
      if (r.status !== 429 && r.status < 500) break;
    }
    if (attempt < 2) await new Promise((res) => setTimeout(res, 1500 * (attempt + 1)));
  }
  throw new Error(`simulator request failed (${lastStatus})`);
}

// Checks the response follows the contract, so a drifting endpoint fails loudly instead of skewing results.
function validate(j, questions) {
  const bad = (why) => { throw new Error(`simulator response does not follow the contract: ${why}`); };
  if (!j || typeof j.answers !== 'object' || j.answers === null) bad('missing "answers" object');
  for (const [name, q] of Object.entries(questions)) {
    const a = j.answers[name];
    if (!a) bad(`no answer for "${name}"`);
    if (q.type === 'choice') {
      const p = a.probabilities;
      if (!p || typeof p !== 'object') bad(`"${name}" needs "probabilities"`);
      const keys = Object.keys(p);
      if (!keys.length || keys.some((k) => !(k in q.criteria) || typeof p[k] !== 'number' || p[k] < 0 || p[k] > 1)) bad(`"${name}" probabilities must be numbers in [0, 1] keyed by the criteria`);
      const sum = keys.reduce((s, k) => s + p[k], 0);
      if (Math.abs(sum - 1) > 0.02) bad(`"${name}" probabilities sum to ${sum.toFixed(3)}, not 1`);
    } else if (q.type === 'noul') {
      if (typeof a.noul !== 'number' || a.noul < 0 || a.noul > 1) bad(`"${name}" needs "noul", a number in [0, 1]`);
    }
  }
  return j;
}

// ---------------------------------------------------------------- matching controls by visible name
// Shared by the harness (server.cjs) and replay.cjs, so a replay clicks what the tester clicked.
// `switch` is its own role (MUI <Switch> renders input[type=checkbox][role=switch]), not a checkbox: without it a
// toggle cannot be clicked by name, and a click by text lands on the adjacent description instead.
const ROLES = ['button', 'link', 'tab', 'option', 'menuitem', 'checkbox', 'switch', 'radio', 'treeitem', 'row', 'combobox'];
const escapeRe = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

// Returns { loc, note }, { error } for malformed input, or null when nothing matches.
// A trailing " #N" picks the Nth match, but only when the literal text (e.g. "Run #210") matches
// nothing, so names that end in a number stay clickable.
async function resolveTarget(page, target) {
  const literal = await locate(page, target, 0);
  if (literal) return literal;
  const m = target.match(/^(.*?)\s+#(\d+)$/);
  if (!m) return null;
  const idx = Number(m[2]) - 1;
  if (idx < 0) return { error: 'ERROR: matches are numbered from #1.' };
  return locate(page, m[1], idx);
}

async function locate(page, target, idx) {
  let role = null;
  let name = target.trim();
  const rm = name.match(/^(\w+):(.*)$/);
  if (rm && ROLES.includes(rm[1])) { role = rm[1]; name = rm[2].trim(); }
  if (!name) return { error: 'ERROR: click needs the visible name of what to click.' };
  const roles = role ? [role] : ROLES;
  const tries = [
    ...roles.map((r) => page.getByRole(r, { name, exact: true })),
    // Fuzzy fallback: the element's name must START with the text (never merely contain it), so
    // "run #210" cannot hit "Approve gate: … (run #210)". Accessible names start with the visible label.
    ...roles.map((r) => page.getByRole(r, { name: new RegExp('^\\s*' + escapeRe(name), 'i') })),
    ...(role ? [] : [page.getByText(name, { exact: true }), page.getByText(name)]),
  ];
  for (const loc of tries) {
    const vis = loc.filter({ visible: true });
    const count = await vis.count();
    if (count > 0) {
      const note = count > 1 ? ` (${count} matches; clicked #${Math.min(idx + 1, count)}. Add " #2" etc. to pick another.)` : '';
      return { loc: vis.nth(Math.min(idx, count - 1)), note };
    }
  }
  return null;
}

// `type --field "<label>"` must reach every text-entry role, not just textbox: <input type="search"> has role
// searchbox and an editable combobox (an autocomplete input) has role combobox, and both are typeable. A
// non-editable <select> shares the combobox role but is the `select` action's job, never fill()'s, so the
// combobox branch keeps only fill()'s own targets: a labelled <select> must neither be filled (fill() throws
// on it) nor, with a duplicate label, shadow a typeable field ahead of it in DOM order. Callers run this with
// exact: true first, then substring — locate()'s ladder — so a field named exactly "<label>" wins over one
// whose name merely contains it; substring names otherwise collide across roles and .or() picks DOM order.
function namedFields(page, field, exact = false) {
  const name = exact ? { name: field, exact: true } : { name: field };
  return page
    .getByRole('textbox', name)
    .or(page.getByRole('searchbox', name))
    .or(page.getByRole('combobox', name).and(page.locator('input, textarea, [contenteditable=""], [contenteditable="true"], [contenteditable="plaintext-only"]')))
    .filter({ visible: true });
}

// Replay only: logs written before the harness recorded the clicked name may need a contains-match on roles,
// which the harness itself never uses. Tried last, after the harness ladder.
async function locateLegacy(page, name) {
  for (const r of ROLES) {
    const v = page.getByRole(r, { name: new RegExp(escapeRe(name), 'i') }).filter({ visible: true });
    if (await v.count()) return v.first();
  }
  return null;
}

// ---------------------------------------------------------------- setup modules
// A setup module runs after the page is opened, e.g. to sign in to a test account on a real app. It exports
// async (page, context) => {}, the contract of server.cjs's UX_SETUP. A missing file or a module that does not
// export a function is a config error, reported before any page is opened. Only an absent `setup` or `null`
// means "no setup"; any other non-path value (an empty string, false) is a config error, not a silent off.
// Returns null or { file, run }: `file` is the resolved path, so a setup that fails at run time can be named.
function loadSetup(file, base) {
  if (file === undefined || file === null) return null;
  if (typeof file !== 'string' || !file.trim()) throw new Error(`setup must be a path to a .cjs module, or null to turn it off (got ${JSON.stringify(file)})`);
  const f = path.resolve(base, file);
  if (!fs.existsSync(f)) throw new Error(`setup module ${f} not found`);
  const fn = require(f);
  if (typeof fn !== 'function') throw new Error(`setup module ${f} must export async (page, context) => {}`);
  return { file: f, run: fn };
}

// Reads a JSON file for a run's configuration. Every error names the file: some read errors (EISDIR) do not.
function readJson(f) {
  try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { throw new Error(String(e.message).includes(f) ? e.message : `${f}: ${e.message}`); }
}

// A setup module signs in to a test account, and a config can hold a signed URL, so error text can carry a
// password, a token or a signature. Mask the values of credential-like keys (any key containing password,
// secret, token, api key, credential or signature; or exactly auth, authorization, session, sid, cookie, sig
// or pwd, so author= and oauth_callback= survive), bearer tokens and URL credentials before printing it.
const SECRET_VALUE = new RegExp(String.raw`(\b(?:[\w-]*(?:password|passwd|secret|token|api[_-]?key|apikey|credential|signature)[\w-]*|(?:x-)?(?:auth|authorization|session|session[_-]?id|sessid|sid|cookie|set-cookie|sig|pwd))["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,&;)}\]]+)`, 'gi');
function redactSecrets(text) {
  return String(text)
    .replace(/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi, '$1 <redacted>')
    .replace(SECRET_VALUE, '$1<redacted>')
    .replace(/(\/\/)[^/\s:@]+:[^/\s@]+@/g, '$1<redacted>@');
}

// Runs fn and returns its result; anything it throws is a config error: print it and exit 2, before a browser
// starts or an output directory is written. Wraps loadSetup and the reads of the files a run is configured by.
function exitOnConfigError(fn) {
  try { return fn(); } catch (e) { console.error(`ERROR: ${redactSecrets(e.message)}`); process.exit(2); }
}

// ---------------------------------------------------------------- options and randomness
// Command-line options: `--name value`. A flag given without a value (last argument, or followed by another
// --flag) is a usage error rather than silently becoming undefined/NaN.
function options(argv) {
  const has = (name) => argv.includes(`--${name}`);
  const str = (name, dflt) => {
    const i = argv.indexOf(`--${name}`);
    if (i < 0) return dflt;
    const v = argv[i + 1];
    if (v === undefined || v.startsWith('--')) usageError(`--${name} needs a value`);
    return v;
  };
  const int = (name, dflt, min) => {
    const raw = str(name, undefined);
    if (raw === undefined) return dflt;
    const n = Number(raw);
    if (!Number.isInteger(n) || n < min) usageError(`--${name} must be an integer >= ${min} (got "${raw}")`);
    return n;
  };
  return { has, str, int };
}

function usageError(msg) {
  console.error(msg);
  process.exit(2);
}

// mulberry32: a small PRNG on exact 32-bit integer arithmetic (Math.imul, >>> 0), uniform in [0, 1).
// Floating-point LCGs lose low bits once the product passes 2^53 and drift from uniform.
function rng(seed) {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6d2b79f5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

// A stable 32-bit seed from any parts (e.g. seed, case id, profile, condition, run index), so every simulated
// walk has its own generator and results do not depend on how concurrent workers interleave.
function seedOf(...parts) {
  let h = 2166136261;
  for (const ch of JSON.stringify(parts)) { h ^= ch.charCodeAt(0); h = Math.imul(h, 16777619); }
  return h >>> 0;
}

module.exports = { loadPlaywright, loadModel, loadSetup, exitOnConfigError, readJson, redactSecrets, tokenFile, simBackend, requireSimBackend, options, rng, seedOf, ROLES, resolveTarget, locateLegacy, namedFields };

SHA-256: a2451c325424609d7f576bbd6a5bfc05fdf670fd332bcc73eb4856cc170db8a3