GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / atman

Verify Mobile UI Browser (part 1)

A JavaScript module in the atman folder of PipelineNews that applies area (`applySafeArea`), attaches diagnostics (`attachDiagnostics`) and selects full page capture (`selectFullPageCapture`), using SHA-256.

700 lines of JavaScript from pipelinenews, in 1 file. Topic: Electricity markets and data pipelines. Section 1003 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Verify Mobile UI Browser interaction · pipelinenews / atman/202608271656-verify-mobile-ui-browser.mjs lines 1–700

Verify Mobile UI Browser

A JavaScript module in the atman folder of PipelineNews that applies area (`applySafeArea`), attaches diagnostics (`attachDiagnostics`) and selects full page capture (`selectFullPageCapture`), using SHA-256.

interactionpipelinenews / atman/202608271656-verify-mobile-ui-browser.mjs · lines 1–700 of 1963 · version 2026-08-27 16:56 · Entry point · pattern sha256File (shared by 4 files)

What it does
It draws its content. Defines 55 functions or classes, including selectedIds, slug, serialiseError, relativeEvidencePath, writeJson. Uses libraries node:crypto, node:fs, node:fs/promises, node:path, node:module. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file run.json; command-line arguments.
Downstream impact
Used directly by 1 file: PipelineNews Mobile CSS Repair Workflow (pipelinenews).
What it achieves
It serialises error (`serialiseError`), writes JSON (`writeJson`) and applies safe area (`applySafeArea`). Its name says it verifies mobile UI browser. Defines `selectedIds`, `slug`, `serialiseError` and 52 more.
Why it matters
Run by PipelineNews Mobile CSS Repair Workflow.
Application
pipelinenews · atman · JavaScript module
Uses
Mobile UI Invariants (import), node:crypto, node:fs, node:fs/promises, node:path, node:module, playwright, sharp, playwright/package.json
Used by
run by PipelineNews Mobile CSS Repair Workflow (workflow run)
Produces
selectedIds, slug, serialiseError, relativeEvidencePath, writeJson, sha256File, invariantResult, emptyInvariantResults, applySafeArea, attachDiagnostics, favicon, retain
Defines here
selectedIds, slug, serialiseError, relativeEvidencePath, writeJson, sha256File, invariantResult, emptyInvariantResults, applySafeArea, attachDiagnostics, favicon, retain, waitUntilReady, navigate, selectFullPageCapture, pngDimensions, assertViewportScreenshotPixels, captureScreenshots, boundedJpeg, exerciseReleaseMenu, visible, restoreOriginalScroll, collectStaticMeasurements, nextFrame, rectData, elementLabel, cssVisible, rendered, inViewport, intersectRect
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 atman/202608271656-verify-mobile-ui-browser.mjs:1-700 · blob fcba98c5336221df52e233d5acc0f42a15c188f8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { createRequire } from "node:module";
import { chromium } from "playwright";
import sharp from "sharp";

import CONTRACT, { GENERATION } from "./202608271656-mobile-ui-invariants.mjs";

const require = createRequire(import.meta.url);
const PLAYWRIGHT_VERSION = require("playwright/package.json").version;
const SHARP_VERSION = require("sharp/package.json").version;
const EXPECTED_SHARP_VERSION = "0.34.3";
const MODE = process.env.MOBILE_UI_MODE === "repair" ? "repair" : "audit";
const SOURCE_COMMIT = process.env.MOBILE_UI_SOURCE_COMMIT || process.env.GITHUB_SHA || "";
const cliOutIndex = process.argv.indexOf("--out-root");
const RAW_DIR = path.resolve(
  cliOutIndex >= 0 && process.argv[cliOutIndex + 1]
    ? process.argv[cliOutIndex + 1]
    : process.env.MOBILE_UI_RAW_DIR || "audit-results/mobile-ui",
);
const FULL_PAGE_CAPTURE_LIMITS = Object.freeze({
  max_dimension_css_px: 16_384,
  max_area_css_pixels: 4_194_304,
  max_project_rows: 1_000,
});
const SCREENSHOT_LIMIT_BYTES = 400 * 1024;
const CELL_RECORD_LIMIT_BYTES = 256 * 1024;
const SCREENSHOT_DIR = path.join(RAW_DIR, "screenshots");

