"""Grounded execution environment for MAUI-Bench (computer-use arm). Renders benchmark instances (menu orderings, grid layouts) into real HTML interfaces, screenshots them with headless Chromium, and exposes three grounding interfaces of increasing structure: pixel : the raw screenshot; the agent answers with click coordinates som : the screenshot with Set-of-Marks numeric tags overlaid; the agent answers with a mark id a11y : a serialized accessibility tree (role, name, bbox); the agent answers with an element id (usable by text-only models) Because the environment generates the HTML itself, every element's ground truth bounding box is known by construction (fixed CSS geometry, no reflow), so click hits, pixel error, and Fitts index of difficulty from actual rendered geometry are computed exactly. A click episode is scored: hit : click lands inside the target bbox (pixel mode), or the selected mark/element id equals the target (som/a11y) pixel_error : Euclidean distance from click to target center (pixel mode) fitts_id : log2(D/W + 1) of the target from screen center, bits, using the rendered geometry (MacKenzie formulation) No JavaScript runs in the page; the page is static and deterministic given the instance, so screenshots are reproducible byte-for-byte across runs of the same Chromium build. """ from __future__ import annotations import base64 import hashlib import json import math import os import subprocess import tempfile CHROMIUM = os.environ.get("MAUI_CHROMIUM", "/snap/bin/chromium") VIEWPORT = (1280, 800) CELL_W, CELL_H = 220, 64 # layout grid cell, px (regular density) MENU_W, MENU_ITEM_H = 320, 44 # menu geometry, px (regular density) MARGIN = 40 # Density scales rendered target geometry, sweeping the Fitts index of # difficulty range so grounding accuracy can be reported as a function of # ID with everything else controlled. DENSITIES = {"regular": 1.0, "compact": 0.6, "dense": 0.35} FONT_CSS = ("font-family: system-ui, 'Segoe UI', Arial, sans-serif;" "-webkit-font-smoothing: antialiased;") # --------------------------------------------------------------------- render def _tag(i: int, fs: int, tag_style: str) -> str: """Set-of-Marks tag markup. scaled: font tracks density; fixed: font stays 11px at every density; outside: 11px tag left of the element.""" if tag_style == "fixed": return (f"{i}") if tag_style == "outside": return (f"{i}") return (f"{i}") def menu_html(order: list[str], som: bool = False, density: str = "regular", tag_style: str = "scaled") -> tuple[str, dict]: """Vertical menu; returns html and {label: bbox} with bbox=(x,y,w,h).""" s = DENSITIES[density] mw, mh = int(MENU_W * s), max(16, int(MENU_ITEM_H * s)) fs = max(8, int(15 * s)) items, boxes = [], {} for i, label in enumerate(order): x, y = MARGIN, MARGIN + i * mh boxes[label] = (x, y, mw, mh) tag = _tag(i + 1, fs, tag_style) if som else "" items.append( f"
{tag}{label}
") html = (f"" f"" f"
Application menu
" + "".join(items) + "") return html, boxes def layout_html(assignment: dict[str, int], shape: tuple[int, int], som: bool = False, density: str = "regular", tag_style: str = "scaled") -> tuple[str, dict]: """Grid of buttons; assignment maps control name -> slot index (row-major).""" rows, cols = shape s = DENSITIES[density] cw, ch = max(40, int(CELL_W * s)), max(18, int(CELL_H * s)) gap = max(4, int(16 * s)) fs = max(8, int(15 * s)) items, boxes = [], {} inv = {v: k for k, v in assignment.items()} n = 0 for slot in range(rows * cols): r, c = divmod(slot, cols) x = MARGIN + c * (cw + gap) y = MARGIN + r * (ch + gap) label = inv.get(slot) if label is None: items.append( f"
") continue n += 1 boxes[label] = (x, y, cw, ch) tag = _tag(n, fs, tag_style) if som else "" items.append( f"
{tag}{label}
") html = ("" f"" f"
Toolbar
" + "".join(items) + "") return html, boxes def screenshot(html: str, out_png: str) -> None: """Render html to out_png with headless Chromium (deterministic).""" os.makedirs(os.path.dirname(out_png), exist_ok=True) with tempfile.NamedTemporaryFile("w", suffix=".html", delete=False, dir=os.path.dirname(out_png)) as f: f.write(html) path = f.name try: subprocess.run( [CHROMIUM, "--headless", "--disable-gpu", "--hide-scrollbars", f"--screenshot={out_png}", f"--window-size={VIEWPORT[0]},{VIEWPORT[1]}", f"file://{path}"], check=True, capture_output=True, timeout=60) finally: os.unlink(path) def a11y_tree(boxes: dict, kind: str) -> str: """Serialized accessibility tree with roles, names, and bboxes.""" role = "menuitem" if kind == "menu" else "button" lines = [f"[window 'Application' 0,0,{VIEWPORT[0]}x{VIEWPORT[1]}]"] for i, (label, (x, y, w, h)) in enumerate(boxes.items()): lines.append(f" [e{i} role={role} name='{label}' bbox={x},{y},{w}x{h}]") return "\n".join(lines) # --------------------------------------------------------------------- scoring def target_center(boxes: dict, target: str) -> tuple[float, float]: x, y, w, h = boxes[target] return (x + w / 2.0, y + h / 2.0) def fitts_id_bits(boxes: dict, target: str, origin: tuple[float, float] | None = None) -> float: """MacKenzie ID from origin (screen center by default) to target, using the smaller side of the rendered bbox as W.""" ox, oy = origin or (VIEWPORT[0] / 2.0, VIEWPORT[1] / 2.0) cx, cy = target_center(boxes, target) d = math.hypot(cx - ox, cy - oy) w = min(boxes[target][2], boxes[target][3]) return math.log2(d / w + 1.0) def score_pixel_click(boxes: dict, target: str, click: tuple[float, float] | None) -> dict: cx, cy = target_center(boxes, target) if click is None: return {"hit": False, "pixel_error": None, "in_any": None} x, y = click tx, ty, tw, th = boxes[target] hit = (tx <= x <= tx + tw) and (ty <= y <= ty + th) in_any = any((bx <= x <= bx + bw) and (by <= y <= by + bh) for bx, by, bw, bh in boxes.values()) return {"hit": bool(hit), "pixel_error": float(math.hypot(x - cx, y - cy)), "in_any": bool(in_any)} def png_b64(path: str) -> str: with open(path, "rb") as f: return base64.b64encode(f.read()).decode() def content_key(*parts) -> str: return hashlib.sha1(json.dumps(parts, sort_keys=True).encode()).hexdigest()[:16]