if (CONTRACT.schema !== "pipelinenews.mobile-ui-invariants.v1") {
  throw new Error(`Unsupported mobile UI contract: ${CONTRACT.schema}`);
}
if (CONTRACT.generation !== GENERATION) {
  throw new Error("Mobile UI contract generation mismatch");
}
if (
  CONTRACT.project_posture?.owner !== "Ventus Ltd"
  || CONTRACT.project_posture?.application !== "non-commercial-open-source"
  || CONTRACT.project_posture?.publisher_redistribution_rights !== "source-specific-not-inferred"
) {
  throw new Error("Mobile UI contract project posture is absent or invalid");
}
if (PLAYWRIGHT_VERSION !== CONTRACT.browser.playwright_version) {
  throw new Error(`Playwright ${PLAYWRIGHT_VERSION} does not match pinned ${CONTRACT.browser.playwright_version}`);
}
if (SHARP_VERSION !== EXPECTED_SHARP_VERSION) {
  throw new Error(`Sharp ${SHARP_VERSION} does not match pinned ${EXPECTED_SHARP_VERSION}`);
}
if (!/^[0-9a-f]{40}$/u.test(SOURCE_COMMIT)) {
  throw new Error("MOBILE_UI_SOURCE_COMMIT or GITHUB_SHA must be an exact lowercase 40-hex source commit");
}

await mkdir(RAW_DIR, { recursive: true });
await mkdir(SCREENSHOT_DIR, { recursive: true });

const targetUrlOverrides = Object.freeze({
  candidate: process.env.MOBILE_UI_CANDIDATE_URL || process.env.MOBILE_CANDIDATE_URL,
  baseline: process.env.MOBILE_UI_BASELINE_URL,
  original: process.env.MOBILE_UI_ORIGINAL_URL,
});
const allTargets = CONTRACT.targets.map((target) => ({
  ...target,
  url: targetUrlOverrides[target.id] || target.url,
}));
function selectedIds(environmentName, allowed) {
  const raw = process.env[environmentName];
  if (raw === undefined) return [...allowed];
  if (!raw.trim() || raw.trim().toLowerCase() === "none") return [];
  const values = raw.split(",").map((value) => value.trim()).filter(Boolean);
  if (new Set(values).size !== values.length) throw new Error(`${environmentName} repeats an id`);
  for (const value of values) {
    if (!allowed.includes(value)) throw new Error(`${environmentName} contains unknown id ${value}`);
  }
  return values;
}
const selectedTargetIds = selectedIds("MOBILE_UI_TARGET_IDS", allTargets.map(({ id }) => id));
const selectedCellIds = selectedIds("MOBILE_UI_CELL_IDS", CONTRACT.cells.map(({ id }) => id));
const includeRotate = process.env.MOBILE_UI_INCLUDE_ROTATE === undefined
  ? true
  : process.env.MOBILE_UI_INCLUDE_ROTATE === "true";
const shardId = process.env.MOBILE_UI_SHARD_ID || "complete";
const targets = allTargets.filter(({ id }) => selectedTargetIds.includes(id));
const staticCells = CONTRACT.cells.filter(({ id }) => selectedCellIds.includes(id));
if (targets.length === 0) throw new Error("MOBILE_UI_TARGET_IDS selected no targets");
if (staticCells.length === 0 && !includeRotate) throw new Error("shard selected neither static nor rotation cells");
const candidateGeneration = process.env.MOBILE_UI_CANDIDATE_GENERATION || "202608271524";
const startedAt = new Date().toISOString();
const recordFiles = [];
const requiredFailures = [];
let optionalOriginalFailure = null;

function slug(value) {
  return String(value).replace(/[^a-zA-Z0-9._-]+/gu, "-");
}

function serialiseError(error) {
  if (!(error instanceof Error)) return { name: "Error", message: String(error), stack: null };
  const serialised = { name: error.name, message: error.message, stack: error.stack || null };
  for (const key of [
    "rotation_phase",
    "rotation_operation",
    "expected_geometry",
    "observed_geometry",
    "rotation_trace",
    "browser_diagnostics",
  ]) {
    if (error[key] !== undefined) serialised[key] = error[key];
  }
  if (error.cause instanceof Error) {
    serialised.cause = serialiseError(error.cause);
  }
  return serialised;
}

function relativeEvidencePath(filePath) {
  return path.relative(RAW_DIR, filePath).split(path.sep).join("/");
}

async function writeJson(filePath, value) {
  await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`);
}

async function sha256File(filePath) {
  const hash = createHash("sha256");
  await new Promise((resolve, reject) => {
    const stream = createReadStream(filePath);
    stream.on("error", reject);
    stream.on("data", (chunk) => hash.update(chunk));
    stream.on("end", resolve);
  });
  return hash.digest("hex");
}

function invariantResult(id, applicable, pass, measurement) {
  const descriptor = CONTRACT.invariants.find((invariant) => invariant.id === id);
  if (!descriptor) throw new Error(`Invariant ${id} is absent from the frozen contract`);
  const mode = descriptor[MODE];
  let status = "N/A";
  if (applicable) {
    if (mode === "report-only") status = pass ? "REPORT-ONLY-PASS" : "REPORT-ONLY-FAIL";
    else status = pass ? "PASS" : "FAIL";
  }
  return {
    id,
    name: descriptor.name,
    applicable,
    pass: applicable ? Boolean(pass) : null,
    status,
    mode,
    measurement,
  };
}

function emptyInvariantResults(reason, rotate = false) {
  return CONTRACT.invariants
    .filter(({ id }) => id !== "I12")
    .map((descriptor) => invariantResult(
      descriptor.id,
      false,
      null,
      { reason, expected_scope: rotate ? "rotate" : "static" },
    ));
}

async function applySafeArea(cdp, cellId, orientation) {
  const requested = CONTRACT.safe_area_insets_by_cell[cellId]
    || Object.values(CONTRACT.safe_area_insets_by_cell).find((value) => (
      orientation === "landscape" ? value.left > 0 : value.top > 0
    ))
    || { top: 0, right: 0, bottom: 0, left: 0 };
  const insets = {
    ...requested,
    topMax: requested.top,
    rightMax: requested.right,
    bottomMax: requested.bottom,
    leftMax: requested.left,
  };
  try {
    await cdp.send("Emulation.setSafeAreaInsetsOverride", { insets });
    return { supported: true, requested, error: null };
  } catch (error) {
    return { supported: false, requested, error: serialiseError(error) };
  }
}

function attachDiagnostics(page) {
  const diagnostics = {
    console_errors: [],
    page_errors: [],
    failed_requests: [],
    http_errors: [],
  };
  const favicon = (url) => {
    try {
      return new URL(url).pathname.endsWith("/favicon.ico");
    } catch {
      return false;
    }
  };
  const retain = (list, value) => {
    if (list.length < 20) list.push(value);
  };
  page.on("console", (message) => {
    if (message.type() === "error") retain(diagnostics.console_errors, message.text().slice(0, 500));
  });
  page.on("pageerror", (error) => retain(diagnostics.page_errors, String(error).slice(0, 500)));
  page.on("requestfailed", (request) => {
    if (!favicon(request.url())) {
      retain(diagnostics.failed_requests, {
        url: request.url().slice(0, 500),
        error: (request.failure()?.errorText || "request failed").slice(0, 500),
      });
    }
  });
  page.on("response", (response) => {
    if (response.status() >= 400 && !favicon(response.url())) {
      retain(diagnostics.http_errors, { url: response.url().slice(0, 500), status: response.status() });
    }
  });
  return diagnostics;
}

async function waitUntilReady(page, target) {
  const timeout = target.required
    ? CONTRACT.browser.ready_timeout_ms
    : Math.min(CONTRACT.browser.ready_timeout_ms, 30_000);

  if (target.ready === "fast-1524") {
    await page.waitForFunction(() => (
      document.body.dataset.fastReady === "true"
      || document.body.dataset.fastFailed === "true"
    ), null, { timeout });
    const boot = await page.evaluate(() => ({
      ready: document.body.dataset.fastReady || null,
      failed: document.body.dataset.fastFailed || null,
      generation: document.body.dataset.fastGeneration || null,
    }));
    if (boot.failed === "true" || boot.ready !== "true" || boot.generation !== candidateGeneration) {
      throw new Error(`Fast candidate failed closed: ${JSON.stringify(boot)}`);
    }
    await page.waitForFunction(() => (
      document.querySelectorAll("#tbody > tr").length > 0
      && document.querySelectorAll("#stories .story").length > 0
    ), null, { timeout });
  } else if (target.ready === "trusted-v9-6-2") {
    await page.waitForFunction(() => (
      document.querySelectorAll("#tbody > tr").length === 7_680
      && document.querySelectorAll("#stories .story").length === 133
    ), null, { timeout });
  } else {
    await page.waitForFunction(() => {
      if (document.readyState === "loading") return false;
      const rows = document.querySelectorAll("tbody tr, [role='row']").length;
      return rows >= 3 || Boolean(document.querySelector(".tablewrap, table, canvas, [role='grid']"));
    }, null, { timeout });
  }

  return page.evaluate(() => ({
    title: document.title,
    ready_state: document.readyState,
    fast_ready: document.body.dataset.fastReady || null,
    fast_failed: document.body.dataset.fastFailed || null,
    fast_generation: document.body.dataset.fastGeneration || null,
    project_rows: document.querySelectorAll("#tbody > tr").length,
    story_rows: document.querySelectorAll("#stories .story").length,
    dom_elements: document.getElementsByTagName("*").length,
  }));
}

async function navigate(page, target) {
  const timeout = target.required
    ? CONTRACT.browser.navigation_timeout_ms
    : Math.min(CONTRACT.browser.navigation_timeout_ms, 30_000);
  const response = await page.goto(target.url, { waitUntil: "domcontentloaded", timeout });
  if (!response) throw new Error("Navigation returned no main-resource response");
  if (!response.ok()) throw new Error(`Navigation returned HTTP ${response.status()}`);
  return waitUntilReady(page, target);
}

function selectFullPageCapture(dimensions, limits) {
  const documentWidth = dimensions.document_width;
  const documentHeight = dimensions.document_height;
  const documentPixels = documentWidth * documentHeight;
  const reasons = [];
  if (
    !Number.isFinite(documentWidth)
    || !Number.isFinite(documentHeight)
    || documentWidth <= 0
    || documentHeight <= 0
  ) {
    reasons.push(`invalid document dimensions ${documentWidth}x${documentHeight}`);
  } else if (
    documentWidth > limits.max_dimension_css_px
    || documentHeight > limits.max_dimension_css_px
  ) {
    reasons.push(
      `document ${documentWidth}x${documentHeight} exceeds ${limits.max_dimension_css_px} CSS px side limit`,
    );
  }
  if (!Number.isSafeInteger(documentPixels) || documentPixels <= 0) {
    reasons.push(`invalid or unsafe document area ${documentPixels}`);
  } else if (documentPixels > limits.max_area_css_pixels) {
    reasons.push(
      `document ${documentWidth}x${documentHeight} area ${documentPixels} exceeds `
      + `${limits.max_area_css_pixels} CSS pixels`,
    );
  }
  if (dimensions.project_row_count > limits.max_project_rows) {
    reasons.push(`project row count ${dimensions.project_row_count} exceeds ${limits.max_project_rows}`);
  }
  return {
    complete_document: reasons.length === 0,
    reason: reasons.length > 0 ? `bounded fallback: ${reasons.join("; ")}` : null,
    document_css_pixels: documentPixels,
    limits,
  };
}

function pngDimensions(buffer) {
  const signature = "89504e470d0a1a0a";
  if (
    buffer.length < 24
    || buffer.subarray(0, 8).toString("hex") !== signature
    || buffer.subarray(12, 16).toString("ascii") !== "IHDR"
  ) {
    throw new Error("Screenshot raster is not a bounded PNG with an IHDR header");
  }
  return {
    width: buffer.readUInt32BE(16),
    height: buffer.readUInt32BE(20),
  };
}

function assertViewportScreenshotPixels(fileName, observed, expected) {
  if (observed.width === expected.width && observed.height === expected.height) return true;
  const error = new Error(
    `Viewport screenshot ${fileName} is ${observed.width}x${observed.height}; `
    + `expected ${expected.width}x${expected.height}`,
  );
  error.name = "ScreenshotGeometryError";
  error.expected_geometry = expected;
  error.observed_geometry = observed;
  throw error;
}

async function captureScreenshots(page, targetId, cellId, suffix = "", expectedViewport = null) {
  const stem = `${slug(targetId)}--${slug(cellId)}${suffix ? `--${slug(suffix)}` : ""}`;
  const viewportPath = path.join(SCREENSHOT_DIR, `${stem}--viewport.jpeg`);
  const fullPath = path.join(SCREENSHOT_DIR, `${stem}--full.jpeg`);
  const dimensions = await page.evaluate(() => ({
    document_width: Math.max(
      document.documentElement.scrollWidth,
      document.body?.scrollWidth || 0,
    ),
    document_height: Math.max(
      document.documentElement.scrollHeight,
      document.body?.scrollHeight || 0,
    ),
    viewport_width: innerWidth,
    viewport_height: innerHeight,
    project_row_count: document.querySelectorAll("#tbody > tr").length,
  }));
  const expectedViewportPixels = {
    width: expectedViewport?.width ?? dimensions.viewport_width,
    height: expectedViewport?.height ?? dimensions.viewport_height,
  };
  const boundedJpeg = async (filePath, fullPage) => {
    const raster = await page.screenshot({
      type: "png",
      fullPage,
      scale: "css",
      animations: "disabled",
    });
    const rasterPixels = pngDimensions(raster);
    if (!fullPage) {
      assertViewportScreenshotPixels(path.basename(filePath), rasterPixels, expectedViewportPixels);
    }
    let buffer;
    let quality;
    for (const attempt of [70, 55, 40, 28, 18, 10, 5]) {
      quality = attempt;
      buffer = await sharp(raster, { limitInputPixels: false })
        .jpeg({ quality, chromaSubsampling: "4:2:0", mozjpeg: false })
        .toBuffer();
      if (buffer.byteLength <= SCREENSHOT_LIMIT_BYTES) break;
    }
    if (buffer.byteLength > SCREENSHOT_LIMIT_BYTES) {
      throw new Error(`Screenshot ${path.basename(filePath)} exceeds 400 KiB at minimum JPEG quality`);
    }
    await writeFile(filePath, buffer);
    return {
      path: relativeEvidencePath(filePath),
      captured: true,
      bytes: buffer.byteLength,
      sha256: createHash("sha256").update(buffer).digest("hex"),
      quality,
      source_raster_bytes: raster.byteLength,
      encoder: `sharp-${SHARP_VERSION}`,
      browser_rasterizations: 1,
      css_pixel_scale: true,
      pixel_width: rasterPixels.width,
      pixel_height: rasterPixels.height,
      expected_viewport_pixels: fullPage ? null : expectedViewportPixels,
      pixel_dimensions_match_expected: fullPage ? null : true,
      screenshot_budget_bytes: SCREENSHOT_LIMIT_BYTES,
      within_400_kib_budget: buffer.byteLength <= SCREENSHOT_LIMIT_BYTES,
    };
  };

  const viewport = await boundedJpeg(viewportPath, false);
  const fullPagePolicy = selectFullPageCapture(dimensions, FULL_PAGE_CAPTURE_LIMITS);
  let full;
  if (fullPagePolicy.complete_document) {
    full = await boundedJpeg(fullPath, true);
  } else {
    full = await boundedJpeg(fullPath, false);
  }
  return {
    viewport,
    full: {
      ...full,
      complete_document: fullPagePolicy.complete_document,
      note: fullPagePolicy.reason,
      capture_policy: fullPagePolicy,
    },
    dimensions,
  };
}

async function exerciseReleaseMenu(page) {
  const menuSelector = CONTRACT.selectors.release_menu;
  const openerSelector = CONTRACT.selectors.release_menu_opener;
  const base = await page.evaluate(({ menuSelector: menuQuery, openerSelector: openerQuery }) => {
    const menu = document.querySelector(menuQuery);
    const opener = document.querySelector(openerQuery);
    const visible = (element) => {
      if (!element) return false;
      const style = getComputedStyle(element);
      const rect = element.getBoundingClientRect();
      return style.display !== "none" && style.visibility !== "hidden" && rect.width > 0 && rect.height > 0;
    };
    return {
      menu_present: Boolean(menu),
      menu_initially_visible: visible(menu),
      opener_present: Boolean(opener),
      opener_visible: visible(opener),
    };
  }, { menuSelector, openerSelector });
  if (!base.opener_present || !base.opener_visible) return { ...base, exercised: false };

  const originalScroll = await page.evaluate(() => {
    const root = document.scrollingElement || document.documentElement;
    const main = document.querySelector(".main");
    return {
      root: { x: root.scrollLeft, y: root.scrollTop },
      main: main ? { x: main.scrollLeft, y: main.scrollTop } : null,
    };
  });
  const restoreOriginalScroll = () => page.evaluate((positions) => {
    const root = document.scrollingElement || document.documentElement;
    const main = document.querySelector(".main");
    root.scrollTo(positions.root.x, positions.root.y);
    if (main && positions.main) main.scrollTo(positions.main.x, positions.main.y);
  }, originalScroll);

  try {
    await page.locator(openerSelector).first().click();
    await page.waitForFunction((selector) => {
      const menu = document.querySelector(selector);
      if (!menu) return false;
      const rect = menu.getBoundingClientRect();
      const style = getComputedStyle(menu);
      return style.display !== "none" && style.visibility !== "hidden" && rect.width > 0 && rect.height > 0;
    }, menuSelector, { timeout: 5_000 });

    const opened = await page.evaluate((selector) => {
      const menu = document.querySelector(selector);
      const rect = menu.getBoundingClientRect();
      const style = getComputedStyle(menu);
      const isPopover = menu.matches(":popover-open");
      const isDialog = menu instanceof HTMLDialogElement && menu.open;
      const htmlOverflow = getComputedStyle(document.documentElement).overflowY;
      const bodyOverflow = getComputedStyle(document.body).overflowY;
      const main = document.querySelector(".main");
      const mainOverflow = main ? getComputedStyle(main).overflowY : null;
      const fitsViewport = rect.top >= -0.5 && rect.left >= -0.5
        && rect.bottom <= innerHeight + 0.5 && rect.right <= innerWidth + 0.5;
      const internallyScrollable = /(auto|scroll)/u.test(style.overflowY)
        && menu.scrollHeight > menu.clientHeight + 1
        && rect.height <= innerHeight + 0.5;
      return {
        rect: {
          top: rect.top,
          right: rect.right,
          bottom: rect.bottom,
          left: rect.left,
          width: rect.width,
          height: rect.height,
        },
        viewport: { width: innerWidth, height: innerHeight },
        overlay_open: isPopover || isDialog || menu.getAttribute("aria-modal") === "true",
        popover_open: isPopover,
        dialog_open: isDialog,
        fits_viewport: fitsViewport,
        internally_scrollable: internallyScrollable,
        scroll_height: menu.scrollHeight,
        client_height: menu.clientHeight,
        overflow_y: style.overflowY,
        lock_styles: { html: htmlOverflow, body: bodyOverflow, main: mainOverflow },
        underlying_scroll_locked: [htmlOverflow, bodyOverflow, mainOverflow].some((value) => value === "hidden"),
      };
    }, menuSelector);

    const candidates = [
      { x: 1, y: 1 },
      { x: opened.viewport.width - 2, y: 1 },
      { x: 1, y: opened.viewport.height - 2 },
      { x: opened.viewport.width - 2, y: opened.viewport.height - 2 },
    ];
    const outside = candidates.find(({ x, y }) => (
      x < opened.rect.left || x > opened.rect.right || y < opened.rect.top || y > opened.rect.bottom
    ));
    let outsideDismiss = false;
    let scrollProbe = {
      attempted: false,
      locked: false,
      before: null,
      after: null,
      deltas: null,
    };
    if (outside) {
      const beforeScroll = await page.evaluate(() => {
        const root = document.scrollingElement || document.documentElement;
        const main = document.querySelector(".main");
        return {
          root: { x: root.scrollLeft, y: root.scrollTop },
          main: main ? { x: main.scrollLeft, y: main.scrollTop } : null,
        };
      });
      await page.mouse.move(outside.x, outside.y);
      await page.mouse.wheel(0, 160);
      await page.evaluate(() => new Promise((resolve) => {
        requestAnimationFrame(() => requestAnimationFrame(resolve));
      }));
      const afterScroll = await page.evaluate(() => {
        const root = document.scrollingElement || document.documentElement;
        const main = document.querySelector(".main");
        return {
          root: { x: root.scrollLeft, y: root.scrollTop },
          main: main ? { x: main.scrollLeft, y: main.scrollTop } : null,
        };
      });
      const deltas = {
        root_x: afterScroll.root.x - beforeScroll.root.x,
        root_y: afterScroll.root.y - beforeScroll.root.y,
        main_x: afterScroll.main && beforeScroll.main ? afterScroll.main.x - beforeScroll.main.x : 0,
        main_y: afterScroll.main && beforeScroll.main ? afterScroll.main.y - beforeScroll.main.y : 0,
      };
      scrollProbe = {
        attempted: true,
        locked: Object.values(deltas).every((value) => Math.abs(value) < 1),
        before: beforeScroll,
        after: afterScroll,
        deltas,
      };
      await page.evaluate((positions) => {
        const root = document.scrollingElement || document.documentElement;
        const main = document.querySelector(".main");
        root.scrollTo(positions.root.x, positions.root.y);
        if (main && positions.main) main.scrollTo(positions.main.x, positions.main.y);
      }, beforeScroll);
      await page.mouse.click(outside.x, outside.y);
      outsideDismiss = await page.waitForFunction((selector) => {
        const menu = document.querySelector(selector);
        if (!menu) return true;
        const rect = menu.getBoundingClientRect();
        const style = getComputedStyle(menu);
        return style.display === "none" || style.visibility === "hidden" || rect.width === 0 || rect.height === 0;
      }, menuSelector, { timeout: 2_000 }).then(() => true, () => false);
    }
    if (!outsideDismiss) await page.keyboard.press("Escape").catch(() => {});
    const result = {
      ...base,
      ...opened,
      exercised: true,
      open_error: null,
      outside_point: outside || null,
      outside_dismiss: outsideDismiss,
      underlying_scroll_probe: scrollProbe,
      underlying_scroll_locked: scrollProbe.locked,
    };
    await restoreOriginalScroll();
    return result;
  } catch (error) {
    await page.keyboard.press("Escape").catch(() => {});
    await restoreOriginalScroll().catch(() => {});
    return { ...base, exercised: true, open_error: serialiseError(error), outside_dismiss: false };
  }
}

async function collectStaticMeasurements(page, cell, safeArea, menuExercise) {
  return page.evaluate(async ({ contract, cellSpec, safeAreaState, menuExerciseState }) => {
    const { selectors, thresholds } = contract;
    const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve));
    const rectData = (rect) => ({
      x: Number(rect.x.toFixed(2)),
      y: Number(rect.y.toFixed(2)),
      top: Number(rect.top.toFixed(2)),
      right: Number(rect.right.toFixed(2)),
      bottom: Number(rect.bottom.toFixed(2)),
      left: Number(rect.left.toFixed(2)),
      width: Number(rect.width.toFixed(2)),
      height: Number(rect.height.toFixed(2)),
    });
    const elementLabel = (element) => {
      if (!element) return null;
      if (element.id) return `#${element.id}`;
      const classes = [...element.classList].slice(0, 3).join(".");
      return `${element.tagName.toLowerCase()}${classes ? `.${classes}` : ""}`;
    };
    const cssVisible = (element) => {
      if (!(element instanceof Element)) return false;
      const style = getComputedStyle(element);
      if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) return false;
      if (typeof element.checkVisibility === "function") {
        return element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });
      }
      return Boolean(element.getClientRects().length);
    };
    const rendered = (element) => {
      if (!cssVisible(element)) return false;
      const rect = element.getBoundingClientRect();
      return rect.width > 0 && rect.height > 0;
    };
    const inViewport = (rect) => (
      rect.bottom > 0 && rect.right > 0 && rect.top < innerHeight && rect.left < innerWidth
    );
    const intersectRect = (rect, clip) => {
      const left = Math.max(rect.left, clip.left);
      const top = Math.max(rect.top, clip.top);
      const right = Math.min(rect.right, clip.right);
      const bottom = Math.min(rect.bottom, clip.bottom);
      if (right <= left || bottom <= top) return null;
      return {
        x: left,
        y: top,
        left,
        top,
        right,
        bottom,
        width: right - left,
        height: bottom - top,
      };
    };
    const visibleHitRect = (element) => {
      let visible = intersectRect(element.getBoundingClientRect(), {
        left: 0,
        top: 0,
        right: innerWidth,
        bottom: innerHeight,
      });
      if (!visible) return null;
      for (let ancestor = element.parentElement; ancestor && visible; ancestor = ancestor.parentElement) {
        const style = getComputedStyle(ancestor);
        const clipX = /^(?:auto|clip|hidden|scroll)$/u.test(style.overflowX);
        const clipY = /^(?:auto|clip|hidden|scroll)$/u.test(style.overflowY);
        if (!clipX && !clipY) continue;
        const ancestorRect = ancestor.getBoundingClientRect();
        visible = intersectRect(visible, {
          left: clipX ? ancestorRect.left : -Infinity,
          top: clipY ? ancestorRect.top : -Infinity,
          right: clipX ? ancestorRect.right : Infinity,
          bottom: clipY ? ancestorRect.bottom : Infinity,
        });
      }
      return visible;
    };
    const elementOwnsHitAt = (element, x, y) => {
      if (x < 0 || y < 0 || x >= innerWidth || y >= innerHeight) return false;
      const hit = document.elementFromPoint(x, y);
      return Boolean(hit && (hit === element || element.contains(hit)));
    };
    const visibleHitWithin = (element, rect) => {
      if (!rect) return false;
      const epsilon = 0.25;
      const xs = [
        rect.left + rect.width / 2,
        Math.min(rect.right - epsilon, rect.left + epsilon),
        Math.max(rect.left + epsilon, rect.right - epsilon),
      ];
      const ys = [
        rect.top + rect.height / 2,
        Math.min(rect.bottom - epsilon, rect.top + epsilon),
        Math.max(rect.top + epsilon, rect.bottom - epsilon),
      ];
      return xs.some((x) => ys.some((y) => elementOwnsHitAt(element, x, y)));
    };
    const hitTestable = (element) => {