diff --git a/tasks/dasyn_260630_00013/environment/Dockerfile b/tasks/dasyn_260630_00013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00013/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00013/environment/setup/setup.sh b/tasks/dasyn_260630_00013/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00013/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00013/tests/grade.json b/tasks/dasyn_260630_00013/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..e9f3caacf5694579879925c197ac4184da40be61 --- /dev/null +++ b/tasks/dasyn_260630_00013/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a corporate architecture gallery event site in React + Tailwind, elegant original design, static sample projects/speakers only, smooth page transitions." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00013/tests/grade.py b/tasks/dasyn_260630_00013/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00013/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00013/tests/test.sh b/tasks/dasyn_260630_00013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00013/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00013/tests/webdev/__init__.py b/tasks/dasyn_260630_00013/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00013/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00013/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00013/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00013/tests/webdev/shot.py b/tasks/dasyn_260630_00013/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00013/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00013/tests/webdev/verdict.py b/tasks/dasyn_260630_00013/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00013/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00014/environment/Dockerfile b/tasks/dasyn_260630_00014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00014/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00014/environment/setup/setup.sh b/tasks/dasyn_260630_00014/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00014/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00014/tests/grade.json b/tasks/dasyn_260630_00014/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..e881fdf156b2f6a74fa152799b4fee852146591b --- /dev/null +++ b/tasks/dasyn_260630_00014/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build me a static website for a small Scandinavian style restaurant/cafe that also publishes local music news and weekly listening picks. I want it to feel clean like ProductHunt cards but warmer, with lots of white space, soft beige/blue colors, simple typography, and easy UI. Pages/sections: hero with restaurant name and short intro, featured music news cards, today menu, upcoming acoustic nights, chef playlist picks, about section, opening hours, location text, and contact/footer. Use only vanilla HTML CSS and JS, no backend or API, all news/menu/event content can be sample static data in the page. Add simple interactions like category filter for news cards and mobile menu." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00014/tests/grade.py b/tasks/dasyn_260630_00014/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00014/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00014/tests/test.sh b/tasks/dasyn_260630_00014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00014/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00014/tests/webdev/__init__.py b/tasks/dasyn_260630_00014/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00014/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00014/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00014/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00014/tests/webdev/shot.py b/tasks/dasyn_260630_00014/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00014/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00014/tests/webdev/verdict.py b/tasks/dasyn_260630_00014/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00014/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00015/environment/Dockerfile b/tasks/dasyn_260630_00015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00015/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00015/environment/setup/setup.sh b/tasks/dasyn_260630_00015/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00015/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00015/tests/grade.json b/tasks/dasyn_260630_00015/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..1073b934a0ff14993550d1a89df50b1f99682b61 --- /dev/null +++ b/tasks/dasyn_260630_00015/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Make a bold charity shop editorial website like a clean GitHub project page style, where people can read stories about donated products and browse items for a cause. Add a simple search bar to filter the mock products and articles, use GSAP for smooth section animations, and keep everything static with sample content only, no login or payment system." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00015/tests/grade.py b/tasks/dasyn_260630_00015/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00015/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00015/tests/test.sh b/tasks/dasyn_260630_00015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00015/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00015/tests/webdev/__init__.py b/tasks/dasyn_260630_00015/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00015/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00015/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00015/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00015/tests/webdev/shot.py b/tasks/dasyn_260630_00015/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00015/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00015/tests/webdev/verdict.py b/tasks/dasyn_260630_00015/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00015/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00025/environment/Dockerfile b/tasks/dasyn_260630_00025/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00025/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00025/environment/setup/setup.sh b/tasks/dasyn_260630_00025/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00025/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00025/tests/grade.json b/tasks/dasyn_260630_00025/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..3f6f510055e1771c19f1cacab2f6a73f9f0d8e96 --- /dev/null +++ b/tasks/dasyn_260630_00025/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Design a clean swiss style landing page for an online entertainment store like Amazon but only for movies, music albums, comedy shows and event tickets, make it static front end only with sample products and fake prices. I want a hero section with big bold typography, white space, black red and yellow accent colors, product cards arranged like amazon deals, featured categories, best sellers, new releases, customer ratings shown as static stars, and a simple cart preview area. Add drag and drop interaction where users can drag product cards into a wishlist or cart box and use GSAP animations for smooth card movement, hover effects, section reveal and banner transitions. Include sections for today entertainment deals, streaming bundles, concert pass offers, kids shows, and gift cards. Make it look professional and easy to shop, responsive for mobile and desktop, no login, no payment, no real checkout, no backend or database, just mock content and static sample images/placeholders. Add editable contact/footer text and a promo strip like Amazon but more modern and minimal." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00025/tests/grade.py b/tasks/dasyn_260630_00025/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00025/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00025/tests/test.sh b/tasks/dasyn_260630_00025/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00025/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00025/tests/webdev/__init__.py b/tasks/dasyn_260630_00025/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00025/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00025/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00025/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00025/tests/webdev/shot.py b/tasks/dasyn_260630_00025/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00025/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00025/tests/webdev/verdict.py b/tasks/dasyn_260630_00025/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00025/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00040/environment/Dockerfile b/tasks/dasyn_260630_00040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00040/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00040/environment/setup/setup.sh b/tasks/dasyn_260630_00040/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00040/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00040/tests/grade.json b/tasks/dasyn_260630_00040/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..c19596e79a5a38373c53e7aed60f7021578fb26c --- /dev/null +++ b/tasks/dasyn_260630_00040/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a playful static website in SvelteKit for a dental marketplace product showcase called ToothCart. It should feel like a bright Vercel-style landing page but more fun and friendly, with rounded cards, soft shadows, candy colors, clean spacing, responsive mobile layout, and smooth micro interactions. IMPORTANT: this is only a static front-end site, no backend, no database, no login, no checkout, no real payments, no external APIs. Use mock/sample product data inside the project.\n\nPages/sections needed:\n- Hero section: headline like “Find cute dental supplies in seconds”, short subtitle, 2 CTA buttons, playful tooth mascot illustration placeholder, trust badges\n- Featured marketplace grid: dental products such as toothbrush kits, whitening strips, floss packs, braces wax, kids dental care set, mouthwash tablets, tongue cleaner, travel hygiene kit\n- Drag-and-drop feature: user can drag product cards into a “Compare Basket” or “Smile Kit Builder” area on the page. Keep it simple: drag product cards into a tray, show selected item names/prices, allow removing items, and show a mock total. This must be client-side only with static data.\n- Category pills: Cleaning, Whitening, Kids, Orthodontic, Travel, Eco Friendly. Clicking can just filter the static product list in the UI.\n- Product card design: image placeholder or simple CSS illustration, name, tag, rating, mock price, short description, “Add to kit” button\n- How it works section: Browse, Drag to compare, Pick your smile kit\n- Promo banner: playful dental discount message, no real coupon validation\n- Testimonials: 3 fake customer reviews\n- FAQ: static accordion, questions about product quality, shipping mock text, returns mock text, dentist recommendations. Do not connect to anything real.\n- Footer: logo, simple links, social placeholders, disclaimer “Demo static marketplace showcase”.\n\nDesign requirements:\n- Style should be playful, clean, modern, like a polished Vercel landing page mixed with dental/toothpaste colors.\n- Use white background with mint, sky blue, lavender, peach accents.\n- Use cute icons/emojis or simple inline SVG/CSS shapes if needed, but no image generation required.\n- Add hover effects, card lift, small sparkle/tooth decorations, gentle gradients.\n- Fully responsive for desktop/tablet/mobile.\n- Make it feel like a real marketplace but it is just a static product showcase.\n\nTechnical requirements:\n- Use SvelteKit.\n- Static rendering only, suitable to deploy on Vercel as a static front-end.\n- Keep all product content local/mock, preferably in a simple array.\n- No auth, no cart checkout, no API routes, no server actions, no database.\n- Drag-and-drop should work with normal browser events or Svelte actions, simple and reliable.\n- Please create neat components like Hero, ProductGrid, ProductCard, CompareTray, CategoryFilter, Testimonials, FAQ, Footer.\n- Include basic accessibility: keyboard focus styles, alt text/placeholders, readable contrast, semantic sections.\n- Final result should look polished enough for a startup landing page demo." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00040/tests/grade.py b/tasks/dasyn_260630_00040/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00040/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00040/tests/test.sh b/tasks/dasyn_260630_00040/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00040/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00040/tests/webdev/__init__.py b/tasks/dasyn_260630_00040/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00040/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00040/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00040/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00040/tests/webdev/shot.py b/tasks/dasyn_260630_00040/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00040/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00040/tests/webdev/verdict.py b/tasks/dasyn_260630_00040/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00040/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00047/environment/Dockerfile b/tasks/dasyn_260630_00047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00047/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00047/environment/setup/setup.sh b/tasks/dasyn_260630_00047/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00047/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00047/tests/grade.json b/tasks/dasyn_260630_00047/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..6a21453b8d3737110208a6bc5abe84efe6bf5e53 --- /dev/null +++ b/tasks/dasyn_260630_00047/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build a static React + Tailwind editorial website for a wedding at an elderly-care home, brutalist style, complex scroll-driven sections, YouTube-inspired video/story layout but use only mock thumbnails and static content, no backend." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00047/tests/grade.py b/tasks/dasyn_260630_00047/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00047/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00047/tests/test.sh b/tasks/dasyn_260630_00047/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00047/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00047/tests/webdev/__init__.py b/tasks/dasyn_260630_00047/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00047/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00047/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00047/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00047/tests/webdev/shot.py b/tasks/dasyn_260630_00047/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00047/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00047/tests/webdev/verdict.py b/tasks/dasyn_260630_00047/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00047/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00071/environment/Dockerfile b/tasks/dasyn_260630_00071/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00071/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00071/environment/setup/setup.sh b/tasks/dasyn_260630_00071/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00071/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00071/tests/grade.json b/tasks/dasyn_260630_00071/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..380a488cd63649d5eca876934e332823e48f29cc --- /dev/null +++ b/tasks/dasyn_260630_00071/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "# Build a Static Editorial Website\n\nCreate a bold, modern editorial-style website for **The Parish Motor Journal**, a church community publication that writes about automotive life, safe driving, family road trips, volunteer transport, classic cars, and faith-based community stories.\n\nThe website should feel like a mix of an online magazine and a ProductHunt-style discovery page, but for church members who love cars and community service. It must be a **pure static front-end website only**. Use mock/static/sample content only. No backend, no database, no login, no live API, no real chatbot service.\n\n---\n\n## Overall Style\n\n- Bold visual design\n- Editorial magazine layout\n- ProductHunt-inspired cards, upvotes, rankings, badges, and launch-style sections\n- Clean but energetic church community feeling\n- Automotive colors: charcoal, cream, red-orange, chrome gray, warm gold\n- Large headlines and strong typography\n- Mobile responsive\n- Simple UI, not too complex\n- Should look polished enough for a real church media team\n\n---\n\n## Required Pages / Sections\n\n### 1. Home Page\n\nInclude:\n\n- Hero section with headline: “Faith, Roads & Community Stories”\n- Short intro paragraph about a church automotive editorial site\n- Featured article card\n- “This Week’s Top Stories” section\n- ProductHunt-style story ranking cards with:\n - Story title\n - Category badge\n - Short summary\n - Mock upvote count\n - Author name\n - Reading time\n- CTA buttons:\n - Read Latest Issue\n - Explore Community Garage\n\n---\n\n### 2. Featured Editorial Section\n\nCreate a bold editorial block for one main article:\n\nExample content idea:\n\n**“How the Sunday Shuttle Ministry Keeps the Community Moving”**\n\nInclude:\n\n- Large image placeholder area\n- Category label\n- Article headline\n- Pull quote\n- Author info\n- Date\n- Read time\n- Button: Read Feature\n\nUse static content only.\n\n---\n\n### 3. ProductHunt-Style Automotive Story Board\n\nCreate a section called **Community Launch Board**.\n\nThis should look like ProductHunt but for church automotive stories, events, and resources.\n\nCards should include mock items like:\n\n- “Classic Car Blessing Day”\n- “Volunteer Van Maintenance Checklist”\n- “Teen Driver Safety Night”\n- “Road Trip Devotional Playlist”\n- “Parish Garage Tool Share”\n\nEach card should show:\n\n- Icon or image placeholder\n- Title\n- One-line description\n- Tag badges\n- Mock upvotes\n- Comment count\n- Ranking number\n\nDo not make the voting functional beyond basic front-end static/visual behavior if needed.\n\n---\n\n### 4. Article Categories\n\nAdd category tiles for:\n\n- Community Cars\n- Safety & Stewardship\n- Classic Auto Stories\n- Road Trip Faith\n- Volunteer Transport\n- Garage Guides\n\nEach tile should include a short description and simple icon style.\n\n---\n\n### 5. Static Chatbot Widget\n\nAdd a small chatbot-style interaction called **Ask the Parish Garage Bot**.\n\nImportant: this must be fake/static only. No AI API, no backend, no external service.\n\nThe widget should:\n\n- Sit in the bottom-right corner or appear as an embedded panel\n- Open/close when clicked\n- Show a few predefined sample questions\n- Display canned responses when a user clicks a question\n\nSample questions:\n\n- “Where can I read this week’s featured story?”\n- “What is the Community Launch Board?”\n- “How do I submit a church automotive story?”\n- “Are the upvotes real?”\n\nSample answers should explain the site using static content.\n\n---\n\n### 6. Submit Story CTA Section\n\nCreate a static call-to-action section for people who want to submit a story.\n\nInclude:\n\n- Heading: “Have a Story from the Road?”\n- Short paragraph\n- Static form UI only with fields:\n - Name\n - Story Title\n - Category\n - Short Summary\n- Button: Submit Story Idea\n\nThe form does not need to send anything. It can show a simple front-end success message or just be visual.\n\n---\n\n### 7. About Section\n\nExplain that The Parish Motor Journal is a community editorial project celebrating:\n\n- Church transportation ministry\n- Safe driving\n- Family road travel\n- Car care wisdom\n- Faith-inspired service\n- Stories from local members\n\nUse warm but professional writing.\n\n---\n\n### 8. Footer\n\nInclude:\n\n- Site name\n- Short mission statement\n- Navigation links\n- Mock social links\n- Newsletter signup UI only, no real submission\n- Small disclaimer: “Static demo website using sample content only.”\n\n---\n\n## Design Requirements\n\n- Bold hero layout\n- ProductHunt-inspired cards and ranking feel\n- Editorial article layout with large typography\n- Automotive visual accents like road lines, dashboard-style badges, speedometer-inspired icons, grille patterns, or tire-track dividers\n- Church-friendly tone, not corporate or aggressive\n- Good spacing and hierarchy\n- Responsive layout for desktop, tablet, and mobile\n- Smooth hover effects\n- Sticky or clean top navigation\n\n---\n\n## Technical Requirements\n\nUse React with simple components and static data arrays. No backend. No authentication. No database. No external APIs. No server-side code. All content can be hardcoded or stored in local static arrays.\n\nRecommended components:\n\n- Header\n- Hero\n- FeaturedArticle\n- LaunchBoard\n- CategoryGrid\n- ChatbotWidget\n- SubmitStoryCTA\n- AboutSection\n- Footer\n\nThe final result should be a complete static website that can run locally and render without external services." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00071/tests/grade.py b/tasks/dasyn_260630_00071/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00071/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00071/tests/test.sh b/tasks/dasyn_260630_00071/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00071/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00071/tests/webdev/__init__.py b/tasks/dasyn_260630_00071/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00071/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00071/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00071/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00071/tests/webdev/shot.py b/tasks/dasyn_260630_00071/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00071/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00071/tests/webdev/verdict.py b/tasks/dasyn_260630_00071/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00071/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00078/environment/Dockerfile b/tasks/dasyn_260630_00078/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00078/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00078/environment/setup/setup.sh b/tasks/dasyn_260630_00078/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00078/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00078/tests/grade.json b/tasks/dasyn_260630_00078/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..4fea8b534e480145df7fa29d33b6a74f1f3b41e1 --- /dev/null +++ b/tasks/dasyn_260630_00078/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a clean light themed static restaurant website for an online food ordering concept. I want it to feel a bit like YouTube in layout: a big featured hero section, horizontal category chips, card-based food items, and an infinite-scroll style menu grid that keeps loading more mock dishes as the user scrolls. Include sections for popular meals, chef recommendations, combo deals, customer reviews, and a simple cart preview UI, but everything can use static sample data only. Make the design modern, mobile responsive, smooth, and suitable for a local restaurant selling burgers, pasta, salads, desserts, and drinks. No backend, no real payments, no login, no external APIs; just a polished static front-end demo." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00078/tests/grade.py b/tasks/dasyn_260630_00078/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00078/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00078/tests/test.sh b/tasks/dasyn_260630_00078/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00078/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00078/tests/webdev/__init__.py b/tasks/dasyn_260630_00078/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00078/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00078/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00078/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00078/tests/webdev/shot.py b/tasks/dasyn_260630_00078/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00078/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00078/tests/webdev/verdict.py b/tasks/dasyn_260630_00078/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00078/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00085/environment/Dockerfile b/tasks/dasyn_260630_00085/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00085/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00085/environment/setup/setup.sh b/tasks/dasyn_260630_00085/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00085/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00085/tests/grade.json b/tasks/dasyn_260630_00085/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..a5e218b244085db1a03a799673835aa563d62fa3 --- /dev/null +++ b/tasks/dasyn_260630_00085/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a static SvelteKit event site for an agriculture membership summit. Use soft neomorphism, complex scroll-driven sections, GitHub-style repo/cards for agenda, speakers, member tiers, sponsor logos, and sample content only. No backend or login." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00085/tests/grade.py b/tasks/dasyn_260630_00085/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00085/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00085/tests/test.sh b/tasks/dasyn_260630_00085/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00085/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00085/tests/webdev/__init__.py b/tasks/dasyn_260630_00085/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00085/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00085/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00085/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00085/tests/webdev/shot.py b/tasks/dasyn_260630_00085/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00085/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00085/tests/webdev/verdict.py b/tasks/dasyn_260630_00085/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00085/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00217/environment/Dockerfile b/tasks/dasyn_260630_00217/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00217/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00217/environment/setup/setup.sh b/tasks/dasyn_260630_00217/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00217/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00217/tests/grade.json b/tasks/dasyn_260630_00217/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..7dabfe5b03094f17e99851123a043209223da7a7 --- /dev/null +++ b/tasks/dasyn_260630_00217/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build me a simple static landing page for a fitness gear shop, kind of ProductHunt style with flat cards, hero section, featured products, categories, and a search bar to filter the mock product list. Use sample content only, no backend or login, make it clean and responsive." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00217/tests/grade.py b/tasks/dasyn_260630_00217/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00217/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00217/tests/test.sh b/tasks/dasyn_260630_00217/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00217/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00217/tests/webdev/__init__.py b/tasks/dasyn_260630_00217/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00217/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00217/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00217/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00217/tests/webdev/shot.py b/tasks/dasyn_260630_00217/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00217/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00217/tests/webdev/verdict.py b/tasks/dasyn_260630_00217/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00217/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00219/environment/Dockerfile b/tasks/dasyn_260630_00219/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00219/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00219/environment/setup/setup.sh b/tasks/dasyn_260630_00219/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00219/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00219/tests/grade.json b/tasks/dasyn_260630_00219/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..ecd619d4bfc76f294b935a1feb39b9676cad078f --- /dev/null +++ b/tasks/dasyn_260630_00219/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a static portfolio website for a boutique coffee shop called \"Velvet Roast\" using React + Tailwind CSS. Design inspiration: Spotify style dark UI with green/caramel gradients, rounded cards, bold typography, and smooth hover states. Sections needed: Hero with big headline \"Brewed Like a Playlist\", short intro, CTA buttons; About the cafe; Signature Coffee Portfolio with cards for espresso, cold brew, latte art, seasonal blends using mock/sample content only; Barista Team section; Gallery grid; Customer vibe/testimonials; Contact/location block with static info. Add a fun drag-and-drop interaction where users can drag coffee cards into a \"My Coffee Lineup\" area, like building a playlist, but keep it fully front-end/static with no backend or saved accounts. Must be responsive for mobile/tablet/desktop, polished gradient background, modern animations, and no external APIs or database." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00219/tests/grade.py b/tasks/dasyn_260630_00219/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00219/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00219/tests/test.sh b/tasks/dasyn_260630_00219/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00219/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00219/tests/webdev/__init__.py b/tasks/dasyn_260630_00219/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00219/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00219/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00219/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00219/tests/webdev/shot.py b/tasks/dasyn_260630_00219/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00219/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00219/tests/webdev/verdict.py b/tasks/dasyn_260630_00219/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00219/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00221/environment/Dockerfile b/tasks/dasyn_260630_00221/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00221/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00221/environment/setup/setup.sh b/tasks/dasyn_260630_00221/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00221/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00221/tests/grade.json b/tasks/dasyn_260630_00221/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..f6662e0fefb6f766a93dc65613c869193f0bb11f --- /dev/null +++ b/tasks/dasyn_260630_00221/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a playful Nuxt static event website for an online course marketplace called SkillPop Summit. It should feel like a colorful virtual expo where people discover mini-courses, workshops, mentor sessions, and creator booths. Make a bold hero section, event schedule, featured instructors, course cards, pricing/pass section, FAQ, sponsor strip, and an infinite-scroll style course marketplace feed using mock content only. Keep it fun with stickers, gradients, chunky buttons, soft shadows, and lively illustrations/placeholders, but still polished and easy to browse on mobile and desktop." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00221/tests/grade.py b/tasks/dasyn_260630_00221/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00221/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00221/tests/test.sh b/tasks/dasyn_260630_00221/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00221/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00221/tests/webdev/__init__.py b/tasks/dasyn_260630_00221/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00221/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00221/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00221/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00221/tests/webdev/shot.py b/tasks/dasyn_260630_00221/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00221/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00221/tests/webdev/verdict.py b/tasks/dasyn_260630_00221/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00221/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00226/environment/Dockerfile b/tasks/dasyn_260630_00226/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00226/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00226/environment/setup/setup.sh b/tasks/dasyn_260630_00226/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00226/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00226/tests/grade.json b/tasks/dasyn_260630_00226/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..ac098e5b1764d2e7f7f93ff7ad5dcc35d50ef4e4 --- /dev/null +++ b/tasks/dasyn_260630_00226/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a bold static campaign-style travel landing page for a fictional mayor candidate named Sofia Reyes promoting the plan “Travel Forward 2026” for better tourism, local transport, and visitor-friendly city experiences. Use only vanilla HTML, CSS, and JavaScript, no backend and no external APIs. Visual direction: inspired by Xiaohongshu layouts with bright editorial cards, bold headlines, sticker-like badges, short travel notes, warm red/pink accents, and mobile-first social feed energy. Sections needed: Hero with headline “A City Worth Visiting, A City Worth Living In”, candidate photo placeholder, CTA buttons “See the Plan” and “Join the Tour”; Travel Promise cards for safer streets, cleaner landmarks, night markets, and easier airport connections; Xiaohongshu-style itinerary feed with 6 mock posts showing local spots and campaign notes; simple timeline for 100-day tourism plan; volunteer/travel ambassador signup block as a static form only; quote/testimonial cards from fictional residents; final call-to-action. Make it responsive, clean, and polished with sample placeholder images/content only. Include simple interactions like tab switching for plan categories, smooth scroll, and a mobile menu." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00226/tests/grade.py b/tasks/dasyn_260630_00226/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00226/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00226/tests/test.sh b/tasks/dasyn_260630_00226/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00226/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00226/tests/webdev/__init__.py b/tasks/dasyn_260630_00226/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00226/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00226/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00226/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00226/tests/webdev/shot.py b/tasks/dasyn_260630_00226/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00226/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00226/tests/webdev/verdict.py b/tasks/dasyn_260630_00226/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00226/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00227/environment/Dockerfile b/tasks/dasyn_260630_00227/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00227/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00227/environment/setup/setup.sh b/tasks/dasyn_260630_00227/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00227/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00227/tests/grade.py b/tasks/dasyn_260630_00227/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00227/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00227/tests/webdev/__init__.py b/tasks/dasyn_260630_00227/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00227/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00227/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00227/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00227/tests/webdev/shot.py b/tasks/dasyn_260630_00227/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00227/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00227/tests/webdev/verdict.py b/tasks/dasyn_260630_00227/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00227/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00228/environment/Dockerfile b/tasks/dasyn_260630_00228/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00228/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00228/environment/setup/setup.sh b/tasks/dasyn_260630_00228/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00228/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00228/tests/grade.json b/tasks/dasyn_260630_00228/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..5a8665cf3986eff9d35f2a10628e42d00a8383e6 --- /dev/null +++ b/tasks/dasyn_260630_00228/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "build me a static website for an insurance review and documentation hub, kind of like if Netflix made a brutalist guide for comparing insurance companies but absolutely no backend or logins or live data, just a really polished front end with mock/sample content. I want it to feel like a serious review site mixed with docs, where people can browse sections like auto insurance, health insurance, home insurance, travel insurance, life insurance, renters insurance, and small business insurance, with each category having static review cards, rating breakdowns, policy explainer pages, glossary entries, fake editor notes, comparison tables, and clear disclaimers that everything is sample educational content. The visual direction should be brutalist but still premium: huge blocky typography, harsh black/white contrast, acid green or red accent color, chunky borders, oversized cards, editorial layouts, sticky side navigation, and Netflix-inspired horizontal rows like “Top Rated for Families”, “Budget Picks”, “Best Claim Experience”, “Newly Reviewed”, except these are all static cards not connected to any service. Add parallax interactions as the user scrolls, like big background words sliding at different speeds, rating panels drifting subtly, oversized quote blocks moving slower than the content, and a hero section with layered insurance documents moving on scroll, but keep it all simple front-end CSS/JS, no canvas, no 3D, no WebGL. The site should be complex and feel complete: home page, review listing page layout, sample company detail/review page, documentation/learn page, glossary page, methodology page, privacy/disclaimer page, and a style guide section showing components. Include filter-looking UI chips and tabs for insurance type, price range, claim score, coverage strength, etc but they can just be visual/static or simple client-side mock interactions, no database and no API. I want the homepage to open with a dramatic hero saying something like “Insurance reviews without the fine-print fog”, then a Netflix-like shelf layout of insurance providers with bold score badges, then a brutalist comparison matrix, then documentation blocks explaining premiums, deductibles, exclusions, claims, riders, and policy limits. Make the content realistic but invented, with fake company names and sample ratings. Needs to be fully responsive for mobile/tablet/desktop, accessible, fast, and easy to edit. Please create it as a static React site using local mock data only, no auth, no external APIs, no payments, no real quotes, no personal info forms, no server implementation. Add smooth scrolling/parallax, hover states, mobile nav, and enough realistic copy so it doesn't look empty." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00228/tests/grade.py b/tasks/dasyn_260630_00228/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00228/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00228/tests/test.sh b/tasks/dasyn_260630_00228/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00228/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00228/tests/webdev/__init__.py b/tasks/dasyn_260630_00228/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00228/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00228/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00228/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00228/tests/webdev/shot.py b/tasks/dasyn_260630_00228/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00228/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00228/tests/webdev/verdict.py b/tasks/dasyn_260630_00228/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00228/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00243/environment/Dockerfile b/tasks/dasyn_260630_00243/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00243/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00243/environment/setup/setup.sh b/tasks/dasyn_260630_00243/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00243/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00243/tests/grade.json b/tasks/dasyn_260630_00243/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..3bd426b8c862e9667418af5bc2eea197e6b58cfa --- /dev/null +++ b/tasks/dasyn_260630_00243/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Act as a senior Vue front-end designer and build a polished static portfolio website for a fintech agency called LedgerNorth Studio. I want an elegant premium look, not too flashy, with a sticky navigation bar that stays smooth on scroll and highlights sections like Work, Services, Process, Insights, and Contact. The site should present the agency like a trusted team that designs dashboards, payment flows, banking apps, and compliance-friendly fintech experiences. Use only static/mock content, sample case studies, placeholder metrics, fake client quotes, and local component data, no backend, no login, no live API, no database. I like the way Reddit pages make content easy to scan with cards, votes/comments style metadata, and clear threaded sections, so borrow that feeling lightly for the case study and insight cards, but keep the visual style elegant and agency-grade. Include a strong hero, featured projects, service cards, process timeline, team credibility section, testimonial strip, FAQ, and a refined contact CTA. Make it responsive for desktop and mobile, with tasteful animations, clean spacing, accessible contrast, and production-quality component structure." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00243/tests/grade.py b/tasks/dasyn_260630_00243/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00243/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00243/tests/test.sh b/tasks/dasyn_260630_00243/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00243/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00243/tests/webdev/__init__.py b/tasks/dasyn_260630_00243/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00243/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00243/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00243/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00243/tests/webdev/shot.py b/tasks/dasyn_260630_00243/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00243/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00243/tests/webdev/verdict.py b/tasks/dasyn_260630_00243/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00243/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00272/environment/Dockerfile b/tasks/dasyn_260630_00272/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00272/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00272/environment/setup/setup.sh b/tasks/dasyn_260630_00272/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00272/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00272/tests/grade.json b/tasks/dasyn_260630_00272/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..ca7a49dfdb6e7f758e3fcfc4223f70764b07a283 --- /dev/null +++ b/tasks/dasyn_260630_00272/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "create a modern Vercel like static React website for my yoga studio campaign, like a political launch page showing memberships, class packs and merch products with a search bar, bold sections, mock content only no backend" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00272/tests/grade.py b/tasks/dasyn_260630_00272/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00272/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00272/tests/test.sh b/tasks/dasyn_260630_00272/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00272/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00272/tests/webdev/__init__.py b/tasks/dasyn_260630_00272/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00272/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00272/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00272/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00272/tests/webdev/shot.py b/tasks/dasyn_260630_00272/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00272/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00272/tests/webdev/verdict.py b/tasks/dasyn_260630_00272/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00272/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00275/environment/Dockerfile b/tasks/dasyn_260630_00275/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00275/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00275/environment/setup/setup.sh b/tasks/dasyn_260630_00275/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00275/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00275/tests/grade.json b/tasks/dasyn_260630_00275/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..9bfd366a5b47d4406b6af076b245a0bb778fe2d8 --- /dev/null +++ b/tasks/dasyn_260630_00275/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create an elegant animated portfolio website for me as an edtech product designer / learning experience designer. I want it to feel like a polished personal portfolio, not a startup landing page, but still modern and trustworthy enough for schools, bootcamps, and education companies. Please build it as a static React site with GSAP animations only, no backend, no login, no database, no API calls, and no live data. Static/mock content is totally fine. The overall vibe should be premium, calm, academic, and slightly editorial, with a soft off-white background, deep navy text, muted teal or blue accents, thin borders, subtle shadows, and lots of whitespace. I want the layout to be medium complexity: impressive but not overloaded. Use GitHub as a visual reference in a tasteful way, like a small contribution-style activity grid, project cards that feel a little like repository cards, clean metadata chips, and maybe a pinned-project section, but do not actually connect to GitHub or fetch anything. The site should have a hero section with my name, title, short intro, CTA buttons, and a smooth animated headline. Add an about section explaining my focus on digital learning platforms, curriculum UX, accessibility, and student engagement. Add a featured projects section with 4 static case studies such as an online course dashboard redesign, a language learning mobile concept, a teacher analytics interface, and a virtual classroom onboarding flow. Each project card should include role, tools, outcome, and a fake repo-style tag list. Add a skills section grouped into UX research, product strategy, UI systems, edtech knowledge, and front-end basics. Add a GitHub-inspired learning lab section with a static contribution graph showing consistent practice or design experiments, plus small notes like prototypes, audits, design systems, and accessibility reviews. Add a testimonials or recommendations section with 3 elegant quote cards using fictional text. Add a contact section with email text, social links as static anchors, and a simple visual resume download button that does not need to actually download anything unless it is just a placeholder. Please include smooth GSAP scroll reveals, staggered card animations, subtle parallax on decorative shapes, hover animations on cards/buttons, and a refined page-load entrance. Keep it fully responsive for desktop, tablet, and mobile. I do not need any real integrations, forms can be decorative only, and all content/images can be placeholders or CSS-based graphics. Please make it clean, accessible, and portfolio-ready." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00275/tests/grade.py b/tasks/dasyn_260630_00275/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00275/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00275/tests/test.sh b/tasks/dasyn_260630_00275/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00275/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00275/tests/webdev/__init__.py b/tasks/dasyn_260630_00275/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00275/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00275/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00275/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00275/tests/webdev/shot.py b/tasks/dasyn_260630_00275/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00275/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00275/tests/webdev/verdict.py b/tasks/dasyn_260630_00275/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00275/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00281/environment/Dockerfile b/tasks/dasyn_260630_00281/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00281/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00281/environment/setup/setup.sh b/tasks/dasyn_260630_00281/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00281/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00281/tests/grade.json b/tasks/dasyn_260630_00281/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..759013b8528c89996b2de6a54a5a753166a05275 --- /dev/null +++ b/tasks/dasyn_260630_00281/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "اريد تصميم صفحة هبوط ثابتة لماركت بليس لخدمات رعاية كبار السن، الفكرة مثل واجهة Bilibili من ناحية ترتيب البطاقات والأقسام الكثيرة لكن بأسلوب سويس نظيف: خطوط واضحة، شبكة منظمة، مساحات بيضاء، عناوين قوية وألوان هادئة تناسب المجال الصحي. الصفحة تعرض مقدمة عن المنصة، بطاقات لمقدمي الرعاية، خدمات مثل مرافقة يومية وتمريض منزلي وجلسات علاج طبيعي، قسم تقييمات وهمية، باقات أسعار، وأسئلة شائعة. أريد استخدام بيانات تجريبية فقط بدون تسجيل دخول أو قاعدة بيانات أو API. مهم يكون فيه lazy loading للصور والبطاقات عند النزول في الصفحة، مع تصميم responsive للموبايل والتابلت. خليه يبدو موثوق واحترافي ومناسب لأهالي يبحثون عن رعاية آمنة لكبار السن." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00281/tests/grade.py b/tasks/dasyn_260630_00281/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00281/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00281/tests/test.sh b/tasks/dasyn_260630_00281/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00281/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00281/tests/webdev/__init__.py b/tasks/dasyn_260630_00281/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00281/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00281/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00281/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00281/tests/webdev/shot.py b/tasks/dasyn_260630_00281/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00281/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00281/tests/webdev/verdict.py b/tasks/dasyn_260630_00281/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00281/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00286/environment/Dockerfile b/tasks/dasyn_260630_00286/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00286/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00286/environment/setup/setup.sh b/tasks/dasyn_260630_00286/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00286/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00286/tests/grade.json b/tasks/dasyn_260630_00286/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..68ffca3b91aee0210676d20c5e4d9621bb9c8cf9 --- /dev/null +++ b/tasks/dasyn_260630_00286/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build a static Astro website for an eco community restaurant called Verde Commons. Style: elegant art-deco mixed with modern sustainability, inspired by Instagram carousel visuals and story highlight cards, but no live Instagram feed. Use mock/static content only. Pages/sections: HERO with headline “Farm-to-Table Dining for a Greener Neighborhood”, gold + emerald art-deco patterns, CTA buttons Reserve a Table and View Menu (buttons can just link to sections). Scroll-driven experience: as user scrolls, reveal menu cards, community impact stats, vertical timeline of local farms, sticky ingredient spotlight, and parallax deco frames. Sections needed: About the community kitchen, Seasonal Menu, Weekend Brunch, Local Producers, Zero-Waste Practices, Events Calendar, Instagram-style Gallery Grid with fake captions, Testimonials, Location + Opening Hours, Footer. Visual direction: deep forest green, cream, muted gold, black accents, geometric borders, arched cards, premium restaurant photography placeholders, subtle grain texture, mobile responsive. Make it feel complex and polished with animations, sticky nav, section anchors, decorative badges, and accessible typography. No backend, no API, no database, no booking system functionality, only static front-end." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00286/tests/grade.py b/tasks/dasyn_260630_00286/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00286/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00286/tests/test.sh b/tasks/dasyn_260630_00286/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00286/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00286/tests/webdev/__init__.py b/tasks/dasyn_260630_00286/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00286/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00286/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00286/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00286/tests/webdev/shot.py b/tasks/dasyn_260630_00286/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00286/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00286/tests/webdev/verdict.py b/tasks/dasyn_260630_00286/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00286/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00288/environment/Dockerfile b/tasks/dasyn_260630_00288/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00288/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00288/environment/setup/setup.sh b/tasks/dasyn_260630_00288/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00288/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00288/tests/grade.json b/tasks/dasyn_260630_00288/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..659f2c7d2e4866ba9498e6b7ad2c3597b2fedf5f --- /dev/null +++ b/tasks/dasyn_260630_00288/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a static React + Tailwind website for a hair salon, classic wiki style but polished like Linear. It should showcase services/products with mock content, include category pages, comparison cards, and a drag-and-drop section where visitors can arrange their ideal treatment package. No backend, just static front end." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00288/tests/grade.py b/tasks/dasyn_260630_00288/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00288/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00288/tests/test.sh b/tasks/dasyn_260630_00288/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00288/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00288/tests/webdev/__init__.py b/tasks/dasyn_260630_00288/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00288/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00288/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00288/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00288/tests/webdev/shot.py b/tasks/dasyn_260630_00288/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00288/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00288/tests/webdev/verdict.py b/tasks/dasyn_260630_00288/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00288/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00415/environment/Dockerfile b/tasks/dasyn_260630_00415/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00415/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00415/environment/setup/setup.sh b/tasks/dasyn_260630_00415/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00415/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00415/tests/grade.json b/tasks/dasyn_260630_00415/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..9eee064215da3c39938d952519703ac367a2e002 --- /dev/null +++ b/tasks/dasyn_260630_00415/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "أنشئ موقع إخباري عقاري ثابت بالكامل باستخدام Nuxt، الفكرة مثل Airbnb لكن بدل الحجز يكون بوابة أخبار وتحليلات عن العقارات والمناطق السكنية. المطلوب تصميم Cyberpunk واضح: خلفية داكنة، ألوان نيون بنفسجي/أزرق/وردي، بطاقات زجاجية، خطوط حديثة، glow effects، واجهة فاخرة وسهلة. الموقع عربي RTL بالكامل. الصفحات/الأقسام: الصفحة الرئيسية مع Hero كبير بعنوان \"رادار العقار 2026\" وزر CTA، شريط أخبار عاجلة ثابت بمحتوى وهمي، قسم أخبار السوق، قسم أحياء مرشحة للسكن، قسم مقارنات أسعار، قسم مقالات رأي، وقسم Newsletter شكلي فقط بدون إرسال. أريد كروت أخبار تشبه كروت Airbnb من ناحية الصورة الكبيرة، السعر/المؤشر، الموقع، التقييم أو badge، لكن المحتوى يكون عقاري إخباري مثل: ارتفاع أسعار الشقق في الرياض، أفضل مناطق الاستثمار، تحليل الإيجارات، مشاريع جديدة. استخدم بيانات static/mock داخل الكود فقط، لا API ولا backend ولا قاعدة بيانات ولا تسجيل دخول. التفاعل المطلوب بسيط: خاصية drag-and-drop لإعادة ترتيب كروت الأخبار أو كروت الأحياء داخل قسم \"رتّب أولوياتك\"، وكل شيء يعمل في المتصفح فقط بدون حفظ حقيقي. أضف فلاتر شكلية تعمل محلياً مثل المدينة، نوع الخبر، مستوى السعر، لكن كلها من بيانات ثابتة. يجب أن يكون الموقع responsive للموبايل والتابلت، مع navbar، search bar شكلي، footer، تأثيرات hover، انتقالات ناعمة، وحالة empty إذا لم تظهر نتائج. لا تستخدم 3D أو WebGL أو Canvas. المطلوب تسليم واجهة static site فقط قابلة للتشغيل بدون أي خدمات خارجية، مع تنظيم المكونات في Nuxt وتصميم نظيف قريب من مواقع editorial/news الحديثة مع لمسة Airbnb cyberpunk." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00415/tests/grade.py b/tasks/dasyn_260630_00415/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00415/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00415/tests/test.sh b/tasks/dasyn_260630_00415/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00415/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00415/tests/webdev/__init__.py b/tasks/dasyn_260630_00415/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00415/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00415/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00415/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00415/tests/webdev/shot.py b/tasks/dasyn_260630_00415/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00415/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00415/tests/webdev/verdict.py b/tasks/dasyn_260630_00415/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00415/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00423/environment/Dockerfile b/tasks/dasyn_260630_00423/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00423/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00423/environment/setup/setup.sh b/tasks/dasyn_260630_00423/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00423/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00423/tests/grade.json b/tasks/dasyn_260630_00423/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..ff927863e8002737b3fb7ae458a79dc66299de27 --- /dev/null +++ b/tasks/dasyn_260630_00423/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "اريد تصميم موقع ثابت بـ Next.js لكن بدون باكند او تسجيل دخول، يكون كأنه صفحة تحريرية دافئة لكنيسة محلية هدفها جذب المتطوعين والموظفين الجدد للخدمة. الصفحة الرئيسية فيها فيديو خلفية هادئ في الهيرو عن المجتمع والخدمة مع طبقة لون دافئة ونص واضح ودعوة للتقديم. اريد الاقسام مرتبة مثل Reddit من ناحية وجود بطاقات منشورات وتعليقات مختصرة وشارات للتصنيفات، لكن التصميم يكون راقي وكنسي وليس نسخة مباشرة. المحتوى يكون عينات ثابتة فقط: قصص خدام، فرص تطوع، وظائف مفتوحة، اسئلة شائعة، جدول فعاليات تعارف، واقتباسات من أعضاء الكنيسة. اضف فلاتر شكلية للتصنيفات وروابط تنقل وسلايدر بسيط او تبويبات، كلها تعمل بالواجهة فقط. المهم يكون responsive، سريع، ومناسب كموقع static editorial recruitment للكنيسة مع ألوان دافئة وصور/فيديوهات placeholder." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00423/tests/grade.py b/tasks/dasyn_260630_00423/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00423/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00423/tests/test.sh b/tasks/dasyn_260630_00423/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00423/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00423/tests/webdev/__init__.py b/tasks/dasyn_260630_00423/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00423/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00423/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00423/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00423/tests/webdev/shot.py b/tasks/dasyn_260630_00423/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00423/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00423/tests/webdev/verdict.py b/tasks/dasyn_260630_00423/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00423/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00424/environment/Dockerfile b/tasks/dasyn_260630_00424/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00424/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00424/environment/setup/setup.sh b/tasks/dasyn_260630_00424/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00424/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00424/tests/grade.json b/tasks/dasyn_260630_00424/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..353d28cc540e59f44740419f493f45227c113b8f --- /dev/null +++ b/tasks/dasyn_260630_00424/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "اعمل لي موقع ثابت بس بـ SvelteKit لاستوديو يوغا فيه عرض باقات حجز ريتريت كأنها فندق، تصميم نظيف مستوحى من انستغرام، مع ناف بار ثابت وصور وكروت وأسعار ومحتوى وهمي بدون تسجيل او باك اند" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00424/tests/grade.py b/tasks/dasyn_260630_00424/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00424/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00424/tests/test.sh b/tasks/dasyn_260630_00424/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00424/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00424/tests/webdev/__init__.py b/tasks/dasyn_260630_00424/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00424/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00424/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00424/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00424/tests/webdev/shot.py b/tasks/dasyn_260630_00424/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00424/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00424/tests/webdev/verdict.py b/tasks/dasyn_260630_00424/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00424/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00441/environment/Dockerfile b/tasks/dasyn_260630_00441/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00441/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00441/environment/setup/setup.sh b/tasks/dasyn_260630_00441/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00441/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00441/tests/grade.json b/tasks/dasyn_260630_00441/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..97ee28a905918876d137cb950254d0b0ceeeb126 --- /dev/null +++ b/tasks/dasyn_260630_00441/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a modern responsive landing page for a finance crowdfunding platform called FundNest. It should feel like a soft neomorphism version of Twitter: clean feed-inspired cards, rounded pill buttons, floating action-style CTA, profile-style campaign previews, subtle blue accents, lots of white/very light gray surfaces and soft shadows. This is only a static marketing website, so use mock/static campaign data and placeholder images, no backend or real payments. Sections needed: 1) Hero section with headline “Invest in ideas before they become the future”, short subtitle, animated stats cards, and CTA buttons “Explore Campaigns” and “Start a Fundraiser”. 2) Social proof strip with sample investor counts, funded amount, and success rate. 3) Featured Campaigns section showing 4 crowdfunding finance cards like clean energy bond, women-led startup fund, local business loan pool, and education microfund. Cards should include mock funding progress, target amount, days left, category tags, and a small creator avatar/name. 4) How It Works section with 3 steps: Discover, Back, Track Impact. 5) Live Activity style area inspired by Twitter timeline but static, with small animated posts such as “Aarav backed GreenGrid with $250” and “CivicFund reached 82% funded”. 6) Trust and Security section with finance-friendly content about transparent milestones, risk notes, community validation, and encrypted payments, but keep it visual not text-heavy. 7) Testimonials in tweet-style bubbles. 8) Pricing or platform fee section with simple cards. 9) FAQ section. 10) Footer with navigation, newsletter mock input, and legal links. Visual style: neomorphic soft raised panels, inset progress bars, subtle glassy highlights, rounded corners, calming finance palette of ice white, slate, sky blue, mint green, and a little graphite. Add tasteful animations: hero cards float slowly, progress bars fill on load, timeline items slide in, CTA hover bounce/glow, counters can be static-looking animated numbers if easy. Must be mobile friendly, polished, accessible, and work as a static front-end page without APIs, login, database, or external services." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00441/tests/grade.py b/tasks/dasyn_260630_00441/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00441/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00441/tests/test.sh b/tasks/dasyn_260630_00441/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00441/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00441/tests/webdev/__init__.py b/tasks/dasyn_260630_00441/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00441/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00441/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00441/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00441/tests/webdev/shot.py b/tasks/dasyn_260630_00441/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00441/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00441/tests/webdev/verdict.py b/tasks/dasyn_260630_00441/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00441/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00448/environment/Dockerfile b/tasks/dasyn_260630_00448/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00448/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00448/environment/setup/setup.sh b/tasks/dasyn_260630_00448/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00448/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00448/tests/grade.json b/tasks/dasyn_260630_00448/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..af3a6bc3d929d147136a7f9fa7dabe20786c2c61 --- /dev/null +++ b/tasks/dasyn_260630_00448/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "I need a clean elegant SvelteKit static website for a fictional dental themed restaurant / cafe called Enamel Table, basically a product showcase for their tooth friendly menu items and private dining packages. Make it feel premium and calm, not childish, with ivory, soft mint, charcoal, subtle gold accents, nice typography, and polished spacing. The home page should have a hero, short brand story, featured menu/product cards, chef dentist approved concept section, reservation callout that is just a visual button/link and not a working backend form, testimonials, FAQ, and footer. I want the product/menu showcase to be simple static sample content only, like whitening-friendly brunch, low sugar dessert flight, herbal drinks, kids smile menu, etc. Please add tasteful cursor effects, like a small custom cursor dot or soft glow that reacts on hover over cards/buttons, but keep it lightweight and accessible and don’t use canvas or 3D. For the content layout, take some inspiration from Reddit in the sense of stacked discussion/card posts, upvote-style little badges, comment-preview style testimonial cards, and clear nested sections, but make it look like a luxury restaurant website, not an actual Reddit clone. No login, no API, no database, no search service, no external live data, just a static front-end that can render by itself with mock copy and placeholder images/gradients. Keep the site simple but complete, responsive for mobile and desktop, with smooth hover states and basic page transitions if easy." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00448/tests/grade.py b/tasks/dasyn_260630_00448/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00448/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00448/tests/test.sh b/tasks/dasyn_260630_00448/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00448/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00448/tests/webdev/__init__.py b/tasks/dasyn_260630_00448/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00448/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00448/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00448/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00448/tests/webdev/shot.py b/tasks/dasyn_260630_00448/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00448/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00448/tests/webdev/verdict.py b/tasks/dasyn_260630_00448/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00448/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00470/environment/Dockerfile b/tasks/dasyn_260630_00470/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00470/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00470/environment/setup/setup.sh b/tasks/dasyn_260630_00470/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00470/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00470/tests/grade.json b/tasks/dasyn_260630_00470/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..c30aaee45f0c784848f022b0cc7bca1c7dddc85c --- /dev/null +++ b/tasks/dasyn_260630_00470/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a classic ProductHunt-style static website in Astro for a restaurant recruitment job board called \"TableShift Jobs\". It should feel like a polished launch page plus curated job-board for restaurants hiring chefs, servers, baristas, hosts, and managers. Pages/sections: Home hero with headline \"Find Your Next Restaurant Role\", featured job cards, category filters UI only, top hiring restaurants, how it works, candidate benefits, employer benefits, testimonials, pricing cards for job posts, FAQ, and contact CTA. Use warm cream, deep navy, tomato red, and brass accents with vintage restaurant typography but modern clean spacing. Include mock/static job listings only, no backend or real applications. Add a small confetti celebration interaction when someone clicks \"Save Job\" or \"Apply Now\" buttons, purely front-end. Make it fully responsive with reusable Astro components and sample content." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00470/tests/grade.py b/tasks/dasyn_260630_00470/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00470/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00470/tests/test.sh b/tasks/dasyn_260630_00470/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00470/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00470/tests/webdev/__init__.py b/tasks/dasyn_260630_00470/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00470/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00470/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00470/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00470/tests/webdev/shot.py b/tasks/dasyn_260630_00470/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00470/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00470/tests/webdev/verdict.py b/tasks/dasyn_260630_00470/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00470/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00471/environment/Dockerfile b/tasks/dasyn_260630_00471/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00471/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00471/environment/setup/setup.sh b/tasks/dasyn_260630_00471/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00471/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00471/tests/grade.json b/tasks/dasyn_260630_00471/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..c9b99aef5f35fdceafadcffdfe8b396374ccc886 --- /dev/null +++ b/tasks/dasyn_260630_00471/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Prompt: Create an elegant, calming, fully responsive static editorial landing page in SvelteKit for a mental-health publication called \"Quiet Harbor Journal\". The site should feel inspired by the clean polish and spacing of Vercel-style websites, but softer and more human. This is a pure static front-end site only, no backend, no database, no login, no appointments, no real APIs, no external services. Use mock/sample editorial content and local/static data only.\n\nWebsite Goal: Build a soothing landing page for a mental-health editorial site that helps visitors discover thoughtful articles, guided reflections, and gentle resources about stress, anxiety, burnout, sleep, relationships, and emotional resilience. The visual style should be elegant, minimal, premium, warm, and trustworthy, not clinical or corporate.\n\nTech Requirements:\n- Use SvelteKit.\n- Static render friendly, suitable for deploy on Vercel as a static site.\n- No server-side features required.\n- No authentication, no forms that actually submit anywhere, no CMS, no API calls.\n- Content can be hardcoded in components or static arrays.\n- Keep complexity simple but polished.\n- Responsive for desktop, tablet, and mobile.\n\nMain Interaction Requirement:\n- Implement an infinite-scroll style editorial feed on the landing page using static mock article data. It does not need to fetch anything from a server. You can simulate loading more posts from a local array when the user reaches near the bottom.\n- Include a small elegant loading indicator or \"unfolding more stories\" transition.\n- If all sample posts are shown, display a calm ending message like \"You’ve reached the quiet end for now. Take a breath.\"\n\nVisual Direction:\n- Soft ivory / warm white background.\n- Muted sage, deep navy, dusty lavender, and gentle sand tones.\n- Large whitespace, refined typography, subtle borders, soft shadows.\n- Editorial magazine feeling with premium landing page polish.\n- Use rounded cards, pill tags, quiet gradients, and subtle hover states.\n- Avoid loud wellness clichés. No neon colors, no clutter.\n\nPage Structure:\n1. Header / Navbar\n- Left: Quiet Harbor Journal logo text with a small abstract mark.\n- Center/right nav links: Essays, Guides, Reflections, Sleep, Burnout, About.\n- Button-style link: Start Reading.\n- Sticky or floating glass-like navbar is okay, but keep it elegant.\n\n2. Hero Section\n- Small eyebrow text: Independent Mental Health Editorial\n- Main headline: \"Gentle writing for heavy days.\"\n- Subheadline: \"Quiet Harbor Journal publishes thoughtful essays, practical guides, and reflective prompts for navigating stress, burnout, anxiety, and everyday emotional life.\"\n- Two CTA buttons: \"Read Latest Essays\" and \"Explore Reflection Prompts\"\n- Right side visual: an elegant editorial feature card stack, not a real image requirement. Use CSS cards with article titles, tags, reading time, and a soft gradient background.\n- Include tiny trust indicators such as: Evidence-informed tone, No judgment, 5-minute reads, Static sample publication.\n\n3. Featured Editorial Strip\n- 3 highlighted cards:\n - \"When Rest Feels Unproductive\"\n - \"A Softer Way to Name Anxiety\"\n - \"The Evening Ritual That Helps You Unclench\"\n- Each card should show category, title, short excerpt, reading time, and author placeholder.\n\n4. Mission / Intro Section\n- Title: \"Mental health writing that leaves room for nuance.\"\n- Paragraph explaining the publication approach: warm, practical, non-alarmist, reflective, careful language.\n- Include 4 small values cards: Compassion, Clarity, Boundaries, Slow Attention.\n\n5. Topic Navigation\n- Horizontal or grid category pills: Stress, Anxiety, Sleep, Burnout, Relationships, Self-Compassion, Work-Life, Reflection Prompts.\n- These do not need to filter unless easy; visual interaction is enough.\n\n6. Infinite Editorial Feed\n- Section title: \"Latest Quiet Reads\"\n- Build a clean article feed with cards.\n- Use at least 18 mock article items in static data, initially show maybe 6, then reveal more as the user scrolls.\n- Article card design should include: category tag, title, excerpt, author name, date, read time, and small decorative accent.\n- Example article themes: nervous system reset, loneliness after success, Sunday anxiety, saying no without guilt, mindful phone boundaries, sleep after overthinking, burnout recovery, gentle productivity, grief anniversaries, emotional check-ins.\n- No real medical claims. Add a small disclaimer somewhere that content is educational/editorial and not a substitute for professional care.\n\n7. Reflection Prompt Band\n- A calm full-width section with 3 prompt cards:\n - \"What felt heavier than it looked today?\"\n - \"Where did you protect your peace this week?\"\n - \"What would support look like if it were simple?\"\n- Include a button-like link: \"Browse More Prompts\" but it can be non-functional/static.\n\n8. Newsletter Style Static Block\n- Create a beautiful newsletter signup-looking section, but do not connect it to anything.\n- Text: \"A quieter inbox, once a week.\"\n- Input and button may be present visually only; button can do nothing or show a small static note like \"Demo only\".\n- Make clear this is a static demo if needed.\n\n9. Footer\n- Columns: Journal, Topics, Resources, Note.\n- Include links as static placeholders.\n- Include disclaimer: \"Quiet Harbor Journal is an editorial wellness concept. It does not provide diagnosis, treatment, crisis support, or medical advice.\"\n- Add copyright line for 2026.\n\nComponents / Implementation Suggestions:\n- Use Svelte components for Navbar, Hero, FeaturedCards, TopicPills, ArticleFeed, PromptSection, Footer if convenient.\n- Use CSS variables for theme colors.\n- Smooth scroll behavior.\n- Elegant reveal animations using CSS only or simple Svelte transitions.\n- Accessible contrast and semantic HTML.\n- Keyboard-friendly buttons/links.\n- Keep it lightweight and static.\n\nDeliverable: A polished SvelteKit static landing page that looks like a premium mental-health editorial website, with an elegant Vercel-inspired layout, calm visuals, simple static content, and an infinite-scroll article feed powered only by local mock data." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00471/tests/grade.py b/tasks/dasyn_260630_00471/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00471/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00471/tests/test.sh b/tasks/dasyn_260630_00471/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00471/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00471/tests/webdev/__init__.py b/tasks/dasyn_260630_00471/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00471/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00471/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00471/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00471/tests/webdev/shot.py b/tasks/dasyn_260630_00471/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00471/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00471/tests/webdev/verdict.py b/tasks/dasyn_260630_00471/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00471/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00477/environment/Dockerfile b/tasks/dasyn_260630_00477/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00477/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00477/environment/setup/setup.sh b/tasks/dasyn_260630_00477/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00477/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00477/tests/grade.json b/tasks/dasyn_260630_00477/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..1b7480fe95bafafddcd3141d56d7bdd799624d4d --- /dev/null +++ b/tasks/dasyn_260630_00477/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Design a minimalist salon startup event website for a Medium-style launch night, built as a static SvelteKit landing page with drag-and-drop section blocks so I can rearrange the hero, schedule, speakers, gallery, FAQs, and RSVP call-to-action. Use mock content only, make it feel premium and modern, and keep it fully static with no backend or login." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00477/tests/grade.py b/tasks/dasyn_260630_00477/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00477/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00477/tests/test.sh b/tasks/dasyn_260630_00477/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00477/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00477/tests/webdev/__init__.py b/tasks/dasyn_260630_00477/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00477/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00477/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00477/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00477/tests/webdev/shot.py b/tasks/dasyn_260630_00477/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00477/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00477/tests/webdev/verdict.py b/tasks/dasyn_260630_00477/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00477/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00483/environment/Dockerfile b/tasks/dasyn_260630_00483/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00483/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00483/environment/setup/setup.sh b/tasks/dasyn_260630_00483/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00483/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00483/tests/grade.json b/tasks/dasyn_260630_00483/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..9b4d1c9f6d19142659e3a4def246828813a8aab1 --- /dev/null +++ b/tasks/dasyn_260630_00483/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "أريد تصميم وتنفيذ موقع بورتفوليو ثابت لمدرب/مدربة لياقة باسم FitFrame Gallery باستخدام Vue فقط (صفحة واحدة أو عدة أقسام داخل نفس الصفحة) بدون باكند وبدون تسجيل دخول وبدون API. المطلوب ستايل فاتح clean modern، كأنه معرض أعمال Fitness Gallery يعرض صور وتمارين ونتائج عملاء بشكل مرتب. الإلهام يكون من Reddit في فكرة البطاقات، التصويت/التفاعل الوهمي، التعليقات المختصرة داخل الكروت، وترتيب المحتوى مثل feed لكن بشكل احترافي وليس نسخة حرفية. المحتوى كله static/mock data عادي. الأقسام المطلوبة: Sticky Navbar ثابت بالأعلى فيه الشعار وروابط Home / Gallery / Programs / Transformations / Reviews / Contact مع active state عند المرور أو الضغط. Hero section بخلفية فاتحة مع gradient ناعم، عنوان قوي: Transform Your Body With Smart Fitness Coaching، وصف قصير، أزرار CTA مثل View Gallery وStart Plan، وعلى اليمين بطاقة كبيرة فيها إحصائيات وهمية مثل 120+ transformations و8 years coaching و4.9 rating. بعد ذلك قسم Gallery Grid يعرض كروت تمارين fitness مثل Strength Training, Mobility, HIIT, Core, Nutrition Prep, Outdoor Running، كل كرت يحتوي صورة placeholder أو gradient، tag، عنوان، وصف قصير، upvotes وهمية مثل Reddit، comments count، وbadge مثل Beginner / Advanced. أريد فلاتر ثابتة في الأعلى All / Strength / Cardio / Mobility / Nutrition تعمل بالـ Vue state بدون API. قسم Programs يكون 3 باقات تدريب: Starter, Performance, Elite مع الأسعار الوهمية والمميزات. قسم Transformations يكون before/after cards بشكل أنيق بدون صور حقيقية ضروري استخدم placeholders، مع timeline صغير. قسم Reviews يكون كروت آراء تشبه منشورات Reddit خفيفة: اسم العميل، مدة التدريب، نجوم، تعليق، وعدد upvotes. قسم Coach Profile يعرض صورة/placeholder وسيرة قصيرة وشهادات. قسم FAQ بسيط accordion يعمل محلياً. Footer فيه روابط اجتماعية وهمية ونص حقوق. مهم جداً الموقع responsive للموبايل والتابلت، sticky nav لا يغطي المحتوى، ألوان light: أبيض، رمادي فاتح، أخضر/ليموني كaccent، ظلال ناعمة، border radius كبير، micro animations hover، smooth scrolling. لا تستخدم أي خدمات خارجية ولا بيانات حقيقية، كل شيء داخل ملفات Vue/static. أريد كود منظم بمكونات واضحة قدر الإمكان، وتصميم premium portfolio/gallery وليس dashboard ثقيل." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00483/tests/grade.py b/tasks/dasyn_260630_00483/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00483/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00483/tests/test.sh b/tasks/dasyn_260630_00483/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00483/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00483/tests/webdev/__init__.py b/tasks/dasyn_260630_00483/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00483/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00483/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00483/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00483/tests/webdev/shot.py b/tasks/dasyn_260630_00483/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00483/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00483/tests/webdev/verdict.py b/tasks/dasyn_260630_00483/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00483/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00484/environment/Dockerfile b/tasks/dasyn_260630_00484/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00484/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00484/environment/setup/setup.sh b/tasks/dasyn_260630_00484/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00484/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00484/tests/grade.json b/tasks/dasyn_260630_00484/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..1dd6b4fe140a7ac10b8c8c79b22be4cb23a9dabb --- /dev/null +++ b/tasks/dasyn_260630_00484/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "build me a static retro documentation website for a wedding publishing guide, like a stylish TikTok inspired mini docs hub for couples making invites, vows, programs and photo books. make it look polished with playful cursor effects, sample/static content only, no backend or login, responsive simple UI but with lots of sections, tabs, cards, timelines and copy examples." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00484/tests/grade.py b/tasks/dasyn_260630_00484/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00484/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00484/tests/test.sh b/tasks/dasyn_260630_00484/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00484/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00484/tests/webdev/__init__.py b/tasks/dasyn_260630_00484/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00484/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00484/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00484/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00484/tests/webdev/shot.py b/tasks/dasyn_260630_00484/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00484/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00484/tests/webdev/verdict.py b/tasks/dasyn_260630_00484/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00484/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00485/environment/Dockerfile b/tasks/dasyn_260630_00485/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00485/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00485/environment/setup/setup.sh b/tasks/dasyn_260630_00485/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00485/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00485/tests/grade.json b/tasks/dasyn_260630_00485/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..f08db8b5e705bbc4061bcca32bc8c7fe5158159a --- /dev/null +++ b/tasks/dasyn_260630_00485/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "luxury React Dribbble style moving company hotel-booking event landing page, static mock content only" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00485/tests/grade.py b/tasks/dasyn_260630_00485/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00485/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00485/tests/test.sh b/tasks/dasyn_260630_00485/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00485/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00485/tests/webdev/__init__.py b/tasks/dasyn_260630_00485/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00485/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00485/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00485/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00485/tests/webdev/shot.py b/tasks/dasyn_260630_00485/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00485/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00485/tests/webdev/verdict.py b/tasks/dasyn_260630_00485/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00485/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00611/environment/Dockerfile b/tasks/dasyn_260630_00611/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00611/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00611/environment/setup/setup.sh b/tasks/dasyn_260630_00611/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00611/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00611/tests/grade.json b/tasks/dasyn_260630_00611/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..34933a65e085a17bba8ca94270aff4fe481f3e14 --- /dev/null +++ b/tasks/dasyn_260630_00611/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "我想做一个静态的美妆品牌作品集/展示官网,用 Astro 搭建就行,不需要后台和登录,也不要接任何接口,内容先用假的产品和案例数据。整体感觉参考 Linear 那种干净高级的排版,扁平化设计,留白多一点,主色可以是奶油白、玫瑰粉和深灰。页面要像一个小型电商美妆品牌官网,有首页、精选产品区、护肤套装展示、品牌故事、用户评价、作品案例/妆容灵感、价格卡片和底部联系方式。希望滚动的时候有轻微 parallax 效果,比如背景色块、产品卡片和大图层有错位滚动,但不要太夸张,移动端也要顺滑。产品卡片可以展示口红、精华、面霜、香氛这些静态样品,按钮只是展示用比如“查看详情”“加入愿望清单”,不用真的购物车功能。请把组件结构做清楚,页面视觉要像能直接给客户看的中等复杂度官网。" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00611/tests/grade.py b/tasks/dasyn_260630_00611/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00611/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00611/tests/test.sh b/tasks/dasyn_260630_00611/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00611/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00611/tests/webdev/__init__.py b/tasks/dasyn_260630_00611/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00611/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00611/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00611/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00611/tests/webdev/shot.py b/tasks/dasyn_260630_00611/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00611/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00611/tests/webdev/verdict.py b/tasks/dasyn_260630_00611/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00611/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00616/environment/Dockerfile b/tasks/dasyn_260630_00616/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00616/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00616/environment/setup/setup.sh b/tasks/dasyn_260630_00616/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00616/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00616/tests/grade.json b/tasks/dasyn_260630_00616/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..b64c7975562529686f675ba9b90dd977beae6dab --- /dev/null +++ b/tasks/dasyn_260630_00616/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a simple corporate landing page for an agency marketplace showcase, with sticky nav, hero section, featured service cards, client logos, pricing blocks and contact CTA. Use only HTML CSS and vanilla JS, static sample content is fine." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00616/tests/grade.py b/tasks/dasyn_260630_00616/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00616/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00616/tests/test.sh b/tasks/dasyn_260630_00616/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00616/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00616/tests/webdev/__init__.py b/tasks/dasyn_260630_00616/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00616/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00616/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00616/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00616/tests/webdev/shot.py b/tasks/dasyn_260630_00616/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00616/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00616/tests/webdev/verdict.py b/tasks/dasyn_260630_00616/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00616/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00618/environment/Dockerfile b/tasks/dasyn_260630_00618/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00618/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00618/tests/webdev/__init__.py b/tasks/dasyn_260630_00618/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00618/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00618/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00618/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00618/tests/webdev/shot.py b/tasks/dasyn_260630_00618/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00618/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00618/tests/webdev/verdict.py b/tasks/dasyn_260630_00618/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00618/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00627/environment/Dockerfile b/tasks/dasyn_260630_00627/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00627/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00627/environment/setup/setup.sh b/tasks/dasyn_260630_00627/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00627/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00627/tests/grade.json b/tasks/dasyn_260630_00627/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..cff4abb5a532e7ca14f6a94f832486d8e7e73805 --- /dev/null +++ b/tasks/dasyn_260630_00627/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "اصمم لي موقع بورتفوليو/حملة انتخابية ثابت بالكامل لمرشح محلي اسمه سالم الراشد، فكرته أن حملته مركزة على تحسين أسطح ومنازل الأحياء بعد العواصف، بلمسة أنيقة وفاخرة مثل أسلوب Airbnb في الكروت والمساحات البيضاء. استخدم React مع Tailwind فقط، بدون باك اند أو تسجيل دخول أو API، كل البيانات تكون mock/static. المطلوب صفحة Landing واحدة تشمل: Hero كبير بعنوان \"أسقف آمنة.. أحياء أقوى\" مع CTA تبرع الآن / تعرف على البرنامج، قسم نبذة عن المرشح، بطاقات إنجازات في مجال roofing وخدمة المجتمع، برنامج الحملة في 3 محاور، معرض مشاريع قبل/بعد باستخدام صور placeholder مع lazy loading، شهادات سكان، جدول فعاليات ثابت، قسم أرقام مختصرة، وأسئلة شائعة + Footer. التصميم يكون responsive للموبايل، ألوان هادئة: أبيض، كحلي، ذهبي خفيف، مع ظلال ناعمة وزوايا مستديرة. أضف تأثيرات hover بسيطة و loading='lazy' للصور، ولا تستخدم أي خدمات خارجية." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00627/tests/grade.py b/tasks/dasyn_260630_00627/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00627/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00627/tests/test.sh b/tasks/dasyn_260630_00627/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00627/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00627/tests/webdev/__init__.py b/tasks/dasyn_260630_00627/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00627/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00627/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00627/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00627/tests/webdev/shot.py b/tasks/dasyn_260630_00627/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00627/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00627/tests/webdev/verdict.py b/tasks/dasyn_260630_00627/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00627/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00629/environment/Dockerfile b/tasks/dasyn_260630_00629/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00629/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00629/environment/setup/setup.sh b/tasks/dasyn_260630_00629/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00629/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00629/tests/grade.json b/tasks/dasyn_260630_00629/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..fa69fb6968e0566d7b2f5dcecfcb62b28338125f --- /dev/null +++ b/tasks/dasyn_260630_00629/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "temizlik hizmeti verenler için online kurs etkinliği tanıtım sitesi yap, dribbble tarzı swiss tasarım olsun, scroll ile bölümler hareketli aksın, program eğitmenler fiyatlar ve kayıt çağrısı statik örnek içerikle yeter" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00629/tests/grade.py b/tasks/dasyn_260630_00629/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00629/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00629/tests/test.sh b/tasks/dasyn_260630_00629/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00629/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00629/tests/webdev/__init__.py b/tasks/dasyn_260630_00629/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00629/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00629/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00629/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00629/tests/webdev/shot.py b/tasks/dasyn_260630_00629/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00629/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00629/tests/webdev/verdict.py b/tasks/dasyn_260630_00629/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00629/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00642/environment/Dockerfile b/tasks/dasyn_260630_00642/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00642/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00642/environment/setup/setup.sh b/tasks/dasyn_260630_00642/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00642/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00642/tests/grade.json b/tasks/dasyn_260630_00642/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..b35cd04dacd19e08ad99ec5c5edbf2884db93139 --- /dev/null +++ b/tasks/dasyn_260630_00642/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Act as a senior front-end designer and build a polished static marketing website for a premium social beauty platform called GlowCircle. It should feel like a high-end Dribbble shot brought to life: clean editorial layout, soft gradients, elegant typography, rounded cards, subtle shadows, glassy panels, tasteful motion, and a professional beauty brand vibe. This is only a static front-end site, no backend, no login, no real API, no database, and no external live data. Use mock/sample content for everything. I want a complete landing page with a hero section, social proof strip, featured creator profiles, beauty routine community cards, product discovery highlights, before-and-after story previews, membership benefits, brand partner showcase, testimonials, pricing or plan comparison, FAQ, newsletter-style CTA, and a polished footer. Add realistic interactions such as hover states, tabs for categories like skincare / makeup / haircare / wellness, a mock search input, filter chips, carousel-style testimonial controls, favorite/save buttons that toggle visually, share buttons that open a small static popover, and copy-link buttons that show copied feedback. Important: include skeleton loading states for the creator cards, routine cards, and testimonials, with a short simulated loading effect so the page feels premium even though all data is local/static. Make the responsive design excellent for desktop, tablet, and mobile. Keep the UI simple to run, but visually complex and carefully composed. Please organize the React components cleanly, use static arrays for content, make all buttons and interactions work on the page, and avoid anything requiring services, authentication, or server code." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00642/tests/grade.py b/tasks/dasyn_260630_00642/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00642/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00642/tests/test.sh b/tasks/dasyn_260630_00642/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00642/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00642/tests/webdev/__init__.py b/tasks/dasyn_260630_00642/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00642/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00642/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00642/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00642/tests/webdev/shot.py b/tasks/dasyn_260630_00642/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00642/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00642/tests/webdev/verdict.py b/tasks/dasyn_260630_00642/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00642/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00643/environment/Dockerfile b/tasks/dasyn_260630_00643/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00643/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00643/environment/setup/setup.sh b/tasks/dasyn_260630_00643/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00643/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00643/tests/grade.json b/tasks/dasyn_260630_00643/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..057facbfc965f43a8106e676c365c39c8fe0f5e1 --- /dev/null +++ b/tasks/dasyn_260630_00643/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Can you build me a polished static Vue portfolio website for a charity moving company, like a nonprofit that helps families, seniors, and shelters move safely when they are starting over. I want it to feel very art-deco but still warm and modern, with black, cream, muted gold, deep emerald, geometric borders, elegant headings, and a layout that feels a little like a Medium-style editorial story mixed with a professional service portfolio. It should be a full landing/portfolio site, not an app with accounts or anything, just static pages/sections using mock content. Please include a strong hero section with animated deco lines, a short mission statement, a featured story about a family move, a portfolio/gallery section showing different community moving projects, service cards, impact stats, volunteer callout, testimonials, process timeline, sponsor logos as placeholders, FAQ, and a nice footer. I want smooth scroll animations, hover effects, section reveal animations, animated counters can be fake/static, and a responsive design that looks good on mobile and desktop. Use Vue and keep all data as local sample content only, no backend, no API, no login, no database. Make it feel premium and emotional, like people would trust the organization and want to donate or volunteer, but the buttons can just be normal static links/placeholders." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00643/tests/grade.py b/tasks/dasyn_260630_00643/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00643/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00643/tests/test.sh b/tasks/dasyn_260630_00643/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00643/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00643/tests/webdev/__init__.py b/tasks/dasyn_260630_00643/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00643/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00643/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00643/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00643/tests/webdev/shot.py b/tasks/dasyn_260630_00643/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00643/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00643/tests/webdev/verdict.py b/tasks/dasyn_260630_00643/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00643/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00645/environment/Dockerfile b/tasks/dasyn_260630_00645/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00645/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00645/environment/setup/setup.sh b/tasks/dasyn_260630_00645/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00645/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00645/tests/grade.json b/tasks/dasyn_260630_00645/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..a6e5d8a32a9fbe26d1fb52526616a4673b8110c2 --- /dev/null +++ b/tasks/dasyn_260630_00645/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a minimalist static website for an automotive documentation event called AutoDocs Summit 2026. It should feel clean and commercial like an Amazon event/product page: strong hero section, clear CTA buttons, simple cards, lots of white space, sharp typography, and easy scanning. The event is for technical writers, service manual teams, parts catalog managers, and dealership training departments. Include sections for event overview, why attend, agenda, speaker cards, workshop tracks, venue details, pricing tiers, FAQ, and a documentation resource preview with sample static content only. Add a registration interest form on the page with fields for name, company, role, email, preferred track, and a short message, but keep it fully front-end/static with no backend or real submission required. Make the design responsive for desktop and mobile, professional but not flashy, with subtle automotive accents like charcoal, white, safety orange, and blueprint blue. Please avoid dashboards or app login flows; this should be a polished static marketing/event site that can run without external services." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00645/tests/grade.py b/tasks/dasyn_260630_00645/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00645/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00645/tests/test.sh b/tasks/dasyn_260630_00645/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00645/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00645/tests/webdev/__init__.py b/tasks/dasyn_260630_00645/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00645/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00645/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00645/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00645/tests/webdev/shot.py b/tasks/dasyn_260630_00645/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00645/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00645/tests/webdev/verdict.py b/tasks/dasyn_260630_00645/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00645/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00673/environment/Dockerfile b/tasks/dasyn_260630_00673/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00673/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00673/environment/setup/setup.sh b/tasks/dasyn_260630_00673/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00673/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00673/tests/grade.json b/tasks/dasyn_260630_00673/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..50ca878f83c26f4c8a184ef95bcc31fd8ec795af --- /dev/null +++ b/tasks/dasyn_260630_00673/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build me a polished static SvelteKit landing page for an architecture startup called FormaGrid. It should feel minimalist, premium, and modern, with some inspiration from Spotify’s clean dark sections, bold typography, sticky top navigation, smooth cards, and strong visual rhythm, but do not copy Spotify exactly. This is only a front-end static marketing website, no backend, no login, no database, no real API, no external services. Use mock/static content only. I want the page to sell a startup that helps property developers and design studios explore modular building concepts faster. Include a hero section with a strong headline, short pitch, two CTA buttons, and a search bar where users can type to search/filter static project examples or design templates on the page. The search should actually work on the client side using local sample data. Add sections for featured architecture systems, benefits, workflow steps, metrics, customer quotes, pricing-style plan cards even if they are just marketing packages, FAQ accordion, and a final CTA. Make the UI complex enough to feel like a real startup site: responsive layout, animated hover states, active search results, empty search state, category pills, sticky nav highlighting maybe, smooth scrolling, and clean reusable components. Keep the design minimalist with lots of spacing, black/charcoal background mixed with soft off-white panels, lime or green accent like a music-tech brand, elegant architectural imagery placeholders or gradient blocks, and strong grid layouts. Please make it production-quality visually, mobile friendly, accessible, and fully static so it can be built and rendered without any server implementation." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00673/tests/grade.py b/tasks/dasyn_260630_00673/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00673/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00673/tests/test.sh b/tasks/dasyn_260630_00673/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00673/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00673/tests/webdev/__init__.py b/tasks/dasyn_260630_00673/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00673/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00673/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00673/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00673/tests/webdev/shot.py b/tasks/dasyn_260630_00673/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00673/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00673/tests/webdev/verdict.py b/tasks/dasyn_260630_00673/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00673/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00674/environment/Dockerfile b/tasks/dasyn_260630_00674/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00674/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00674/environment/setup/setup.sh b/tasks/dasyn_260630_00674/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00674/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00674/tests/grade.json b/tasks/dasyn_260630_00674/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..fb389d56a1c686ff5b122318146678ee4c885a0c --- /dev/null +++ b/tasks/dasyn_260630_00674/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "ابغى تسوي لي موقع بورتفوليو بسيط وثابت لشركة تنسيق حدائق اسمها Green Line Gardens، يكون مبني بـ Nuxt كصفحة تسويقية نظيفة بدون باك اند ولا تسجيل دخول ولا قواعد بيانات. الستايل يكون سويسري مرتب وواضح، خطوط كبيرة، مساحات بيضاء كثيرة، جريد منظم، وأحساس قريب من موقع Linear من ناحية البساطة والنعومة. ابغى في الهيرو خلفية فيديو هادئة لحديقة أو نباتات تتحرك بشكل خفيف مع طبقة لون عشان النص يكون واضح، ولو ما فيه فيديو حقيقي استخدم placeholder محلي أو بلوك مناسب كأنه فيديو. الأقسام تكون: هيرو مع عنوان قوي وزر تواصل وهمي، نبذة قصيرة، خدمات مثل قص العشب وتصميم الحدائق والري، معرض مشاريع بصور ثابتة أو placeholders، أرقام بسيطة مثل سنوات الخبرة وعدد المشاريع، وشهادات عملاء نصية وهمية، وفي النهاية CTA وفوتر. خلي المحتوى كله sample/static وما يحتاج أي API، وخلي التصميم responsive ومناسب للجوال." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00674/tests/grade.py b/tasks/dasyn_260630_00674/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00674/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00674/tests/test.sh b/tasks/dasyn_260630_00674/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00674/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00674/tests/webdev/__init__.py b/tasks/dasyn_260630_00674/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00674/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00674/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00674/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00674/tests/webdev/shot.py b/tasks/dasyn_260630_00674/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00674/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00674/tests/webdev/verdict.py b/tasks/dasyn_260630_00674/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00674/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00680/environment/Dockerfile b/tasks/dasyn_260630_00680/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00680/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00680/environment/setup/setup.sh b/tasks/dasyn_260630_00680/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00680/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00680/tests/grade.json b/tasks/dasyn_260630_00680/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..f7ec6c893fd735c52b6701bfbe6123c221b82175 --- /dev/null +++ b/tasks/dasyn_260630_00680/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Please build me a polished static website for a tutoring knowledge wiki called TutorNest, kind of inspired by Airbnb’s clean card layout and friendly browsing feel, but for learning topics instead of rentals. I want it to be a product showcase / wiki style site where students can scroll through lots of tutoring subjects, lesson guides, study tips, tutor profile cards, course collections, and FAQ sections using infinite scroll with mock sample content only. Use vanilla HTML CSS and JavaScript, no backend or login or database. Make the design material style with soft shadows, rounded cards, clear hierarchy, nice spacing, filters/tabs that work on the sample content, search UI can be fake/static, and a responsive layout for desktop and mobile. The homepage should feel like a modern learning marketplace: hero section, subject category chips, featured tutoring paths, wiki article cards, testimonials, pricing cards, and a sticky top nav. Please keep it realistic and complete enough to open locally as a static site." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00680/tests/grade.py b/tasks/dasyn_260630_00680/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00680/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00680/tests/test.sh b/tasks/dasyn_260630_00680/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00680/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00680/tests/webdev/__init__.py b/tasks/dasyn_260630_00680/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00680/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00680/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00680/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00680/tests/webdev/shot.py b/tasks/dasyn_260630_00680/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00680/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00680/tests/webdev/verdict.py b/tasks/dasyn_260630_00680/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00680/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00687/environment/Dockerfile b/tasks/dasyn_260630_00687/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00687/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00687/environment/setup/setup.sh b/tasks/dasyn_260630_00687/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00687/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00687/tests/grade.json b/tasks/dasyn_260630_00687/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..ea8d8fd25322962bcc082b5b1dda27fa951b62a1 --- /dev/null +++ b/tasks/dasyn_260630_00687/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "请用 React 做一个纯静态的 SaaS 风格咖啡店品牌编辑类官网,主题是给独立咖啡馆使用的订阅式运营工具介绍页,不需要后端、登录、数据库或任何真实 API,所有数据用 mock 文案即可。整体视觉要干净、现代,有一点 Spotify 那种深色高级感和大色块排版,但不要照抄;页面包含 hero、产品理念、咖啡店运营痛点、功能卡片、客户故事、价格简表、编辑文章精选和 footer。请加一个明暗模式切换按钮,切换后背景、卡片、文字和强调色都要协调。技术上希望组件拆分清晰,CSS 可以用普通 CSS 或 Tailwind,重点是静态可渲染、响应式、简单交互流畅,不要做地图、实时数据、支付、账号系统或复杂动画。" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00687/tests/grade.py b/tasks/dasyn_260630_00687/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00687/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00687/tests/test.sh b/tasks/dasyn_260630_00687/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00687/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00687/tests/webdev/__init__.py b/tasks/dasyn_260630_00687/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00687/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00687/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00687/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00687/tests/webdev/shot.py b/tasks/dasyn_260630_00687/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00687/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00687/tests/webdev/verdict.py b/tasks/dasyn_260630_00687/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00687/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00689/environment/Dockerfile b/tasks/dasyn_260630_00689/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00689/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00689/environment/setup/setup.sh b/tasks/dasyn_260630_00689/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00689/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00689/tests/grade.json b/tasks/dasyn_260630_00689/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..5e59703f6412c9de32d7718a3b98f2295f196764 --- /dev/null +++ b/tasks/dasyn_260630_00689/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "صمم لي صفحة هبوط ثابتة بـ SvelteKit لخدمة محاسبة مخصصة للكنائس، ستايل بسيط ونظيف مثل Apple، فيها أقسام المزايا والتسعير وآراء وهمية وزر تواصل غير حقيقي، وعند الضغط على زر التجربة يظهر تأثير confetti فقط بدون باك اند." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00689/tests/grade.py b/tasks/dasyn_260630_00689/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00689/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00689/tests/test.sh b/tasks/dasyn_260630_00689/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00689/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00689/tests/webdev/__init__.py b/tasks/dasyn_260630_00689/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00689/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00689/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00689/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00689/tests/webdev/shot.py b/tasks/dasyn_260630_00689/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00689/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00689/tests/webdev/verdict.py b/tasks/dasyn_260630_00689/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00689/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00810/environment/Dockerfile b/tasks/dasyn_260630_00810/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00810/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00810/environment/setup/setup.sh b/tasks/dasyn_260630_00810/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00810/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00810/tests/grade.json b/tasks/dasyn_260630_00810/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..03cccb7e1d3681ce04c43a8cca388486599e8784 --- /dev/null +++ b/tasks/dasyn_260630_00810/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a simple static Next.js marketing site for “VowWire”, a friendly wedding-planning news digest. Style it with a clean Stripe-inspired layout: crisp typography, soft gradients, polished cards, and subtle page transitions between Home, Latest Stories, Planning Guides, and About. Use only mock articles/sample content, no backend or external APIs. Include a homepage hero, featured wedding planning news cards, newsletter signup visual only, and responsive header/footer." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00810/tests/grade.py b/tasks/dasyn_260630_00810/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00810/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00810/tests/test.sh b/tasks/dasyn_260630_00810/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00810/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00810/tests/webdev/__init__.py b/tasks/dasyn_260630_00810/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00810/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00810/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00810/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00810/tests/webdev/shot.py b/tasks/dasyn_260630_00810/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00810/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00810/tests/webdev/verdict.py b/tasks/dasyn_260630_00810/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00810/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00816/environment/Dockerfile b/tasks/dasyn_260630_00816/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00816/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00816/tests/grade.json b/tasks/dasyn_260630_00816/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..2d0ca46debd0c8b74fde98e8ee2d326c35316334 --- /dev/null +++ b/tasks/dasyn_260630_00816/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create dark Next.js photography hotel booking showcase, TikTok style vertical cards, simple UI, mock rooms only" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00816/tests/grade.py b/tasks/dasyn_260630_00816/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00816/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00817/environment/Dockerfile b/tasks/dasyn_260630_00817/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00817/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00817/environment/setup/setup.sh b/tasks/dasyn_260630_00817/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00817/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00817/tests/grade.json b/tasks/dasyn_260630_00817/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..a301e7ca800f456c268e330c492e7bbee57236d6 --- /dev/null +++ b/tasks/dasyn_260630_00817/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "simple static dental portfolio landing page, swiss style, reddit-ish cards, vanilla html css js, subtle animations" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00817/tests/grade.py b/tasks/dasyn_260630_00817/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00817/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00817/tests/test.sh b/tasks/dasyn_260630_00817/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00817/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00817/tests/webdev/__init__.py b/tasks/dasyn_260630_00817/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00817/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00817/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00817/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00817/tests/webdev/shot.py b/tasks/dasyn_260630_00817/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00817/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00817/tests/webdev/verdict.py b/tasks/dasyn_260630_00817/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00817/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00819/environment/Dockerfile b/tasks/dasyn_260630_00819/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00819/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00819/environment/setup/setup.sh b/tasks/dasyn_260630_00819/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00819/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00819/tests/grade.json b/tasks/dasyn_260630_00819/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..2cc5e505eee59ffd6b9bca213a041d58b8a3607d --- /dev/null +++ b/tasks/dasyn_260630_00819/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Сделай статичный сложный портфолио-сайт на Vue для ресторана Roof Cafe при кровельной студии: плоский дизайн, карточки и навигация как у Amazon, меню, галерея кровельных проектов, отзывы, акции. Только моковые данные, без бэка, с красивыми hover-эффектами." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00819/tests/grade.py b/tasks/dasyn_260630_00819/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00819/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00819/tests/test.sh b/tasks/dasyn_260630_00819/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00819/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00819/tests/webdev/__init__.py b/tasks/dasyn_260630_00819/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00819/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00819/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00819/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00819/tests/webdev/shot.py b/tasks/dasyn_260630_00819/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00819/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00819/tests/webdev/verdict.py b/tasks/dasyn_260630_00819/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00819/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00826/environment/Dockerfile b/tasks/dasyn_260630_00826/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00826/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00826/environment/setup/setup.sh b/tasks/dasyn_260630_00826/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00826/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00826/tests/grade.json b/tasks/dasyn_260630_00826/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..69ad3535a501003e41f89976bfee0cc122d4a082 --- /dev/null +++ b/tasks/dasyn_260630_00826/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build a polished static marketing website for my yoga studio using the uploaded logo, instructor portraits, and class room photos as the main brand assets. The site should feel elegant, calming, premium, and Dribbble-inspired, not generic wellness template. I want it to introduce the studio, highlight our slow-flow, prenatal, restorative, and sunrise classes, and include a beautiful changelog-style section called “Studio Notes” where we announce new class formats, seasonal schedule updates, workshop launches, and small improvements to the space. Please make the page fully responsive and simple to run as a front-end only site. Include a refined hero section, class cards, instructor highlights, membership/pricing preview, testimonials, FAQ, and a contact/visit section with static address and opening hours. Add a small floating chatbot-style widget in the bottom corner that opens into a peaceful mock assistant with prewritten sample replies like class recommendation, what to bring, beginner guidance, and membership info. It does not need AI, login, database, booking system, payments, or any real API; mock/static content is fine. Use soft neutrals, warm beige, muted sage, deep charcoal typography, elegant spacing, subtle motion/hover states, and make sure the uploaded assets are used tastefully without redesigning the logo." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00826/tests/grade.py b/tasks/dasyn_260630_00826/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00826/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00826/tests/test.sh b/tasks/dasyn_260630_00826/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00826/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00826/tests/webdev/__init__.py b/tasks/dasyn_260630_00826/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00826/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00826/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00826/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00826/tests/webdev/shot.py b/tasks/dasyn_260630_00826/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00826/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00826/tests/webdev/verdict.py b/tasks/dasyn_260630_00826/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00826/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00828/environment/Dockerfile b/tasks/dasyn_260630_00828/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00828/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00828/environment/setup/setup.sh b/tasks/dasyn_260630_00828/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00828/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00828/tests/grade.json b/tasks/dasyn_260630_00828/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..b1f8f33a223bdfe524ec1c6d140306195fcc214b --- /dev/null +++ b/tasks/dasyn_260630_00828/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Сделай простой статический сайт справочник по фитнесу в стиле glassmorphism, как аккуратная документация на GitHub: главная с кратким описанием, слева список разделов типа разминка, силовые упражнения, кардио, растяжка, питание и восстановление, а в центре карточки с короткими инструкциями. Добавь поиск по названию упражнения и категории, чтобы всё фильтровалось прямо на странице без сервера. Используй только HTML CSS и чистый JavaScript, данные можно сделать обычным массивом с примерами, никаких аккаунтов, базы данных и внешних API не надо. Пусть дизайн будет светлый, с полупрозрачными блоками, мягкими тенями, понятной навигацией и адаптацией под телефон." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00828/tests/grade.py b/tasks/dasyn_260630_00828/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00828/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00828/tests/test.sh b/tasks/dasyn_260630_00828/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00828/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00828/tests/webdev/__init__.py b/tasks/dasyn_260630_00828/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00828/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00828/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00828/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00828/tests/webdev/shot.py b/tasks/dasyn_260630_00828/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00828/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00828/tests/webdev/verdict.py b/tasks/dasyn_260630_00828/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00828/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00829/environment/Dockerfile b/tasks/dasyn_260630_00829/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00829/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00829/environment/setup/setup.sh b/tasks/dasyn_260630_00829/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00829/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00829/tests/grade.json b/tasks/dasyn_260630_00829/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..7d27798540f82c13966b069c3a5c25ccee0db60d --- /dev/null +++ b/tasks/dasyn_260630_00829/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Static React event site for a childcare-focused political campaign, warm Netflix-style hero/cards, GSAP scroll animations, RSVP + volunteer form mock only." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00829/tests/grade.py b/tasks/dasyn_260630_00829/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00829/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00829/tests/test.sh b/tasks/dasyn_260630_00829/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00829/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00829/tests/webdev/__init__.py b/tasks/dasyn_260630_00829/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00829/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00829/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00829/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00829/tests/webdev/shot.py b/tasks/dasyn_260630_00829/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00829/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00829/tests/webdev/verdict.py b/tasks/dasyn_260630_00829/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00829/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00843/environment/Dockerfile b/tasks/dasyn_260630_00843/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00843/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00843/environment/setup/setup.sh b/tasks/dasyn_260630_00843/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00843/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00843/tests/grade.json b/tasks/dasyn_260630_00843/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..abc2e75ffceb04409b56cbdb3dee59bcdffd7eb0 --- /dev/null +++ b/tasks/dasyn_260630_00843/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Prompt: Build a clean Swiss-style personal blog / portfolio website in Nuxt for an interior designer named Clara Vale. It should feel minimal, editorial, and slightly inspired by Spotify’s layout language: dark sidebar-style navigation on desktop, bold green accent, rounded content cards, playlist-like project collections, but NOT a music app clone. Static site only, use mock/sample content and local placeholder images.\n\nWebsite Goal: Clara wants a personal portfolio blog where she shares interior design projects, room styling notes, material inspiration, and short essays about calm living spaces.\n\nPages / Sections:\n\nHome Page\n- Left vertical navigation on desktop with logo text “Clara Vale Studio”, links: Home, Journal, Projects, Moodboards, About, Contact.\n- Mobile should use a simple top nav / hamburger style menu if needed.\n- Hero headline: “Quiet interiors, thoughtful details.”\n- Subtitle: “A personal archive of residential interiors, tactile materials, and everyday design observations.”\n- CTA buttons: “View Projects” and “Read Journal”.\n- Add a Spotify-inspired featured strip called “Currently Curating” with 3 cards: Warm Minimalism, Small Apartment Storage, Natural Stone & Linen.\n\nFeatured Projects Section\n- Grid of 4 project cards with mock content:\n 1. Linen House — soft neutral living room redesign\n 2. North Window Flat — compact apartment styling\n 3. Oak & Paper Studio — workspace interior concept\n 4. Garden Room Notes — calm guest room refresh\n- Each card should show category, short description, date, and a static placeholder image block.\n- Cards should be clean, Swiss, structured with generous spacing.\n\nJournal Section\n- Blog preview layout like an editorial index.\n- Include 5 sample article cards with title, excerpt, tag, and reading time.\n- Example titles: “How to make a room feel quieter”, “The case for fewer objects”, “Layering texture without clutter”, “Small spaces need rhythm”, “Choosing whites that do not feel cold”.\n- No CMS, no dynamic API, just local static arrays/components.\n\nMoodboard Section\n- Spotify playlist reference: create “moodboard playlists” as visual cards.\n- Each card has a title, short description, color swatches, and material tags.\n- Example: Clay + Cotton, Deep Green Kitchen, Pale Oak Morning, Travertine Weekend.\n\nAbout Section\n- Short bio for Clara Vale, independent interior designer and writer.\n- Include design principles in 3 columns: restraint, warmth, function.\n- Add a simple quote block: “A good room should lower your shoulders.”\n\nContact Section\n- Static contact area only, no backend form submission required.\n- Include email text, location “Copenhagen / remote consultations”, and social links as fake placeholder links.\n- If you include a form, make it visual only and show a note like “Static demo form”.\n\nVisual Direction:\n- Swiss grid, strong typography, lots of whitespace, precise alignment.\n- Color palette: off-white #F6F4EF, near-black #111111, muted grey #777, Spotify-inspired green #1DB954, warm beige #D8CBB8.\n- Use large type, thin dividers, clean spacing, rounded cards but not too bubbly.\n- Interior design aesthetic should feel calm, premium, editorial, not corporate.\n- Add subtle hover states and smooth transitions.\n- Fully responsive for desktop, tablet, and mobile.\n\nTechnical Requirements:\n- Use Nuxt for a static front-end site.\n- Keep all content local/mock/static in components or data files.\n- No backend, no database, no authentication, no external API, no real-time features.\n- No 3D, canvas, WebGL, or game-style interactions.\n- Use simple CSS / scoped styles / Nuxt structure as appropriate.\n- Make the page ready to render as a static portfolio/blog homepage." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00843/tests/grade.py b/tasks/dasyn_260630_00843/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00843/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00843/tests/test.sh b/tasks/dasyn_260630_00843/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00843/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00843/tests/webdev/__init__.py b/tasks/dasyn_260630_00843/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00843/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00843/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00843/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00843/tests/webdev/shot.py b/tasks/dasyn_260630_00843/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00843/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00843/tests/webdev/verdict.py b/tasks/dasyn_260630_00843/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00843/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00844/environment/Dockerfile b/tasks/dasyn_260630_00844/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00844/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00844/environment/setup/setup.sh b/tasks/dasyn_260630_00844/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00844/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00844/tests/grade.json b/tasks/dasyn_260630_00844/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..74115f8738f8a4cf66b7022c01570ba23c63cbf5 --- /dev/null +++ b/tasks/dasyn_260630_00844/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Can you build me a static React documentation style website for comparing moving companies, kind of clean like Twitter layout with tabs and cards, but with nice gradient backgrounds. I want sections for how to choose movers, price comparison tables, local vs long distance guide, packing tips docs, fake customer tweets/testimonials, and a small chatbot widget that only uses preset sample questions and answers, no backend or real API needed. Make it feel complete and professional with mock moving company data." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00844/tests/grade.py b/tasks/dasyn_260630_00844/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00844/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00844/tests/test.sh b/tasks/dasyn_260630_00844/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00844/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00844/tests/webdev/__init__.py b/tasks/dasyn_260630_00844/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00844/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00844/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00844/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00844/tests/webdev/shot.py b/tasks/dasyn_260630_00844/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00844/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00844/tests/webdev/verdict.py b/tasks/dasyn_260630_00844/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00844/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00872/environment/Dockerfile b/tasks/dasyn_260630_00872/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00872/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00872/environment/setup/setup.sh b/tasks/dasyn_260630_00872/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00872/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00872/tests/grade.json b/tasks/dasyn_260630_00872/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..ab1d2c457fe97aec90f8e5635ca7264cdf87fd81 --- /dev/null +++ b/tasks/dasyn_260630_00872/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "PROMPT: Create a premium modern static website for a music gear review platform called SoundScore Lab. It should feel like Vercel-style design: clean black/white base, subtle gradients, glass cards, sharp typography, lots of whitespace, smooth motion, polished product showcase vibe. This is a STATIC FRONT-END ONLY website, no backend, no login, no database, no real APIs. Use mock/sample content for all reviews, ratings, products, comments, charts, and newsletter form. Build with React and GSAP animations.\n\nWebsite concept: SoundScore Lab reviews headphones, studio monitors, microphones, MIDI controllers, audio interfaces, and portable speakers for musicians, producers, DJs, podcasters, and audiophiles.\n\nMain requirements:\n- Fully responsive desktop/tablet/mobile layout\n- Modern review-site design inspired by Vercel landing pages\n- Dark mode first, with optional light mode toggle using local state only\n- GSAP scroll animations for sections, cards, comparison rows, rating bars, and hero text\n- Confetti interaction when user clicks “Top Pick”, “Add to Shortlist”, or finishes the quiz section\n- All data must be hardcoded/static JSON inside the frontend\n- No external data services, no auth, no checkout, no real payment, no real newsletter submit\n\nPages/Sections:\n1. Header / Navigation\n- Sticky glass navbar\n- Logo: SoundScore Lab\n- Nav links: Reviews, Rankings, Compare, Buying Guides, Studio Picks, About\n- CTA button: “Find My Gear”\n- Mobile hamburger menu with smooth animation\n\n2. Hero Section\n- Big headline: “Find the music gear that actually sounds right.”\n- Subtitle about honest reviews, lab-style scoring, musician-focused recommendations\n- Search-style input mockup with placeholder like “Search headphones, mics, monitors…” but it does not need real backend search, just visual or local filtering if easy\n- CTA buttons: “Explore Top Reviews” and “Take Gear Quiz”\n- Floating product cards around hero: headphones, mic, speaker, audio interface\n- GSAP intro animation and subtle gradient blobs like Vercel style\n\n3. Featured Review Product Showcase\n- Large highlighted product review card: example “Auralis Pro X7 Headphones”\n- Product image placeholder/card area, price, category, badge “Editor’s Choice”\n- Rating breakdown: Sound Quality, Build, Comfort, Value, Features\n- Pros and cons list\n- CTA buttons: “Read Review” and “Add to Shortlist”\n- Confetti burst on shortlist click\n\n4. Review Rankings Grid\n- Cards for at least 12 mock products across categories\n- Each card needs product name, category, rating score, short verdict, badges like Best Budget, Best Studio, Best Bass, Best Portable\n- Filter chips: Headphones, Microphones, Monitors, Controllers, Interfaces, Speakers\n- Sorting dropdown UI: Highest Rated, Best Value, Newest Reviews (can be frontend/static only)\n- Smooth card entrance animations using GSAP\n\n5. Comparison Table\n- Modern responsive comparison section\n- Compare 4 products side by side\n- Columns: Score, Price, Best For, Frequency Response, Connectivity, Battery/Power, Verdict\n- Add animated rating bars\n- Include “Winner” badge and confetti when clicking the winner badge\n\n6. Interactive Gear Finder Quiz\n- Static multi-step quiz UI only, no backend\n- Questions like: What do you make? Budget range? Need portability? Preferred sound profile?\n- At the end show 3 recommended mock products\n- Trigger confetti when results appear\n- Use clean step indicators and GSAP transitions\n\n7. Editorial Buying Guides\n- Blog-style cards with sample articles:\n - Best Headphones for Mixing in 2026\n - Dynamic vs Condenser Microphones\n - Best Audio Interfaces Under $200\n - Studio Monitor Placement Guide\n- Include author, date, read time, category label\n- Static cards only\n\n8. Audio Score Methodology\n- Explain review scoring system visually\n- Circular score components or animated progress bars\n- Include categories: Frequency Accuracy, Detail, Noise Floor, Latency, Durability, Real-World Use\n- Use GSAP scroll-trigger animation\n\n9. User Review Style Section\n- Mock community quotes/testimonials from producers, singers, podcasters, DJs\n- No real user accounts\n- Include star ratings and small avatar initials\n\n10. Newsletter / CTA Section\n- “Get weekly gear picks in your inbox”\n- Email input is decorative/static, show success toast locally when clicked\n- No real email sending\n- CTA: “Notify Me”\n\n11. Footer\n- Links, categories, social icons placeholders\n- Disclaimer: Reviews are sample content for demo/static website\n- Polished minimal Vercel-like footer\n\nDesign details:\n- Color palette: near-black background, white text, gray borders, electric violet/blue accents, soft neon gradients\n- Use Inter or similar modern font\n- Cards should have subtle border, blur/glass effect, hover lift, glow on active states\n- Use modern icons if available locally/library allowed\n- Product images can be gradient placeholders or simple static assets, no need for real product photos\n- Make it feel like a serious professional product review publication, not a simple template\n\nTechnical notes:\n- React components should be clean and reusable\n- Use GSAP for meaningful animations, especially hero, scroll reveals, rating bars, quiz transitions\n- Confetti can be implemented with a lightweight frontend library or custom DOM effect, but no canvas game or 3D\n- Must run as a static site and not depend on any external API keys or server\n- Please include enough mock content so the page looks complete and complex." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00872/tests/grade.py b/tasks/dasyn_260630_00872/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00872/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00872/tests/test.sh b/tasks/dasyn_260630_00872/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00872/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00872/tests/webdev/__init__.py b/tasks/dasyn_260630_00872/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00872/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00872/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00872/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00872/tests/webdev/shot.py b/tasks/dasyn_260630_00872/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00872/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00872/tests/webdev/verdict.py b/tasks/dasyn_260630_00872/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00872/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00886/environment/Dockerfile b/tasks/dasyn_260630_00886/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00886/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00886/environment/setup/setup.sh b/tasks/dasyn_260630_00886/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00886/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00886/tests/grade.json b/tasks/dasyn_260630_00886/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..5dc8e3be6dd7c0ac04e67e1f870acfed22e73b3f --- /dev/null +++ b/tasks/dasyn_260630_00886/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Make a simple static React site for a cyberpunk hair salon, like a restaurant landing page but for salon news and offers. Use YouTube-style card layout for news videos/placeholders, no real API just mock content, and add a confetti effect when clicking book/offer buttons." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00886/tests/grade.py b/tasks/dasyn_260630_00886/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00886/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00886/tests/test.sh b/tasks/dasyn_260630_00886/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00886/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00886/tests/webdev/__init__.py b/tasks/dasyn_260630_00886/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00886/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00886/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00886/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00886/tests/webdev/shot.py b/tasks/dasyn_260630_00886/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00886/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00886/tests/webdev/verdict.py b/tasks/dasyn_260630_00886/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00886/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_00888/environment/Dockerfile b/tasks/dasyn_260630_00888/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_00888/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_00888/environment/setup/setup.sh b/tasks/dasyn_260630_00888/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_00888/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_00888/tests/grade.json b/tasks/dasyn_260630_00888/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..d8b2b2b8dfeb833bbdd9e4c67778fa416f14f357 --- /dev/null +++ b/tasks/dasyn_260630_00888/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "make me a static pricing page for a marketplace startup kind of like a cleaner Medium-style layout but with soft neomorphism cards and Tailwind. it should show different seller plans, buyer perks, featured add-ons, comparison table, faq, and a nice hero section with mock stats only. no backend or login stuff, just a polished responsive page with simple buttons/toggles for monthly vs yearly prices using sample content" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_00888/tests/grade.py b/tasks/dasyn_260630_00888/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_00888/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_00888/tests/test.sh b/tasks/dasyn_260630_00888/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_00888/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_00888/tests/webdev/__init__.py b/tasks/dasyn_260630_00888/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_00888/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_00888/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_00888/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_00888/tests/webdev/shot.py b/tasks/dasyn_260630_00888/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_00888/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_00888/tests/webdev/verdict.py b/tasks/dasyn_260630_00888/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_00888/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01103/environment/Dockerfile b/tasks/dasyn_260630_01103/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01103/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01103/environment/setup/setup.sh b/tasks/dasyn_260630_01103/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01103/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01103/tests/grade.json b/tasks/dasyn_260630_01103/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..509595b32fcd87661e9daf124664e3ca99037f60 --- /dev/null +++ b/tasks/dasyn_260630_01103/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Can you build me a polished static editorial style website for an elderly care service changelog, like a warm magazine page where families can read what changed each month in the care home and app updates. I want it to feel inspired by Xiaohongshu layouts, with cute card sections, soft captions, little tags, friendly photos placeholders and that lifestyle notebook vibe, but still professional for older adults and their children. Please make the whole design glassmorphism with frosted panels, pastel peach, cream, soft mint and gentle blue colors, big readable text, calm spacing and accessibility feeling. The page should have a hero saying something like Care Updates Journal, then featured changelog cards for things like safer medication reminders, new family visit calendar, improved meal preference notes, fall prevention checklist, caregiver training updates, and resident activity highlights. Use only mock/static sample content, no API or backend or login. I also want a nice timeline section, editor notes, small quote blocks from family members, and a final newsletter-style call to action that is just visual, not functional. Add some tasteful GSAP animations for card entrance, sticky-ish section reveals, hover micro interactions, and when someone clicks a celebrate update button it should throw confetti on the page. Keep it fully static front-end only, responsive for mobile and desktop, medium complexity, no 3d, no canvas game, no real data connection. Make it feel gentle, trustworthy, modern, and shareable like a Xiaohongshu post but as a real website." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01103/tests/grade.py b/tasks/dasyn_260630_01103/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01103/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01103/tests/test.sh b/tasks/dasyn_260630_01103/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01103/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01103/tests/webdev/__init__.py b/tasks/dasyn_260630_01103/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01103/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01103/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01103/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01103/tests/webdev/shot.py b/tasks/dasyn_260630_01103/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01103/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01103/tests/webdev/verdict.py b/tasks/dasyn_260630_01103/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01103/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01104/environment/Dockerfile b/tasks/dasyn_260630_01104/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01104/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01104/environment/setup/setup.sh b/tasks/dasyn_260630_01104/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01104/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01104/tests/grade.json b/tasks/dasyn_260630_01104/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..701f17b7de67f01ed700db2194f0bf395cbde454 --- /dev/null +++ b/tasks/dasyn_260630_01104/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "اريد منك إنشاء موقع ويب ثابت ب React لعرض منتج مالي خيري خاص بكنيسة اسمها مؤقتا GraceLedger، الفكرة انه منصة تعريفية فقط تساعد الكنيسة على شرح كيف يمكن تنظيم التبرعات والميزانيات والمصاريف بشفافية لكن بدون تسجيل دخول وبدون قاعدة بيانات وبدون ربط دفع حقيقي وبدون اي API، فقط واجهة تسويقية كاملة بمحتوى تجريبي. التصميم اريده brutalist قوي وواضح، مربعات سميكة، حدود سوداء عريضة، ألوان عالية التباين، تايبوجرافي كبيرة، كروت قاسية، ظلال حادة، شكل غير ناعم كثيرا، لكن يبقى مرتب ومقروء ومناسب لكنيسة ومجال fintech في نفس الوقت. اريد الصفحة طويلة ومعقدة مثل موقع منتج حقيقي وفيها شريط تنقل sticky يبقى فوق عند التمرير ويحتوي روابط للأقسام مثل الرئيسية، المشكلة، الحل، المميزات، لوحة الشفافية، الخطط، الأسئلة، تواصل. خذ إلهام من طريقة Bilibili في كثافة البطاقات، الأقسام المتعددة، الشرائط الأفقية، الإحساس النشط والحيوي، لكن لا تنسخ العلامة أو الألوان حرفيا. الصفحة الرئيسية تبدأ بهيرو كبير فيه عنوان قوي عن الشفافية المالية للكنائس، وصف قصير، زر أساسي وهمي مثل استكشف العرض وزر ثانوي مثل شاهد كيف يعمل، مع بطاقات أرقام ثابتة مثل تبرعات هذا الشهر، مشاريع مفتوحة، تقارير منشورة، وكلها mock data. بعد ذلك اعمل قسم يعرض المشكلة الحالية في إدارة التبرعات بطريقة بصرية، ثم قسم المنتج وفيه mock dashboard مصمم فقط بال HTML/CSS يعرض دخل، مصروفات، صناديق تبرع، حالة مشروع ترميم، ولا يحتاج أي بيانات حقيقية. أريد أيضا قسم مميزات مفصل فيه بطاقات: تتبع التبرعات، ميزانية النشاطات، تقارير للمجلس، وضوح للمجتمع، أرشفة الإيصالات بشكل تمثيلي فقط، تنبيهات شكلية غير حقيقية. أضف قسم product showcase كبير يعرض ثلاث لقطات واجهة وهمية داخل إطارات brutalist، واحدة للوحة الكنيسة، واحدة لتقرير شهري، واحدة لمقارنة المصروفات، وكل لقطة تكون ثابتة. أريد قسم تسعير أو باقات لكن كعرض تسويقي فقط: Starter Parish وCommunity Finance وDiocese View مع مميزات وهمية ولا يوجد شراء حقيقي. أضف قسم قصص استخدام ثابتة لكنيسة صغيرة وكنيسة حضرية ومؤسسة خيرية تابعة للكنيسة، مع أسماء خيالية. أريد عناصر تفاعلية أمامية فقط مثل أزرار تتغير hover، tabs لعرض أقسام dashboard، accordion للأسئلة الشائعة، sticky nav يوضح القسم النشط إذا أمكن بدون تعقيد، وفلاتر بسيطة لكروت المميزات كلها محلية داخل الصفحة. لا تضف تسجيل دخول ولا لوحة حقيقية ولا حفظ بيانات ولا عمليات دفع. اجعل الموقع responsive للجوال والتابلت والديسكتوب، مع قائمة موبايل واضحة. اهتم بالتفاصيل: microcopy عربي جيد، اتجاه RTL، أزرار كبيرة، حالات hover/focus، تباعد مضبوط، footer فيه روابط وهمية وملاحظة أن كل الأرقام تجريبية للعرض فقط. اريد الكود نظيف ومقسم إلى مكونات React واضحة، ويمكن تشغيله كموقع static فقط بدون خدمات خارجية." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01104/tests/grade.py b/tasks/dasyn_260630_01104/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01104/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01104/tests/test.sh b/tasks/dasyn_260630_01104/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01104/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01104/tests/webdev/__init__.py b/tasks/dasyn_260630_01104/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01104/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01104/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01104/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01104/tests/webdev/shot.py b/tasks/dasyn_260630_01104/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01104/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01104/tests/webdev/verdict.py b/tasks/dasyn_260630_01104/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01104/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01132/environment/Dockerfile b/tasks/dasyn_260630_01132/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01132/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01132/environment/setup/setup.sh b/tasks/dasyn_260630_01132/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01132/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01132/tests/grade.json b/tasks/dasyn_260630_01132/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..98b29bb4daea99be785f1865bb56acd05eb599ce --- /dev/null +++ b/tasks/dasyn_260630_01132/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "ابغى موقع توثيق بسيط بـ SvelteKit لمجتمع فني محلي، ستايل minimalist ومرتب شوي مثل طريقة تنظيم Amazon بالتصنيفات، صفحات ثابتة عن الورش والمعارض ودليل الانضمام، مع محتوى تجريبي كفاية وتأثيرات hover ناعمة على الكروت والروابط بدون باكند" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01132/tests/grade.py b/tasks/dasyn_260630_01132/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01132/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01132/tests/test.sh b/tasks/dasyn_260630_01132/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01132/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01132/tests/webdev/__init__.py b/tasks/dasyn_260630_01132/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01132/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01132/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01132/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01132/tests/webdev/shot.py b/tasks/dasyn_260630_01132/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01132/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01132/tests/webdev/verdict.py b/tasks/dasyn_260630_01132/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01132/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01133/environment/Dockerfile b/tasks/dasyn_260630_01133/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01133/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01133/environment/setup/setup.sh b/tasks/dasyn_260630_01133/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01133/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01133/tests/grade.json b/tasks/dasyn_260630_01133/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..be318c8933b9f581055bdc7f6a34e9db41440d12 --- /dev/null +++ b/tasks/dasyn_260630_01133/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "MASTER PROMPT – STATIC EVENT PORTFOLIO WEBSITE FOR A COWORKING SPACE\n\nCreate a modern material-design Next.js static website for a coworking space called “NOVA DESK Studio”. The website is not an app, no backend, no login, no database, no real API, no booking system. It should be a polished static front-end marketing/event portfolio site that can run with only mock/static content. Use Next.js + React components, clean CSS modules or Tailwind, and make it fully responsive.\n\nMAIN GOAL\nBuild an event-focused portfolio website for a premium coworking space that hosts workshops, founder talks, design meetups, demo nights, networking breakfasts, creator sessions, and community events. The site should feel like a mix of a professional coworking landing page + event showcase + YouTube-inspired media library. Reference YouTube visually only for the grid of video/event cards, thumbnail style, channel-like profile area, tabs, play badges, and clean content hierarchy. Do NOT connect to YouTube API and do NOT require live embeds; use static placeholder thumbnails and mock titles.\n\nSTYLE / VISUAL DIRECTION\n- Material design, clean surfaces, cards, shadows, rounded corners, elevation layers\n- Premium but approachable coworking feel\n- Light theme primarily, with deep navy/charcoal sections for contrast\n- Accent colors: electric blue, warm orange, soft mint\n- Background: off-white #F7F8FA with subtle geometric patterns\n- Use large hero typography, smooth spacing, soft shadows\n- Include parallax scrolling effects: hero background blobs move slowly, event cards section has subtle depth movement, venue photos slide at different speeds while scrolling\n- No 3D, no WebGL, no canvas, no game elements\n- Animations should be CSS/Framer Motion style only if needed, but keep it static and simple\n\nSTRUCTURE REQUIRED\n\n1. TOP NAVBAR\n- Left: logo icon + “NOVA DESK Studio”\n- Center nav links: Home, Events, Spaces, Speakers, Gallery, Testimonials, Contact\n- Right CTA button: “View Upcoming Events”\n- Sticky navbar with slight blur and material shadow on scroll\n- Mobile hamburger menu is okay but it must be static front-end only\n\n2. HERO SECTION\nHeadline: “Where Workspaces Become Community Stages”\nSubheadline: “A curated coworking space for founders, designers, creators, and teams — hosting weekly talks, workshops, demo nights, and creative meetups.”\nCTA buttons:\n- Explore Events\n- See the Space\nHero layout:\n- Left text with badges: “Weekly Events”, “120+ Community Sessions”, “Central City Location”\n- Right side: material glass dashboard card showing event preview timeline\n Example cards:\n • Tue 18: Design Systems Night\n • Thu 20: Startup Pitch Practice\n • Sat 22: Creator Breakfast Club\n- Add floating chips around hero: “Fast Wi-Fi”, “Podcast Room”, “Workshop Hall”, “Coffee Bar”\n- Parallax background with soft blue/orange circles and grid pattern\n\n3. YOUTUBE-INSPIRED FEATURED EVENTS WALL\nThis is important. Make it visually inspired by YouTube’s homepage/channel video grid but adapted for coworking events.\n- Section title: “Featured Community Sessions”\n- Add horizontal filter tabs like: All, Workshops, Founder Talks, Design, Marketing, Networking, Wellness\n- Cards should look like event/video thumbnails:\n - large rectangular thumbnail image placeholder\n - small play icon overlay or “Recap” badge\n - title\n - host/speaker avatar\n - metadata line: “NOVA DESK • 2 days ago • 48 attendees” but static mock text\n - short category pill\n- Use 8 sample event cards\nExample event titles:\n 1. “Building a Personal Brand from a Shared Desk”\n 2. “Design Critique Night: Landing Pages That Convert”\n 3. “Founder Coffee: From Idea to First Customer”\n 4. “No-Code Demo Evening for Small Teams”\n 5. “Freelancer Finance Basics Workshop”\n 6. “Community Lunch: Remote Teams Edition”\n 7. “Creator Studio Open House”\n 8. “Mindful Productivity for Busy Makers”\n- This is static only, no real video playback required. If a modal is added, it can just show a static recap card.\n\n4. UPCOMING EVENT HIGHLIGHT\nA large material card with event poster style.\nTitle: “Next Big Event: Workspace Futures Summit”\nDate: “Friday, July 24, 2026”\nTime: “6:00 PM – 9:30 PM”\nLocation: “NOVA DESK Main Lounge”\nDescription: “An evening of short talks, networking, and practical ideas for building better work cultures in flexible spaces.”\nInclude agenda timeline:\n- 6:00 Welcome Coffee\n- 6:30 Opening Talk\n- 7:15 Panel Discussion\n- 8:00 Community Demos\n- 8:45 Open Networking\nCTA button: “Save My Spot” but it should NOT connect to backend, just a visual CTA or anchor link.\nAdd small note: “Static demo button – no registration backend included.”\n\n5. ABOUT THE COWORKING SPACE\nCreate section with two columns:\nLeft: image collage placeholders of coworking desks, meeting room, lounge, workshop area\nRight: text:\n“Designed for people who need more than a desk.”\nBullets:\n- Flexible work zones for focus and collaboration\n- Event-ready lounge with projector and modular seating\n- Creator room for podcasts, filming, and workshops\n- Community calendar with curated learning sessions\n- Coffee, lockers, phone booths, and high-speed internet\nUse material icon-like circles.\n\n6. SPACES PORTFOLIO SECTION\nThis is portfolio scenario. Show the different spaces as portfolio case cards:\n- Focus Desk Zone\n- Founder Meeting Room\n- Creator Recording Booth\n- Event Lounge\n- Coffee & Networking Bar\n- Outdoor Brainstorm Terrace\nEach card: image placeholder, title, capacity, best for, small feature list. Static content only.\nAdd hover effect: card lifts with shadow.\n\n7. SPEAKERS / HOSTS SECTION\nShow 6 host profile cards with avatars:\n- Maya Chen – Brand Strategist\n- Leo Martin – Product Designer\n- Sofia Alvarez – Startup Mentor\n- Noah Kim – Community Builder\n- Amara Patel – Wellness Coach\n- Elias Brooks – Growth Marketer\nEach card has role, short bio, and topics. Use material cards.\n\n8. PARALLAX STORY STRIP\nAdd a full-width section with parallax background image placeholder and overlay text:\n“From quiet morning focus sessions to packed evening panels, NOVA DESK is built to turn everyday work into meaningful connections.”\nInclude counters:\n- 120+ Events Hosted\n- 3,500+ Guests Welcomed\n- 40+ Local Speakers\n- 6 Flexible Spaces\nCounters can be static numbers, no real counting needed but animation is okay.\n\n9. EVENT GALLERY\nUse masonry or neat responsive grid. Static images only.\nCategories: Talks, Workshops, Community, Space Details.\nAdd captions like YouTube community post vibe but more professional.\nNo external image API. Use local placeholders or gradients.\n\n10. TESTIMONIALS\nMaterial carousel-style layout but can be static cards.\nTestimonials:\n- “The founder nights helped me meet my first design partner.”\n- “Best coworking event energy in the city.”\n- “A beautiful space where workshops actually feel premium.”\nInclude names and roles. Static.\n\n11. PRICING / ACCESS CARDS OPTIONAL BUT STATIC\nCreate 3 cards:\n- Day Pass – “For curious visitors”\n- Community Events Pass – “For regular learners”\n- Team Studio Day – “For small teams”\nDo not implement payment. Add text: “Pricing shown for demo layout only.”\n\n12. CONTACT / VISIT SECTION\nStatic contact area only:\n- Address: 84 Meridian Avenue, Creative District\n- Email: hello@novadesk.example\n- Hours: Mon–Fri 8:00–20:00, Sat 10:00–16:00\n- Add simple visual form with fields Name, Email, Message, but it should not submit anywhere. Can show disabled/demo submit button or prevent default.\n- Include note: “Static front-end form, no backend submission.”\n\n13. FOOTER\nColumns:\n- NOVA DESK Studio mini description\n- Explore links\n- Event Categories\n- Social links as icons/text only\n- Newsletter mock input but no backend\nFooter bottom: “© 2026 NOVA DESK Studio. Static demo website.”\n\nINTERACTION REQUIREMENTS\n- Smooth scrolling between sections\n- Parallax scrolling elements in hero and story strip\n- Hover states on cards and buttons\n- Filter tabs can visually switch active state if simple local state is used, but static sample data is enough\n- Mobile responsive: desktop 3–4 card grid, tablet 2, mobile 1\n- Sticky nav with blur\n- Button micro-interactions\n\nTECH REQUIREMENTS\n- Use Next.js static front-end, React components\n- No server actions, no API routes, no external database, no authentication, no live data\n- All content can be hardcoded arrays in components\n- Use mock images/placeholders or local assets\n- Keep file structure clean: components for Navbar, Hero, EventGrid, SpacePortfolio, Speakers, Gallery, Testimonials, Footer\n- Make the design production-quality, not plain template\n- Must be renderable as a static site without external services\n\nFINAL FEEL\nThe finished website should look like a premium coworking space event portfolio, with material cards and YouTube-inspired event thumbnails, strong visual hierarchy, smooth parallax sections, and polished responsive layout. Make it medium complexity but very complete visually." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01133/tests/grade.py b/tasks/dasyn_260630_01133/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01133/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01133/tests/test.sh b/tasks/dasyn_260630_01133/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01133/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01133/tests/webdev/__init__.py b/tasks/dasyn_260630_01133/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01133/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01133/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01133/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01133/tests/webdev/shot.py b/tasks/dasyn_260630_01133/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01133/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01133/tests/webdev/verdict.py b/tasks/dasyn_260630_01133/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01133/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01135/environment/Dockerfile b/tasks/dasyn_260630_01135/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01135/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01135/environment/setup/setup.sh b/tasks/dasyn_260630_01135/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01135/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01135/tests/grade.json b/tasks/dasyn_260630_01135/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..aaf7a7b14a6ca4b26a4fe9db352b7ceedf7660d4 --- /dev/null +++ b/tasks/dasyn_260630_01135/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a premium corporate fashion pricing page website like the attached Netflix-style reference, but for a luxury clothing subscription/editorial brand. I want a static front-end only site with no backend, no login, no payment, and no API needed, use mock/static content. The page should feel like a polished fashion magazine meets SaaS pricing page: dark elegant hero, big editorial typography, sticky top navigation, cinematic plan cards, scroll-driven sections that reveal benefits, comparison table, seasonal collection highlights, testimonial quotes from stylists, FAQ, and final CTA. Include 3 pricing tiers such as Essential Edit, Studio Wardrobe, and Maison Concierge with monthly/yearly toggle UI only visual, not functional payment. Make the design inspired by Netflix pricing layout with bold red accent transformed into high-fashion burgundy/gold/black palette. It must be fully responsive for mobile, tablet, and desktop, with smooth scroll animations, clean corporate spacing, premium imagery placeholders, and simple React + CSS/Tailwind components that can run as a static website without external services." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01135/tests/grade.py b/tasks/dasyn_260630_01135/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01135/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01135/tests/test.sh b/tasks/dasyn_260630_01135/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01135/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01135/tests/webdev/__init__.py b/tasks/dasyn_260630_01135/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01135/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01135/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01135/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01135/tests/webdev/shot.py b/tasks/dasyn_260630_01135/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01135/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01135/tests/webdev/verdict.py b/tasks/dasyn_260630_01135/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01135/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01157/environment/Dockerfile b/tasks/dasyn_260630_01157/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01157/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01157/environment/setup/setup.sh b/tasks/dasyn_260630_01157/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01157/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01157/tests/grade.json b/tasks/dasyn_260630_01157/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..1a7819225dbe52c9fd3ca56f6c1a06aa557f01a4 --- /dev/null +++ b/tasks/dasyn_260630_01157/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a static SvelteKit link-in-bio event site for a nonprofit climate meetup, clean Scandinavian style, with Amazon-like searchable event/resource cards, filters, donation/volunteer links, speakers, schedule, sponsors, all using mock content only no backend." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01157/tests/grade.py b/tasks/dasyn_260630_01157/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01157/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01157/tests/test.sh b/tasks/dasyn_260630_01157/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01157/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01157/tests/webdev/__init__.py b/tasks/dasyn_260630_01157/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01157/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01157/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01157/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01157/tests/webdev/shot.py b/tasks/dasyn_260630_01157/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01157/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01157/tests/webdev/verdict.py b/tasks/dasyn_260630_01157/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01157/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01159/environment/Dockerfile b/tasks/dasyn_260630_01159/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01159/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01159/environment/setup/setup.sh b/tasks/dasyn_260630_01159/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01159/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01159/tests/grade.json b/tasks/dasyn_260630_01159/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..d9d0d04c50cd6dad850f22ab58841e8f1c26a601 --- /dev/null +++ b/tasks/dasyn_260630_01159/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "帮我做一个 React 静态网站,主题是「城市公共文化会员服务指南」,偏政府/公共服务类的信息编辑站,不要后台不要登录不要接口,所有数据都用本地 mock 内容写死即可。整体视觉参考小红书的信息流排版和卡片感,但不要做成社交平台,要更正式、更可信,适合市民浏览公共图书馆、文化馆、博物馆、社区活动中心的会员权益说明。风格要求:新拟态 neomorphism,浅灰白背景,柔和阴影,圆角大卡片,少量政务蓝 + 暖橙点缀,干净高级,不要太花。页面结构要复杂一点:顶部固定导航,左侧可以有目录锚点,主内容是编辑型专题页。必须包含:首页 Hero(标题:一张公共文化会员卡,解锁城市共享文化资源),副标题、两个 CTA 按钮(立即了解权益 / 查看办理材料),右侧做一组新拟态数据卡片,比如 128 家场馆、36 类活动、0 元基础会员、全年可用;下面做「会员类型」三档卡片:基础会员、家庭会员、长者友好会员,写清适用人群、权益、办理材料;再做「权益清单」模块,用小红书风格瀑布流/笔记卡片展示借阅、预约展览、公益课程、亲子活动、无障碍服务、积分兑换(注意积分只是展示规则,不要实现真实账户);做「办理流程」时间线:准备材料、填写申请、现场核验、领取实体卡/电子凭证说明(静态展示即可);做「常见问题」折叠样式可以用前端本地 state;做一个「会员申请意向表」静态表单,字段包括姓名、手机号、所在区、会员类型、常去场馆、备注,提交后只在页面显示成功提示,不要真的发送;再做政策提示/温馨提醒模块、服务热线展示、页脚。交互:导航锚点跳转、FAQ 展开收起、会员类型筛选权益卡片、本地表单校验和成功状态、返回顶部按钮。不要使用真实地图、真实 API、真实认证、数据库或后端。内容用中文,文案要像政府网站但更亲民,组件化写清楚,响应式适配手机和桌面。" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01159/tests/grade.py b/tasks/dasyn_260630_01159/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01159/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01159/tests/test.sh b/tasks/dasyn_260630_01159/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01159/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01159/tests/webdev/__init__.py b/tasks/dasyn_260630_01159/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01159/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01159/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01159/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01159/tests/webdev/shot.py b/tasks/dasyn_260630_01159/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01159/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01159/tests/webdev/verdict.py b/tasks/dasyn_260630_01159/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01159/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01161/environment/Dockerfile b/tasks/dasyn_260630_01161/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01161/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01161/environment/setup/setup.sh b/tasks/dasyn_260630_01161/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01161/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01161/tests/grade.json b/tasks/dasyn_260630_01161/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..aadc2de85d0f2a67e39dab5b2252661106af5d96 --- /dev/null +++ b/tasks/dasyn_260630_01161/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "صمّم Landing Page ثابتة وبسيطة لمجتمع جمال اسمه \"Glow Circle\" باستخدام React و Tailwind CSS فقط. المطلوب يكون ستايل ودود، ناعم، وألوان وردي فاتح / كريمي / بنفسجي خفيف. الصفحة هدفها دعوة البنات للانضمام لمجتمع يهتم بالعناية بالبشرة والمكياج وتبادل النصائح. الأقسام المطلوبة: Hero Section بعنوان واضح \"مجتمعك اليومي للجمال والثقة\" مع وصف قصير وزرين CTA: \"انضمي للمجتمع\" و \"شاهدي الروتين\". قسم بطاقات للمميزات: نصائح يومية، تحديات عناية أسبوعية، مراجعات منتجات، جلسات دردشة مجتمعية لكن كلها محتوى ثابت/وهمي بدون تسجيل دخول. قسم تفاعلي بسيط Drag and Drop: بطاقات روتين صباحي مثل Cleanser, Toner, Serum, Sunscreen يستطيع المستخدم ترتيبها بالسحب والإفلات، مع شكل لطيف وتعليمات قصيرة، بدون حفظ بيانات. قسم قصص من العضوات باستخدام شهادات وهمية وصور placeholder. قسم جدول فعاليات ثابتة للشهر مثل Beauty Sunday و Makeup Swap. Footer بسيط فيه روابط وهمية وأيقونات اجتماعية غير مرتبطة بخدمات حقيقية. اجعل التصميم Responsive للموبايل والتابلت والديسكتوب، مع حركات Hover خفيفة وGlass cards، ولا تستخدم أي Backend أو API أو قاعدة بيانات، فقط محتوى Static Sample داخل الكود." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01161/tests/grade.py b/tasks/dasyn_260630_01161/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01161/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01161/tests/test.sh b/tasks/dasyn_260630_01161/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01161/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01161/tests/webdev/__init__.py b/tasks/dasyn_260630_01161/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01161/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01161/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01161/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01161/tests/webdev/shot.py b/tasks/dasyn_260630_01161/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01161/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01161/tests/webdev/verdict.py b/tasks/dasyn_260630_01161/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01161/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01166/environment/Dockerfile b/tasks/dasyn_260630_01166/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01166/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01166/environment/setup/setup.sh b/tasks/dasyn_260630_01166/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01166/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01166/tests/grade.json b/tasks/dasyn_260630_01166/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..4e06709d61c82a3bdedca44b2f2b7e7f74daa409 --- /dev/null +++ b/tasks/dasyn_260630_01166/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a simple static React website for a restaurant hiring campaign, like a clean Vercel style landing page with material design cards and soft animations, show a hero section for recruiting chefs waiters baristas and delivery staff, add a gallery of restaurant workplace photos using sample images only, include job role cards with mock salary range and shift timing, benefits section, team culture section, opening branches section, and a contact/apply section with only static email phone and address text no backend form needed, make it responsive and modern with smooth hover effects and scroll animations" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01166/tests/grade.py b/tasks/dasyn_260630_01166/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01166/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01166/tests/test.sh b/tasks/dasyn_260630_01166/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01166/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01166/tests/webdev/__init__.py b/tasks/dasyn_260630_01166/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01166/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01166/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01166/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01166/tests/webdev/shot.py b/tasks/dasyn_260630_01166/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01166/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01166/tests/webdev/verdict.py b/tasks/dasyn_260630_01166/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01166/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01168/environment/Dockerfile b/tasks/dasyn_260630_01168/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01168/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01168/environment/setup/setup.sh b/tasks/dasyn_260630_01168/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01168/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01168/tests/grade.json b/tasks/dasyn_260630_01168/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..d8c2e230a048e4342b779d21846bdcad6e519d14 --- /dev/null +++ b/tasks/dasyn_260630_01168/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Can you build me a static Nuxt website for an online course product called CareFlix Academy, it teaches families how to take better care of elderly parents at home. I want it to feel kind of like Netflix but NOT glossy corporate, more brutalist and bold, like big blocks, harsh borders, oversized type, black/red/cream colors, course cards in rows, and a simple streaming-library vibe. It should be a product showcase landing page only, no login, no payments, no backend, no real video player needed, just mock/static content. Make the hero look like a featured course with a big title, short emotional description, rating, lesson count, and buttons like Start Learning and View Modules. Under it add rows like Popular Care Lessons, Dementia Basics, Safe Home Setup, Medication Routines, and Emergency Prep, each with course cards that look like Netflix thumbnails but brutalist. Include a skeleton loading interaction when the page first opens or when switching between course categories, just fake it with front-end state and placeholder cards for a second so it feels polished. Keep it simple but visually strong, responsive for phone and desktop, with a pricing/benefits strip, testimonials from adult children caregivers, FAQ, and a final CTA. Use sample course data inside the project, no APIs or external services, and make sure it can render as a static site." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01168/tests/grade.py b/tasks/dasyn_260630_01168/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01168/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01168/tests/test.sh b/tasks/dasyn_260630_01168/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01168/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01168/tests/webdev/__init__.py b/tasks/dasyn_260630_01168/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01168/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01168/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01168/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01168/tests/webdev/shot.py b/tasks/dasyn_260630_01168/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01168/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01168/tests/webdev/verdict.py b/tasks/dasyn_260630_01168/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01168/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01192/environment/Dockerfile b/tasks/dasyn_260630_01192/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01192/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01192/environment/setup/setup.sh b/tasks/dasyn_260630_01192/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01192/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01192/tests/grade.json b/tasks/dasyn_260630_01192/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..03b815ddb6db204585b173038bf763710c3edb38 --- /dev/null +++ b/tasks/dasyn_260630_01192/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build a static Nuxt website for a political campaign product showcase called Freight Forward 2026. It is a campaign-style site for a logistics modernization platform / policy package, not a real app. Use mock/static content only, no API, no backend, no login, no database.\n\nOverall Style\n- Swiss editorial design, very structured and clean\n- Inspired by Notion landing pages: lots of white space, simple cards, database/table-like blocks, crisp typography\n- Political campaign energy but not messy: confident, civic, organized, modern\n- Colors: off-white background, black text, deep navy, signal red accent, muted gray borders\n- Use strong grid layouts, thin dividers, numbered sections, manifesto-style blocks\n- Fully responsive for desktop, tablet, mobile\n- Static site only\n\nCore Interaction\n- Sticky top navigation that remains visible while scrolling\n- Nav links should smoothly jump to page sections\n- Active/hover states on nav items\n- CTA button always visible on desktop nav\n\nWebsite Goal\nShowcase Freight Forward 2026 as a campaign platform focused on safer ports, faster freight corridors, transparent supply chains, and stronger local jobs. It should feel like a polished product/policy showcase that a campaign team would use to explain the logistics plan to voters, unions, small businesses, port workers, and local press.\n\nPages / Sections\n\n1. Sticky Header\nLeft: Freight Forward 2026 wordmark\nNav items:\n- Platform\n- Logistics Plan\n- Impact\n- Endorsements\n- Timeline\n- FAQ\nRight CTA: Download Brief\nNo actual download needed, can be a styled button only.\n\n2. Hero Section\nSmall badge: Logistics Renewal Platform\nHeadline: Move Goods Faster. Protect Workers. Rebuild Trust.\nSubheadline: A campaign-ready logistics plan for resilient ports, fair freight routes, transparent procurement, and modern regional supply chains.\nCTA buttons:\n- View The Plan\n- Read The Brief\nRight side visual: Notion-style dashboard mockup with cards:\n- Port Delay Index: -28%\n- Local Freight Jobs: +18,400\n- Small Business Delivery Time: 2.1 days faster\n- Route Transparency Score: 94/100\nAdd small campaign label: Policy Draft • Public Version • June 2026\n\n3. Trust / Stats Strip\nUse clean Swiss number cards:\n- 42 regional freight corridors mapped\n- 12 port communities prioritized\n- 18K+ projected union jobs\n- 31% estimated idle-time reduction\n- 100% public reporting commitment\n\n4. Platform Overview\nTitle: A Logistics Platform Built Like Public Infrastructure\nThree large cards:\n- Faster Corridors: Dedicated freight priority zones, smarter scheduling, safer road design\n- Fairer Work: Strong labor standards, safer shifts, training pathways\n- Cleaner Movement: Lower idle time, electrified yards, transparent emissions reporting\nEach card should have small metadata tags like Policy Area, Voter Benefit, Delivery Window.\n\n5. Product Showcase / Policy Modules\nCreate a Notion/database-inspired section with six module cards:\n01 Port Reliability Dashboard\n02 Freight Corridor Renewal\n03 Local Supplier Preference\n04 Worker Safety Standard\n05 Clean Yard Conversion\n06 Public Delivery Tracker\nEach card should include:\n- short description\n- status pill like Drafted / Ready for Vote / Community Review\n- static metric\n- mini progress bar\n\n6. Logistics Plan Detail\nUse a split layout with left sticky section title and right stacked content blocks.\nBlocks:\n- Port Operations: reduce bottlenecks with appointment windows and transparent scheduling\n- Last-Mile Streets: safer routes away from schools and residential streets\n- Regional Warehousing: support small business delivery hubs without displacement\n- Procurement Reform: publish contracts, timelines, and performance scorecards\nMake this section feel like a policy doc mixed with SaaS product cards.\n\n7. Political Campaign Message Section\nLarge manifesto block:\nFreight is not just trucks and containers. It is groceries arriving on time, workers coming home safe, small businesses staying competitive, and neighborhoods breathing cleaner air.\nInclude three quote-style cards from fictional stakeholders:\n- Port worker\n- Small business owner\n- Neighborhood advocate\nClearly use fictional/sample names.\n\n8. Impact Dashboard\nCreate static mock dashboard cards:\n- Delivery Reliability\n- Worker Safety\n- Local Hiring\n- Emissions Reduction\n- Public Transparency\nInclude charts using simple CSS bars / lines only, no canvas, no external chart library required.\nShould look like a clean civic analytics board.\n\n9. Endorsement Strip\nUse fictional endorsements only:\n- Regional Truck Drivers Coalition\n- Main Street Retail Alliance\n- Clean Ports Neighborhood Council\n- Independent Logistics Policy Forum\nEach with a short one-sentence quote.\n\n10. Campaign Timeline\nHorizontal or vertical timeline:\n- Listening Tour\n- Draft Platform Release\n- Port Community Roundtables\n- Corridor Safety Audit\n- Public Brief Publication\n- Election Day Mobilization\nUse dates/months in 2026 and static sample content.\n\n11. Comparison Section\nTitle: Old Freight Politics vs Freight Forward 2026\nTwo-column comparison table:\nOld Way:\n- Closed-door contracts\n- Unclear delivery metrics\n- Unsafe street routing\n- Pollution treated as side effect\n- Workers consulted last\nFreight Forward 2026:\n- Public scorecards\n- Corridor reliability targets\n- Safe route design\n- Clean yard investment\n- Worker-first standards\n\n12. FAQ\nAccordion-style appearance is okay but can be static or simple client-side only. Questions:\n- Is this a real logistics app?\n- Who is this platform for?\n- Does the dashboard use live data?\n- How does the plan support workers?\n- Can communities review the proposal?\nAnswers must make clear the website uses static/mock content.\n\n13. Footer\nInclude:\n- Freight Forward 2026\n- Built for a modern logistics campaign\n- Links: Platform, Impact, Timeline, FAQ\n- Small disclaimer: Static concept website with sample content. No live data or external services.\n\nImplementation Notes\n- Use Nuxt static front-end\n- Componentize sections cleanly\n- Use CSS only for visual charts and dashboard mockups\n- No external APIs, no auth, no server routes\n- Make the UI polished enough for a campaign launch presentation\n- Strong attention to spacing, typography, alignment, and mobile behavior\n- Use placeholder/sample text where needed but make it realistic\n- Add subtle hover states on cards and buttons\n- Add smooth scroll behavior\n- Keep animations lightweight, like fade/slide or floating dashboard cards, no heavy effects" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01192/tests/grade.py b/tasks/dasyn_260630_01192/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01192/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01192/tests/test.sh b/tasks/dasyn_260630_01192/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01192/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01192/tests/webdev/__init__.py b/tasks/dasyn_260630_01192/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01192/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01192/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01192/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01192/tests/webdev/shot.py b/tasks/dasyn_260630_01192/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01192/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01192/tests/webdev/verdict.py b/tasks/dasyn_260630_01192/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01192/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01195/environment/Dockerfile b/tasks/dasyn_260630_01195/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01195/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01195/environment/setup/setup.sh b/tasks/dasyn_260630_01195/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01195/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01195/tests/grade.json b/tasks/dasyn_260630_01195/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..fe7de0791adec5930bbd4d605bf4082c2eae8448 --- /dev/null +++ b/tasks/dasyn_260630_01195/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Astro static portfolio site for a warm tutoring startup, Netflix-style cards/sections, rich hover effects, mock content only" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01195/tests/grade.py b/tasks/dasyn_260630_01195/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01195/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01195/tests/test.sh b/tasks/dasyn_260630_01195/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01195/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01195/tests/webdev/__init__.py b/tasks/dasyn_260630_01195/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01195/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01195/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01195/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01195/tests/webdev/shot.py b/tasks/dasyn_260630_01195/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01195/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01195/tests/webdev/verdict.py b/tasks/dasyn_260630_01195/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01195/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01300/environment/Dockerfile b/tasks/dasyn_260630_01300/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01300/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01300/environment/setup/setup.sh b/tasks/dasyn_260630_01300/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01300/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01300/tests/grade.json b/tasks/dasyn_260630_01300/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..534dfb715a3d50531458d4f01d43d5e97940e3e9 --- /dev/null +++ b/tasks/dasyn_260630_01300/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a static React site for a sports training app pricing/docs page, glassmorphism style like Notion clean layout, complex plan cards, FAQ docs sections, signup interest form with sample data only, and GSAP animations no backend" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01300/tests/grade.py b/tasks/dasyn_260630_01300/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01300/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01300/tests/test.sh b/tasks/dasyn_260630_01300/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01300/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01300/tests/webdev/__init__.py b/tasks/dasyn_260630_01300/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01300/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01300/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01300/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01300/tests/webdev/shot.py b/tasks/dasyn_260630_01300/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01300/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01300/tests/webdev/verdict.py b/tasks/dasyn_260630_01300/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01300/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01301/environment/Dockerfile b/tasks/dasyn_260630_01301/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01301/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01301/environment/setup/setup.sh b/tasks/dasyn_260630_01301/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01301/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01301/tests/grade.json b/tasks/dasyn_260630_01301/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..7ca73934bc62f0e1ddc5a6fe8ada707c5da9a3f0 --- /dev/null +++ b/tasks/dasyn_260630_01301/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build a static dark themed event website for my personal pharmacy blog called “Dose Notes Live”. It should feel clean and premium like Stripe landing pages, with soft gradients, rounded cards, crisp typography, and subtle pharmacy-inspired colors like midnight navy, violet, mint, and white. Use only vanilla HTML, CSS, and JavaScript, no backend, no login, no database, no external APIs. Mock/sample content is totally fine.\n\nEVENT CONCEPT\nA one-day online mini event for pharmacy students, new pharmacists, and healthcare writers who read my personal blog. The event is about medication safety, patient communication, and writing better pharmacy notes.\n\nPAGES / SECTIONS\n- Sticky header with logo text “Dose Notes Live”, nav links, and CTA button\n- Hero section with headline: “A practical pharmacy blog event for safer patient care”\n- Short intro paragraph and two CTA buttons: “Reserve My Spot” and “View Schedule”\n- Event stats row: 1 Day, 5 Sessions, 12 Speakers, Free Static Demo\n- About the event section with 3 clean cards\n- Schedule section with timeline cards for sample sessions\n- Featured speakers section with mock names, roles, and initials/avatar circles\n- Blog spotlight section showing 3 related personal blog post cards\n- Pharmacy topics section: medication safety, counseling tips, OTC decisions, documentation habits\n- Registration callout section, but keep it static only, no real form submission\n- Simple RSVP card with name/email fields and a button that triggers confetti and shows a success message on the page\n- FAQ accordion using vanilla JS\n- Footer with social-style text links, disclaimer, and copyright\n\nINTERACTION\nWhen the visitor clicks the RSVP / Reserve button, show a small confetti celebration and a message like “You’re on the mock guest list!” This must be front-end only. No canvas game, no third-party services. Confetti can be simple DOM elements or CSS/JS particles.\n\nSTYLE REQUIREMENTS\n- Dark mode only\n- Inspired by Stripe: gradient glow backgrounds, elegant spacing, glassy cards, subtle borders\n- Mobile friendly responsive layout\n- Smooth hover states and transitions\n- Keep it simple, polished, and readable\n- Pharmacy tone should be credible but not boring\n\nCONTENT NOTES\nUse placeholder speakers and sample blog titles. Include a small medical disclaimer: “Educational content only, not medical advice.” Deliver as a complete static site that opens locally in the browser." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01301/tests/grade.py b/tasks/dasyn_260630_01301/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01301/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01301/tests/test.sh b/tasks/dasyn_260630_01301/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01301/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01301/tests/webdev/__init__.py b/tasks/dasyn_260630_01301/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01301/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01301/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01301/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01301/tests/webdev/shot.py b/tasks/dasyn_260630_01301/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01301/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01301/tests/webdev/verdict.py b/tasks/dasyn_260630_01301/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01301/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01307/environment/Dockerfile b/tasks/dasyn_260630_01307/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01307/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01307/environment/setup/setup.sh b/tasks/dasyn_260630_01307/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01307/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01307/tests/grade.json b/tasks/dasyn_260630_01307/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..76ee48965b274192217df88cce7369473aea0da3 --- /dev/null +++ b/tasks/dasyn_260630_01307/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Astro static minimalist roofing marketplace portfolio, Dribbble vibe, mock listings, infinite scroll" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01307/tests/grade.py b/tasks/dasyn_260630_01307/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01307/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01307/tests/test.sh b/tasks/dasyn_260630_01307/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01307/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01307/tests/webdev/__init__.py b/tasks/dasyn_260630_01307/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01307/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01307/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01307/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01307/tests/webdev/shot.py b/tasks/dasyn_260630_01307/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01307/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01307/tests/webdev/verdict.py b/tasks/dasyn_260630_01307/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01307/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01331/environment/Dockerfile b/tasks/dasyn_260630_01331/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01331/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01331/environment/setup/setup.sh b/tasks/dasyn_260630_01331/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01331/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01331/tests/grade.json b/tasks/dasyn_260630_01331/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..e12f0b5e897d7b2d2a9d713654ad078a7d417f60 --- /dev/null +++ b/tasks/dasyn_260630_01331/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "build me a bold static portfolio website for a small community yoga studio, use React and Tailwind, no backend or logins or anything just sample content. I want it to feel social and welcoming like the studio is showing off its teachers, class vibe, student stories, and little video-style cards kinda inspired by YouTube layout but not actually pulling youtube videos, just static thumbnails/play buttons and fake titles. keep it simple but polished, with a strong hero section, teacher portfolio cards, class highlights, testimonials, a small schedule preview, and a gallery section. add smooth page transitions between sections/pages so it feels modern when clicking nav links, maybe home / teachers / classes / stories. colors can be warm cream with bold coral, deep green, black text, big typography, rounded cards, and nice hover states. make it responsive and ready as a static site only." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01331/tests/grade.py b/tasks/dasyn_260630_01331/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01331/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01331/tests/test.sh b/tasks/dasyn_260630_01331/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01331/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01331/tests/webdev/__init__.py b/tasks/dasyn_260630_01331/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01331/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01331/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01331/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01331/tests/webdev/shot.py b/tasks/dasyn_260630_01331/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01331/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01331/tests/webdev/verdict.py b/tasks/dasyn_260630_01331/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01331/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01336/environment/Dockerfile b/tasks/dasyn_260630_01336/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01336/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01336/environment/setup/setup.sh b/tasks/dasyn_260630_01336/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01336/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01336/tests/grade.json b/tasks/dasyn_260630_01336/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..578858e8725cea1295a39bf4be9a62cb7efea625 --- /dev/null +++ b/tasks/dasyn_260630_01336/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Tailwind ile statik bir React landing page yapar mısın, diş hekimleri için iş ilanı platformu tanıtımı olacak. Dribbble tarzı modern glassmorphism tasarım istiyorum; hero, özellikler, örnek ilan kartları, klinik/aday avantajları, fiyat/CTA bölümü olsun. Sağ altta da sadece demo çalışan küçük chatbot kutusu ekle, cevaplar mock olabilir backend istemiyorum." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01336/tests/grade.py b/tasks/dasyn_260630_01336/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01336/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01336/tests/test.sh b/tasks/dasyn_260630_01336/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01336/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01336/tests/webdev/__init__.py b/tasks/dasyn_260630_01336/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01336/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01336/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01336/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01336/tests/webdev/shot.py b/tasks/dasyn_260630_01336/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01336/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01336/tests/webdev/verdict.py b/tasks/dasyn_260630_01336/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01336/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01338/environment/Dockerfile b/tasks/dasyn_260630_01338/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01338/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01338/environment/setup/setup.sh b/tasks/dasyn_260630_01338/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01338/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01338/tests/grade.json b/tasks/dasyn_260630_01338/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..faf29ed39f62c826934936a376a96c3e4211a312 --- /dev/null +++ b/tasks/dasyn_260630_01338/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a modern static photography dashboard landing page, Amazon-inspired layout, lazy-loaded sample photo cards only" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01338/tests/grade.py b/tasks/dasyn_260630_01338/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01338/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01338/tests/test.sh b/tasks/dasyn_260630_01338/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01338/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01338/tests/webdev/__init__.py b/tasks/dasyn_260630_01338/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01338/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01338/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01338/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01338/tests/webdev/shot.py b/tasks/dasyn_260630_01338/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01338/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01338/tests/webdev/verdict.py b/tasks/dasyn_260630_01338/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01338/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01353/environment/Dockerfile b/tasks/dasyn_260630_01353/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01353/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01353/environment/setup/setup.sh b/tasks/dasyn_260630_01353/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01353/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01353/tests/grade.json b/tasks/dasyn_260630_01353/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..a3b62f5ab22dbd6a4f6b38df681cd361d1e8c243 --- /dev/null +++ b/tasks/dasyn_260630_01353/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Design a luxury Amazon inspired static landing page for premium sports real estate listings, like villas with private tennis courts, golf course homes, basketball court mansions and athlete training estates, use only mock sample properties and placeholder images, make it look expensive with gold and dark tones, big hero section, search style filters that are only visual, property cards with price, location, sport facility badges, ratings and prime style deal labels, include a simple drag and drop area where users can drag property cards into a compare shortlist box, no login, no backend, no live data, just a clean responsive front end that can run as a static website." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01353/tests/grade.py b/tasks/dasyn_260630_01353/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01353/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01353/tests/test.sh b/tasks/dasyn_260630_01353/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01353/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01353/tests/webdev/__init__.py b/tasks/dasyn_260630_01353/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01353/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01353/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01353/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01353/tests/webdev/shot.py b/tasks/dasyn_260630_01353/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01353/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01353/tests/webdev/verdict.py b/tasks/dasyn_260630_01353/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01353/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01354/environment/Dockerfile b/tasks/dasyn_260630_01354/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01354/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01354/environment/setup/setup.sh b/tasks/dasyn_260630_01354/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01354/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01354/tests/grade.json b/tasks/dasyn_260630_01354/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..186c85e55b8823e900828d5e4301aefb50245dee --- /dev/null +++ b/tasks/dasyn_260630_01354/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Buat landing page Vue static buat startup art eco/nature, vibe kayak TikTok scroll cards, ada mock chatbot guide, sample content aja" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01354/tests/grade.py b/tasks/dasyn_260630_01354/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01354/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01354/tests/test.sh b/tasks/dasyn_260630_01354/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01354/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01354/tests/webdev/__init__.py b/tasks/dasyn_260630_01354/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01354/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01354/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01354/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01354/tests/webdev/shot.py b/tasks/dasyn_260630_01354/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01354/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01354/tests/webdev/verdict.py b/tasks/dasyn_260630_01354/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01354/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01365/environment/Dockerfile b/tasks/dasyn_260630_01365/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01365/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01365/environment/setup/setup.sh b/tasks/dasyn_260630_01365/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01365/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01365/tests/grade.json b/tasks/dasyn_260630_01365/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..1739e2ca18d413c1e5777b0487d80059c48db033 --- /dev/null +++ b/tasks/dasyn_260630_01365/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "I attached a reference screenshot with a ProductHunt-style layout and I want you to create a polished static event website inspired by that clean card-based feeling, but for a premium coworking space gallery opening called \"The Workroom Sessions\". Build it as an elegant, responsive front-end only site, no backend and no real APIs, just mock/static content. The page should feel like a launch/event landing page for a coworking brand hosting an evening gallery event with photography, workspace installations, founder talks, and networking. Please make it look refined, airy, editorial, and modern, with a soft off-white background, warm neutrals, black typography, subtle orange accent buttons, rounded ProductHunt-like cards, tasteful shadows, and smooth page transitions/section transitions. I need sections for hero, event highlights, gallery preview grid, schedule/timeline, featured speakers or hosts, venue details, ticket tiers using static cards, FAQ, and footer. Include sample photos using placeholders/gradients if needed, but design the gallery area beautifully with captions like Focus Pods, Lounge Studio, Maker Table, Reading Wall, and Sunset Desk. The site should be static and ready to deploy as a simple marketing page, no login, no payments, no database, no live maps, no external booking system. If there is a CTA like Reserve Seat, it can just scroll to the ticket section or be a dummy static button. Add elegant hover states, simple fade/slide transitions between page sections, sticky top navigation, mobile-first responsive layout, and a premium coworking-space vibe. Please keep the UI simple but high fidelity, close to ProductHunt in clarity and spacing while not copying exact branding. Use realistic copy throughout, include mock event date/time/location, and make sure it works well on desktop and mobile." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01365/tests/grade.py b/tasks/dasyn_260630_01365/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01365/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01365/tests/test.sh b/tasks/dasyn_260630_01365/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01365/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01365/tests/webdev/__init__.py b/tasks/dasyn_260630_01365/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01365/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01365/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01365/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01365/tests/webdev/shot.py b/tasks/dasyn_260630_01365/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01365/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01365/tests/webdev/verdict.py b/tasks/dasyn_260630_01365/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01365/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01391/environment/Dockerfile b/tasks/dasyn_260630_01391/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01391/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01391/environment/setup/setup.sh b/tasks/dasyn_260630_01391/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01391/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01391/tests/grade.json b/tasks/dasyn_260630_01391/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..9879dccf4fb16c088956d76bb0dbbc1740e91876 --- /dev/null +++ b/tasks/dasyn_260630_01391/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a static Astro editorial website for a boutique travel agency, with a polished glassmorphism look inspired by Instagram story highlights and travel reels. I want a homepage plus article-style destination sections, curated trip cards, editor picks, a dreamy hero, and smooth scroll/hover animations that make it feel premium but not too heavy. Use only mock/static content and local assets/placeholders, no backend or APIs. Keep the layout responsive, modern, and agency-like, with soft gradients, frosted panels, rounded cards, and nice typography for a travel magazine feel." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01391/tests/grade.py b/tasks/dasyn_260630_01391/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01391/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01391/tests/test.sh b/tasks/dasyn_260630_01391/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01391/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01391/tests/webdev/__init__.py b/tasks/dasyn_260630_01391/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01391/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01391/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01391/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01391/tests/webdev/shot.py b/tasks/dasyn_260630_01391/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01391/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01391/tests/webdev/verdict.py b/tasks/dasyn_260630_01391/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01391/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01398/environment/Dockerfile b/tasks/dasyn_260630_01398/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01398/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01398/environment/setup/setup.sh b/tasks/dasyn_260630_01398/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01398/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01398/tests/grade.json b/tasks/dasyn_260630_01398/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..d3409bc6d683bb510327caf195db2b4d21bf64bf --- /dev/null +++ b/tasks/dasyn_260630_01398/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "make me a simple dark SvelteKit restaurant crowdfunding landing page for a new late-night ramen spot, kinda Netflix style with big hero poster vibes, red accents, horizontal reward cards, progress section with fake/static numbers only, menu teaser, founder story, and nice hover effects on cards/buttons. no backend or payments needed just a static site mockup" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01398/tests/grade.py b/tasks/dasyn_260630_01398/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01398/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01398/tests/test.sh b/tasks/dasyn_260630_01398/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01398/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01398/tests/webdev/__init__.py b/tasks/dasyn_260630_01398/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01398/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01398/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01398/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01398/tests/webdev/shot.py b/tasks/dasyn_260630_01398/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01398/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01398/tests/webdev/verdict.py b/tasks/dasyn_260630_01398/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01398/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01502/environment/Dockerfile b/tasks/dasyn_260630_01502/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01502/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01502/environment/setup/setup.sh b/tasks/dasyn_260630_01502/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01502/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01502/tests/grade.json b/tasks/dasyn_260630_01502/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..9076d69679785e451187dbd3f534458595f9c3e9 --- /dev/null +++ b/tasks/dasyn_260630_01502/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build me a simple static React + Tailwind website for a mental-health themed wellness restaurant called Calm Table. I mainly need a clean pricing page, kind of inspired by ProductHunt’s friendly cards and flat UI style, but softer and more calming. The restaurant offers mood-support meal plans and quiet dining packages, so make pricing cards for Starter Lunch, Mindful Dinner, and Weekly Reset. Include a hero, short intro, pricing comparison, a small FAQ, and a contact/reservation interest form with fields like name, email, preferred package, and message. The form can be visual only, no backend or real submission needed. Use mock content, pastel colors, rounded cards, simple icons, responsive layout, and keep it lightweight as a static site only." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01502/tests/grade.py b/tasks/dasyn_260630_01502/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01502/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01502/tests/test.sh b/tasks/dasyn_260630_01502/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01502/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01502/tests/webdev/__init__.py b/tasks/dasyn_260630_01502/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01502/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01502/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01502/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01502/tests/webdev/shot.py b/tasks/dasyn_260630_01502/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01502/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01502/tests/webdev/verdict.py b/tasks/dasyn_260630_01502/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01502/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01505/environment/Dockerfile b/tasks/dasyn_260630_01505/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01505/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01505/environment/setup/setup.sh b/tasks/dasyn_260630_01505/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01505/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01505/tests/grade.json b/tasks/dasyn_260630_01505/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..64bca4d13b9fc93eed6f75e90d2aaf6741b2664c --- /dev/null +++ b/tasks/dasyn_260630_01505/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a luxury Next.js landing page for an agriculture gallery, like a premium Reddit-style feed of farm estates, organic crops, greenhouses and harvest stories. Use only static mock posts and sample images, with cards, upvote/comment looking UI, category filters, elegant gold/cream/green design, and infinite scroll loading more static gallery items. Make it responsive and polished for investors and visitors." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01505/tests/grade.py b/tasks/dasyn_260630_01505/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01505/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01505/tests/test.sh b/tasks/dasyn_260630_01505/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01505/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01505/tests/webdev/__init__.py b/tasks/dasyn_260630_01505/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01505/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01505/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01505/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01505/tests/webdev/shot.py b/tasks/dasyn_260630_01505/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01505/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01505/tests/webdev/verdict.py b/tasks/dasyn_260630_01505/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01505/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01533/environment/Dockerfile b/tasks/dasyn_260630_01533/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01533/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01533/environment/setup/setup.sh b/tasks/dasyn_260630_01533/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01533/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01533/tests/grade.json b/tasks/dasyn_260630_01533/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..f9c56ea308aa12d60884f45e8efaec509eb506d5 --- /dev/null +++ b/tasks/dasyn_260630_01533/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a dark Linear-inspired static event documentation website in Next.js for a music production conference called “Signal Notes 2026”, same clean premium feel like the attached reference: black/charcoal background, subtle gradients, thin borders, glass cards, sharp typography. It should feel like docs + event site combined, with a left sidebar navigation for Overview, Schedule, Speakers, Workshops, Venue, FAQ, and Sponsor Notes, and a main content area with sections written like documentation pages. Add a hero with date/location, CTA buttons, agenda cards, speaker cards, code-block style schedule snippets, and small music waveform accents. Include a simple confetti animation when clicking “Reserve My Spot” or “Download Schedule”, but keep everything static using mock content only, no login, no payment, no backend, no APIs. Make it responsive for mobile with a clean collapsed nav." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01533/tests/grade.py b/tasks/dasyn_260630_01533/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01533/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01533/tests/test.sh b/tasks/dasyn_260630_01533/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01533/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01533/tests/webdev/__init__.py b/tasks/dasyn_260630_01533/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01533/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01533/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01533/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01533/tests/webdev/shot.py b/tasks/dasyn_260630_01533/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01533/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01533/tests/webdev/verdict.py b/tasks/dasyn_260630_01533/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01533/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01551/environment/Dockerfile b/tasks/dasyn_260630_01551/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01551/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01551/environment/setup/setup.sh b/tasks/dasyn_260630_01551/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01551/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01551/tests/grade.json b/tasks/dasyn_260630_01551/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..7a1fa92b17101535bbc874126b393b46f36caf2d --- /dev/null +++ b/tasks/dasyn_260630_01551/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "I attached a Notion-style reference for the layout. Please create a static luxury editorial changelog website for a mental-health app called Aurelia Mind. It should feel like a premium wellness journal mixed with a clean Notion updates page: left sidebar with release categories, main editorial changelog articles, soft ivory/charcoal palette, serif headlines, gold accents, calm gradients, and polished spacing. Add GSAP cursor effects like a subtle glowing follower, hover magnetic links, and smooth reveal animations while scrolling. Sections needed: hero intro, featured update, timeline of monthly mental-health feature releases, editor notes, research-inspired cards, and footer. Use only mock/static content, no login, no database, no API, no backend. Make it responsive and production-looking." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01551/tests/grade.py b/tasks/dasyn_260630_01551/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01551/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01551/tests/test.sh b/tasks/dasyn_260630_01551/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01551/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01551/tests/webdev/__init__.py b/tasks/dasyn_260630_01551/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01551/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01551/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01551/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01551/tests/webdev/shot.py b/tasks/dasyn_260630_01551/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01551/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01551/tests/webdev/verdict.py b/tasks/dasyn_260630_01551/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01551/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01556/environment/Dockerfile b/tasks/dasyn_260630_01556/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01556/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01556/environment/setup/setup.sh b/tasks/dasyn_260630_01556/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01556/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01556/tests/grade.json b/tasks/dasyn_260630_01556/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..9c363460cde82478014c4e72a1740bdd65b07c0f --- /dev/null +++ b/tasks/dasyn_260630_01556/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build a static SvelteKit documentation-style website for an HVAC jobs board called DuctWork Hub. I want it to feel a bit like Reddit in structure: clear post-style job cards, upvote-looking visual accents, community categories, sticky sidebar sections, and simple threaded FAQ blocks, but it should be totally static with mock/sample listings only. Use a clean flat design, professional blue/gray HVAC colors, good spacing, and mobile responsive layouts. Include pages/sections for how the board works, sample technician jobs, employer posting guide, pay range examples, certification tips, and a community rules/help area. Add a small confetti animation when someone clicks a “Saved job” or “I’m interested” button, but no login, backend, database, or real integrations. Make it polished enough for a marketing/docs site preview." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01556/tests/grade.py b/tasks/dasyn_260630_01556/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01556/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01556/tests/test.sh b/tasks/dasyn_260630_01556/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01556/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01556/tests/webdev/__init__.py b/tasks/dasyn_260630_01556/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01556/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01556/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01556/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01556/tests/webdev/shot.py b/tasks/dasyn_260630_01556/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01556/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01556/tests/webdev/verdict.py b/tasks/dasyn_260630_01556/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01556/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01557/environment/Dockerfile b/tasks/dasyn_260630_01557/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01557/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01557/environment/setup/setup.sh b/tasks/dasyn_260630_01557/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01557/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01557/tests/grade.json b/tasks/dasyn_260630_01557/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..8b8b2f38ddb718a2f2dd24b33d4098576b1b0507 --- /dev/null +++ b/tasks/dasyn_260630_01557/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build a brutalist Tailwind static event site for an electrical-service themed restaurant pop-up, sticky nav, YouTube-like video cards, mock content only" +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01557/tests/grade.py b/tasks/dasyn_260630_01557/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01557/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01557/tests/test.sh b/tasks/dasyn_260630_01557/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01557/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01557/tests/webdev/__init__.py b/tasks/dasyn_260630_01557/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01557/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01557/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01557/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01557/tests/webdev/shot.py b/tasks/dasyn_260630_01557/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01557/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01557/tests/webdev/verdict.py b/tasks/dasyn_260630_01557/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01557/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01558/environment/Dockerfile b/tasks/dasyn_260630_01558/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01558/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01558/environment/setup/setup.sh b/tasks/dasyn_260630_01558/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01558/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01558/tests/grade.json b/tasks/dasyn_260630_01558/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..db89a365061f2d0d273d54339f1a4ce0fe9d610d --- /dev/null +++ b/tasks/dasyn_260630_01558/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Selam, bana React ile tamamen statik çalışan basit bir restoran fan sayfası yapar mısın. Konsept doğa temalı olsun, sanki orman içinde sürdürülebilir yemek yapan küçük bir mekanın hayran sayfası gibi. Ama sayfada ayrıca restoranın işe alım tarafı da öne çıksın: garson, barista, mutfak yardımcısı gibi açık pozisyonları tanıtan küçük kartlar olsun, başvuru butonu sadece görsel dursun herhangi bir form/backend/login olmasın. Genel düzen olarak Amazon tarzı net header, kategori/kart yapısı ve kolay gezilen bir landing page hissi verebilir. GSAP ile hero giriş animasyonu, menü kartlarında ve pozisyon kartlarında hover efektleri istiyorum. İçerikler mock/static olabilir: örnek menü, örnek yorumlar, örnek ekip ilanları. Tek sayfa, responsive, temiz ve doğal yeşil/krem renklerle modern görünsün." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01558/tests/grade.py b/tasks/dasyn_260630_01558/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01558/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01558/tests/test.sh b/tasks/dasyn_260630_01558/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01558/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01558/tests/webdev/__init__.py b/tasks/dasyn_260630_01558/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01558/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01558/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01558/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01558/tests/webdev/shot.py b/tasks/dasyn_260630_01558/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01558/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01558/tests/webdev/verdict.py b/tasks/dasyn_260630_01558/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01558/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01560/environment/Dockerfile b/tasks/dasyn_260630_01560/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01560/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01560/environment/setup/setup.sh b/tasks/dasyn_260630_01560/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01560/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01560/tests/grade.json b/tasks/dasyn_260630_01560/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..61e2a7bdc6c557d0818d662c8307cade452f60a5 --- /dev/null +++ b/tasks/dasyn_260630_01560/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Merhaba, kreş ve çocuk bakım danışmanlığı yapan küçük bir ajans için Vue ile modern ama minimalist bir tanıtım sitesi istiyorum. Site tamamen statik olsun, herhangi bir backend, giriş sistemi, ödeme, veritabanı veya gerçek API bağlantısı olmasın; içerikler örnek/mock olabilir. Ajansın adı Minik Rota olsun, ailelere doğru bakıcıyı, oyun grubunu ve kreş seçimini anlatan bir ürün/hizmet showcase sayfası gibi çalışsın. Tasarımda Bilibili’den ilham alınabilir: üstte sade bir navbar, yumuşak renkli hero alanı, kartlarla öne çıkan hizmetler, yatay kaydırma hissi veren kategori bölümleri, küçük video/öneri kartlarına benzeyen ama gerçek video oynatmayan statik tanıtım kartları olsun. Genel hava çok kalabalık değil, beyaz alanı bol, pastel mavi, krem ve açık pembe tonlarıyla güven veren, ebeveynlere hitap eden bir görünüm olsun. Ana sayfada hero, güven rozetleri, hizmet paketleri, yaş gruplarına göre bakım seçenekleri, ajans süreci adım adım, danışman profilleri, aile yorumları, sık sorulan sorular ve footer bölümü istiyorum. Ayrıca ürün gösterimi gibi üç paket olsun: Başlangıç Danışmanlığı, Kreş Eşleştirme, Tam Destek Aile Planı. Her paketin kartında kısa açıklama, özellik listesi ve statik buton olsun. Mobil uyumlu ve tek sayfa landing page şeklinde hazırlanabilir. Görseller için placeholder ya da basit SVG/gradient bloklar kullanabilirsin, dış servise ihtiyaç olmasın. Kod temiz, component yapısı düzenli ve Vue projesinde direkt çalışacak şekilde olsun." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01560/tests/grade.py b/tasks/dasyn_260630_01560/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01560/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01560/tests/test.sh b/tasks/dasyn_260630_01560/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01560/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01560/tests/webdev/__init__.py b/tasks/dasyn_260630_01560/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01560/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01560/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01560/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01560/tests/webdev/shot.py b/tasks/dasyn_260630_01560/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01560/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01560/tests/webdev/verdict.py b/tasks/dasyn_260630_01560/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01560/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01567/environment/Dockerfile b/tasks/dasyn_260630_01567/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01567/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01567/environment/setup/setup.sh b/tasks/dasyn_260630_01567/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01567/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01567/tests/grade.json b/tasks/dasyn_260630_01567/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..dfebcebc41ca073a58848be3daafadea0754b7ae --- /dev/null +++ b/tasks/dasyn_260630_01567/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "أريد تصميم صفحة link-in-bio ثابتة لمجلة زراعية صغيرة اسمها Neon Farm Notes، بأسلوب cyberpunk لكن مرتبط بالزراعة: خلفية داكنة، أخضر نيون، أصفر كهربائي، خطوط شبكية خفيفة، ولمسات تشبه واجهات GitHub من ناحية البطاقات والترتيب النظيف. الصفحة تكون بسيطة وتعمل بملفات HTML/CSS/JavaScript فقط بدون أي باكند أو تسجيل دخول. المطلوب: قسم علوي فيه صورة/شعار افتراضي، عنوان قصير، وصف تحريري عن الزراعة الذكية والمزارع المستقبلية. بعدها روابط كبيرة على شكل أزرار: أحدث المقالات، دليل الزراعة المائية، قصص المزارعين، النشرة الأسبوعية، أرشيف الصور، تواصل معنا. أضف أيضاً 3 بطاقات مقالات ثابتة بمحتوى تجريبي، وكل بطاقة فيها عنوان ووسم وملخص قصير. أريد انتقالات لطيفة بين الأقسام أو عند الضغط على الروابط الداخلية، مثل fade/slide بدون تعقيد. التصميم responsive للموبايل أولاً، مع حالات hover واضحة، ولا تستخدم أي API أو بيانات حية، فقط محتوى ثابت تجريبي." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01567/tests/grade.py b/tasks/dasyn_260630_01567/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01567/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01567/tests/test.sh b/tasks/dasyn_260630_01567/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01567/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01567/tests/webdev/__init__.py b/tasks/dasyn_260630_01567/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01567/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01567/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01567/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01567/tests/webdev/shot.py b/tasks/dasyn_260630_01567/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01567/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01567/tests/webdev/verdict.py b/tasks/dasyn_260630_01567/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01567/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01569/environment/Dockerfile b/tasks/dasyn_260630_01569/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01569/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01569/environment/setup/setup.sh b/tasks/dasyn_260630_01569/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01569/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01569/tests/grade.json b/tasks/dasyn_260630_01569/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..79ac80c2a302d8bc7207a4c03e0ad5bd2d914aff --- /dev/null +++ b/tasks/dasyn_260630_01569/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a static ProductHunt-style review landing page for a bakery discovery site called CrumbRank. It should feel Swiss/minimal with lots of white space, clean typography, grid cards, sharp dividers, and orange/cream accents. Sections: hero with tagline and CTA, featured bakery of the week, ranked bakery review cards, category filters as static UI only, customer quote strip, comparison table for top bakeries, editorial section with baking trend posts, newsletter signup mock form, and footer. Include realistic sample bakery names, ratings, short reviews, tags like sourdough / croissant / cakes, and placeholder images. Add lazy-loading for images and smooth simple interactions like hover states and filter buttons visually changing state, but no backend, no login, no real API, no database. Mobile responsive and polished like a modern launch/review site." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01569/tests/grade.py b/tasks/dasyn_260630_01569/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01569/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01569/tests/test.sh b/tasks/dasyn_260630_01569/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01569/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01569/tests/webdev/__init__.py b/tasks/dasyn_260630_01569/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01569/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01569/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01569/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01569/tests/webdev/shot.py b/tasks/dasyn_260630_01569/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01569/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01569/tests/webdev/verdict.py b/tasks/dasyn_260630_01569/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01569/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01593/environment/Dockerfile b/tasks/dasyn_260630_01593/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01593/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01593/environment/setup/setup.sh b/tasks/dasyn_260630_01593/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260630_01593/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260630_01593/tests/grade.json b/tasks/dasyn_260630_01593/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..de8bf82d672206301cb105747a4a179246ce95e3 --- /dev/null +++ b/tasks/dasyn_260630_01593/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a corporate-style static landing page in Nuxt for a restaurant membership program called \"TableCircle Club\". The design should feel inspired by Reddit’s community layout: clean card-based sections, subtle upvote-style visual accents, discussion/thread-like testimonial cards, and a friendly membership community vibe, but make it polished for a premium restaurant brand. Sections needed: Hero with headline \"Join the TableCircle Club\" and CTA buttons, Membership Benefits cards, How It Works in 3 steps, Featured Member Perks, Community Highlights with mock/static comments from diners, Pricing or membership tiers, FAQ, and Footer. Use warm restaurant colors like cream, deep burgundy, charcoal, and gold accents. Add lazy-loading for food/gallery images and use only static/sample content, no backend, no login, no database, no real API. Make it fully responsive for mobile/tablet/desktop and ready to deploy as a static site." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01593/tests/grade.py b/tasks/dasyn_260630_01593/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01593/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01593/tests/test.sh b/tasks/dasyn_260630_01593/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01593/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260630_01593/tests/webdev/__init__.py b/tasks/dasyn_260630_01593/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260630_01593/tests/webdev/eval_rubric.py b/tasks/dasyn_260630_01593/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260630_01593/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260630_01593/tests/webdev/shot.py b/tasks/dasyn_260630_01593/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260630_01593/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260630_01593/tests/webdev/verdict.py b/tasks/dasyn_260630_01593/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260630_01593/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260630_01594/environment/Dockerfile b/tasks/dasyn_260630_01594/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260630_01594/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260630_01594/tests/grade.json b/tasks/dasyn_260630_01594/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..b9a241b8fed55b8692f8a6cbce1870b0165fbac2 --- /dev/null +++ b/tasks/dasyn_260630_01594/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "I have a moodboard attached for a botanical outdoor wedding festival vibe. Please build a polished static SvelteKit marketing site for “Willow & Wren Wedding Weekend”, a nature-inspired entertainment/wedding event landing page that can be deployed on Vercel with no backend or external services. The page should feel like a premium wedding website mixed with a small music-and-dining festival: soft greens, ivory, wildflowers, paper textures, elegant serif typography, and warm sunset photography placeholders. I want a complex scroll-driven experience with a sticky story timeline, parallax floral layers, animated section reveals, a ceremony-to-afterparty schedule, couple story, venue highlights, acoustic performance lineup, menu preview, guest dress-code guide, travel/accommodation cards, photo gallery using static sample images, FAQ, and a final RSVP-style call-to-action that is only decorative/static, not a real form submission. Use mock text and sample content everywhere. Make it responsive, accessible, fast, and ready as a static site only." +} \ No newline at end of file diff --git a/tasks/dasyn_260630_01594/tests/grade.py b/tasks/dasyn_260630_01594/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260630_01594/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260630_01594/tests/test.sh b/tasks/dasyn_260630_01594/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260630_01594/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00113/environment/Dockerfile b/tasks/dasyn_260638_00113/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00113/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00113/environment/setup/setup.sh b/tasks/dasyn_260638_00113/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00113/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00113/tests/grade.json b/tasks/dasyn_260638_00113/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..bac4d53b0b8d51da5bb62e55e72f899270633cbf --- /dev/null +++ b/tasks/dasyn_260638_00113/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "项目需求文档|请制作一个纯静态的高端 HVAC 暖通空调会员制服务落地页网站,品牌名暂定为「Aurum Air Club」。整体必须是 art-deco / 装饰艺术风格:黑金配色、象牙白、深墨绿、几何线条、拱门、金属描边、复古酒店大堂感,但内容是现代家庭和商业暖通维护会员服务。请用原生 HTML + CSS + vanilla JavaScript 完成,不要使用后端、数据库、登录、支付、真实接口或任何实时数据;所有价格、会员权益、案例、评价、日程都用静态 mock 内容即可。网站需要像 GitHub 上优秀开源项目主页/README 那样结构清晰:顶部有醒目的项目式介绍、功能亮点、套餐对比、安装/使用说明风格的服务流程区、FAQ 和版本更新式的维护计划说明,但视觉上不是程序员风,而是奢华 Art Deco。\\n\\n交付要求:一个可直接打开的静态站点,建议文件结构:index.html、styles.css、script.js、assets 占位图片或 CSS 图形均可。不要依赖外部服务,不要调用真实地图、天气、支付、CRM、表单提交、第三方 API。表单如果出现,只做前端静态展示和简单提示,比如点击按钮显示“已记录示例请求”,不能真的提交。\\n\\n页面定位:这是一个 HVAC 公司推广“年度会员保养计划”的 landing page,目标客户包括高端住宅业主、小型精品酒店、办公室、零售店。用户进入页面后要感觉这是一个可靠、昂贵、专业、全年无忧的暖通会员俱乐部。文案要中文为主,可以适当有英文小标题,例如 “Annual Comfort Membership”。\\n\\n必须包含的页面/区块:\\n1. 顶部导航:Logo「Aurum Air Club」、导航项:会员权益、服务流程、套餐、案例、常见问题、预约体验。导航固定在顶部,滚动后有玻璃拟态/深色半透明效果。\\n2. Hero 首屏:大标题例如“把全年舒适交给一张会员卡”,副标题说明提供空调、采暖、新风、热泵、商用 HVAC 的年度巡检与维护。右侧/背景可以做 Art Deco 几何风格的空调出风口、温控器、风流线条插画,不需要真实图片。CTA 按钮:查看会员方案、预约静态演示。加入一个高级会员卡视觉:金色边框、会员编号、年份 2026、权益标签。\\n3. 会员信任条:展示静态数字,比如“24h 内优先响应示例”“4 次年度巡检”“120+ 静态客户案例”“98% 示例满意度”,明确是展示型内容也可以。\\n4. 会员权益区:用卡片列出:春季制冷前检查、秋季采暖前检查、滤网与风道建议、热泵效率评估、商用系统巡检清单、紧急工单优先排队、备件折扣展示、舒适度报告样例。\\n5. 套餐对比区:三档会员:Bronze Comfort、Gold Residence、Platinum Commercial。每档要有价格占位、适合对象、巡检次数、响应优先级、包含服务、增值权益。重点突出 Gold 或 Platinum。不要做真实购买,只放静态按钮“选择此方案”。\\n6. 服务流程区:像 GitHub README 的步骤说明一样清楚:Step 01 初始系统评估、Step 02 建立设备档案、Step 03 季节性巡检、Step 04 发送静态舒适报告、Step 05 下一年度优化建议。可以做类似代码块/终端块的设计,但内容是服务清单,不要真的运行代码。\\n7. Page transitions / 页面过渡:网站虽然是单页,也要有明显的页面切换体验。请实现顶部导航点击不同 section 时的平滑滚动、section 进入时淡入上移、会员卡/套餐卡 hover 时有优雅的 Art Deco 金线过渡;可以加一个全屏或半屏的金色几何 wipe transition,在点击导航或 CTA 跳转锚点时短暂出现,让人感觉像多页面切换。必须用 vanilla JS 实现。\\n8. 案例展示区:静态案例 4 个,例如“湖畔别墅热泵维护”“精品酒店公共区域新风巡检”“设计事务所办公室恒温优化”“高端零售店夜间维护”。每个案例有问题、服务、结果三行,结果数据为样例。\\n9. 设备覆盖区:展示中央空调、分体空调、热泵、锅炉/采暖、新风系统、商用 rooftop unit、温控器、空气净化模块等,做成装饰艺术徽章或网格。\\n10. 舒适报告样例区:做一张静态报告 UI,包含温度稳定性、能耗趋势、滤网状态、下一次保养建议,不要真实图表库,可以用 CSS 条形图/进度条。\\n11. 推荐语区:3-5 条静态客户评价,客户身份虚构,比如“精品酒店运营经理”“复式住宅业主”“画廊负责人”。\\n12. FAQ:至少 8 个问题,内容包括会员是否包含维修材料、是否适合老设备、商用客户如何安排巡检、是否支持多台设备、是否可以先体验、价格是否固定等。FAQ 可以点击展开/收起,用原生 JS。\\n13. 预约体验区:放一个静态表单:姓名、物业类型、设备数量、希望服务、留言。按钮点击后只显示前端成功提示,不发送请求。\\n14. Footer:包含品牌介绍、静态联系方式占位、服务城市占位、GitHub reference 风格的小链接文字如“Static site concept / README inspired layout”,但不要真的依赖 GitHub 数据。\\n\\n设计细节:\\n- 视觉关键词:Art Deco、黑金、几何分割、对称构图、细线边框、豪华会员卡、复古电梯门/酒店大堂风、暖通设备科技感。\\n- 字体:可以使用系统字体,不要必须加载外部字体。标题需要有高级感,字距略大。\\n- 背景:深色渐变 + 金色线框图案 + 柔和光晕。\\n- 响应式:手机、平板、桌面都要好看;移动端导航可折叠或简化。\\n- 动效:首屏进入动画、滚动 reveal、按钮 hover、卡片 hover、FAQ 展开、锚点页面过渡。动效要优雅,不要太花。\\n- 可访问性:按钮可聚焦,颜色对比合理,表单 label 完整,减少动效用户可以尽量不被强制干扰。\\n\\n内容语气:专业、高端、可靠,像会员制酒店管家 + HVAC 工程顾问。不要写成普通维修小广告。可以有少量英文标签提升质感,但主要内容必须是中文。\\n\\n技术限制再次强调:只做静态前端,不要登录系统、不要用户账户、不要后台管理、不要数据库、不要支付、不要真实预约接口、不要地图 API、不要天气 API、不要 WebGL/Three.js/3D、不要游戏或物理效果。所有内容都是静态示例。" +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00113/tests/grade.py b/tasks/dasyn_260638_00113/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00113/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00113/tests/test.sh b/tasks/dasyn_260638_00113/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00113/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00113/tests/webdev/__init__.py b/tasks/dasyn_260638_00113/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00113/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00113/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00113/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00113/tests/webdev/shot.py b/tasks/dasyn_260638_00113/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00113/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00113/tests/webdev/verdict.py b/tasks/dasyn_260638_00113/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00113/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00114/environment/Dockerfile b/tasks/dasyn_260638_00114/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00114/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00114/environment/setup/setup.sh b/tasks/dasyn_260638_00114/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00114/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00114/tests/grade.json b/tasks/dasyn_260638_00114/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..e865d6dee8c18c5df3386bfae9a945a64c92a07d --- /dev/null +++ b/tasks/dasyn_260638_00114/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "I need you to build a full static Astro marketing website for a retro-style fitness review site, kind of inspired by the fast swipeable energy of TikTok but NOT a social app and no backend. The site should be called something like RepCheck Club and it reviews home workout programs, fitness apps, resistance bands, treadmills, dumbbell sets, protein snacks, and old-school workout gadgets. I want it to feel like an 80s/90s gym magazine mixed with short-form video culture: neon accents, grainy poster textures, chunky typography, rating cards, bold stickers, VHS-style labels, and punchy sections that make people want to scroll. It must be a static front-end only site, so use mock/sample review data inside the project and do not connect to any real API, database, login, comments, payments, accounts, or live feeds. Make the homepage feel like a landing page for the review brand: hero section, featured review carousel or horizontal cards, top rated products, trending workout categories, comparison strip, editor picks, testimonial quotes, newsletter-style signup form that is only visual/non-functional, and a strong footer. Add separate-looking sections for short review snippets that visually reference TikTok vertical cards, but they can just be static cards with thumbnails/placeholders, fake captions, ratings, tags, and buttons. I also want lazy-loading behavior for images/cards so the page feels polished: use native lazy loading or Astro-friendly lazy loading patterns, skeleton placeholders if reasonable, and avoid loading everything heavy at once. Please include responsive design for mobile, tablet, and desktop, with mobile being especially strong because this should feel swipe/scroll friendly. Every button, filter chip, tab, accordion, comparison toggle, and menu should work on the front end only with local static state, no server. Category filters can filter the mock review cards client-side. Add review scores, pros and cons, star ratings, badges like “Best Budget”, “Most Viral”, “Retro Pick”, and “Beginner Friendly”. Keep it medium complexity, clean file structure, reusable components, accessible HTML, good contrast, keyboard-friendly interactions, and nice micro animations. Please do not make it modern minimal; I specifically want retro fitness review-site vibes with a marketing-site structure, polished enough to look like a real launch page, but completely static and able to build without external services." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00114/tests/grade.py b/tasks/dasyn_260638_00114/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00114/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00114/tests/test.sh b/tasks/dasyn_260638_00114/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00114/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00114/tests/webdev/__init__.py b/tasks/dasyn_260638_00114/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00114/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00114/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00114/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00114/tests/webdev/shot.py b/tasks/dasyn_260638_00114/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00114/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00114/tests/webdev/verdict.py b/tasks/dasyn_260638_00114/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00114/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00115/environment/Dockerfile b/tasks/dasyn_260638_00115/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00115/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00115/environment/setup/setup.sh b/tasks/dasyn_260638_00115/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00115/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00115/tests/grade.json b/tasks/dasyn_260638_00115/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..4557dcf4a6e09b1ebfac8dc1ebcd74267a9d9b02 --- /dev/null +++ b/tasks/dasyn_260638_00115/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Flat Stripe-style community pharmacy portfolio, static mock content, confetti" +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00115/tests/grade.py b/tasks/dasyn_260638_00115/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00115/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00115/tests/test.sh b/tasks/dasyn_260638_00115/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00115/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00115/tests/webdev/__init__.py b/tasks/dasyn_260638_00115/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00115/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00115/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00115/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00115/tests/webdev/shot.py b/tasks/dasyn_260638_00115/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00115/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00115/tests/webdev/verdict.py b/tasks/dasyn_260638_00115/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00115/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00122/environment/Dockerfile b/tasks/dasyn_260638_00122/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00122/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00122/environment/setup/setup.sh b/tasks/dasyn_260638_00122/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00122/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00122/tests/grade.json b/tasks/dasyn_260638_00122/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..7e39c5bc69e416a64e9dd475e65100e5882d341d --- /dev/null +++ b/tasks/dasyn_260638_00122/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a polished static landing page / marketing website for a coworking space brand called ThreadDesk Collective. I want the overall inspiration to feel like Reddit’s community-first layout but turned into a premium material-design coworking website: card-based sections, soft shadows, rounded surfaces, vote-style social proof badges, topic/community tags, pinned announcement cards, and a scrolling feed feeling without actually using any live data. Build it as a fully responsive React static site using GSAP for smooth animations and an infinite-scroll style experience where more prewritten static sections/cards continue loading/revealing as the user scrolls. No backend, no auth, no booking system, no API calls, no database, just mock/static content. Visual Style: Material design, warm off-white background, muted orange, graphite, teal accent, lots of elevated cards, sticky top navigation, soft gradients, clean icons, subtle micro-interactions. Page Goal: make visitors want to tour or join the coworking space. Header: logo ThreadDesk, nav links Spaces, Amenities, Community, Pricing, Events, FAQ, CTA button “Book a Tour” but it only scrolls to a static contact card. Hero Section: headline “A Coworking Space Built Like Your Favorite Online Community, But In Real Life.” Subheadline about desks, studios, founders, freelancers, quiet zones, and community rituals. Include CTA buttons “Explore Memberships” and “See The Vibe”. Add right-side mock community dashboard card with posts like “Pinned: Monday founder breakfast”, “Hot desk availability”, “Show & Tell Fridays”, upvote numbers, comment chips, member avatars. Infinite Scroll Feed Concept: after the hero, create a continuous vertical feed of static content cards that animate in with GSAP as you scroll. Cards should include workspace photos placeholders, testimonial snippets, event promos, amenity highlights, pricing mini cards, community prompts, neighborhood guides, and member spotlights. It should feel like browsing a curated coworking subreddit, but branded and elegant. Sections Needed: 1) Community Feed strip with static post cards and tags like #focus, #founders, #designers, #wellness. 2) Spaces section with cards for Hot Desks, Dedicated Desks, Private Studios, Podcast Room, Wellness Nook, Rooftop Lounge. 3) Amenities grid with material icons style: fiber internet, phone booths, meeting rooms, espresso bar, mail handling, printing, lockers, nap pods. 4) Why Members Stay section with metric cards: 180+ members, 42 weekly collabs, 24/7 access, 96% renewal rate, all static. 5) Pricing section with three membership cards: Day Pass, Flex Desk, Studio Plus, with feature lists and highlighted recommended plan. 6) Events section styled like Reddit pinned posts: Founder Breakfast, Demo Night, Quiet Coworking Sprint, Freelance Clinic. 7) Testimonials as comment-thread cards with fake names and roles. 8) FAQ accordion-like static UI is okay, can be non-functional or simple front-end only. 9) Final CTA with contact details mock address and a simple static form layout that does not submit anywhere. Animation requirements: use GSAP for hero entrance, sticky cards, staggered reveal of feed cards, floating badge animations, smooth scroll-triggered sections, and infinite-scroll illusion by rendering multiple batches of static cards. Make it feel complex and premium but keep performance reasonable. Include mobile layout with bottom sticky CTA bar. Do not use external services or live maps; use a stylized static map card/placeholder instead. Deliverable should be a beautiful static React website with sample copy and placeholder images/gradient blocks where needed." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00122/tests/grade.py b/tasks/dasyn_260638_00122/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00122/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00122/tests/test.sh b/tasks/dasyn_260638_00122/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00122/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00122/tests/webdev/__init__.py b/tasks/dasyn_260638_00122/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00122/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00122/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00122/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00122/tests/webdev/shot.py b/tasks/dasyn_260638_00122/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00122/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00122/tests/webdev/verdict.py b/tasks/dasyn_260638_00122/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00122/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00125/environment/Dockerfile b/tasks/dasyn_260638_00125/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00125/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00125/environment/setup/setup.sh b/tasks/dasyn_260638_00125/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00125/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00125/tests/grade.json b/tasks/dasyn_260638_00125/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..3dc8a783887d807f4f5ece1019a0a6f5782402ad --- /dev/null +++ b/tasks/dasyn_260638_00125/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Tailwind ile statik bir React sitesi istiyorum, şehirler arası taşınma firmaları için küçük bir etkinlik/rehber sayfası gibi olsun. Konu: \"2026 Evden Eve Nakliyat Tanıtım Günleri\". Site tek sayfa olabilir, neomorphism tarzında yumuşak gölgeli kartlar, açık gri arka plan, modern ama sade görünüm istiyorum. Üstte hero alanı, etkinlik tarihi ve kısa açıklama, altında Wikipedia sayfalarındaki gibi düzenli bilgi kutusu hissi veren bir bölüm olsun ama daha şık tasarımla. Sonra örnek nakliyat firmaları dizini olsun: firma adı, hizmet verdiği şehirler, kısa açıklama, puan gibi tamamen statik sahte bilgiler yeterli. Kartlara hover animasyonu, sayfa açılışında hafif fade/slide animasyonları ve butonlarda küçük geçiş efektleri ekle. Ayrıca program akışı, sık sorulan sorular ve iletişim yerine sadece statik adres/telefon bilgisi olan footer olsun. Backend, giriş sistemi, veritabanı veya gerçek API kullanma, her şey örnek içerikle çalışsın." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00125/tests/grade.py b/tasks/dasyn_260638_00125/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00125/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00125/tests/test.sh b/tasks/dasyn_260638_00125/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00125/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00125/tests/webdev/__init__.py b/tasks/dasyn_260638_00125/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00125/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00125/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00125/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00125/tests/webdev/shot.py b/tasks/dasyn_260638_00125/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00125/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00125/tests/webdev/verdict.py b/tasks/dasyn_260638_00125/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00125/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00140/environment/Dockerfile b/tasks/dasyn_260638_00140/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00140/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00140/environment/setup/setup.sh b/tasks/dasyn_260638_00140/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00140/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00140/tests/grade.json b/tasks/dasyn_260638_00140/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..0c955bc666629948e29370c7b02eeb6fe5295c62 --- /dev/null +++ b/tasks/dasyn_260638_00140/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "# مطلوب إنشاء موقع توثيقي ثابت Documentation Website لمطعم بطابع إسكندنافي + خدمات السباكة الداخلية\n\nأريد تصميم وتنفيذ موقع Static Website كامل كأنه صفحة توثيق احترافية منشورة من GitHub/README ولكن بشكل أجمل وحديث. الفكرة غريبة شوي: مطعم اسكندنافي اسمه \"Nord Pipe Kitchen\" يشرح للزوار نظام السباكة والنظافة المائية داخل المطعم، وكيف يتم تجهيز المطبخ، غسل الأدوات، إدارة المياه، الصيانة الوقائية، ومعايير السلامة. الموقع ليس تطبيق حقيقي ولا يحتاج أي Backend. فقط Front-End ثابت بمحتوى Mock/Sample.\n\n## الهدف العام\nبناء صفحة ويب واحدة أو عدة أقسام داخل Landing/Docs Site تعرض معلومات المطعم وخدمات السباكة الداخلية بأسلوب Scandinavian: بسيط، أبيض، هادئ، مساحات واسعة، خطوط نظيفة، ألوان خشب فاتح، أزرق رمادي، أخضر نعناعي، رمادي بارد، مع صور/بطاقات وهمية أو placeholders فقط.\n\n## مهم جداً\n- الموقع Static فقط.\n- لا تستخدم API حقيقية.\n- لا يوجد تسجيل دخول.\n- لا يوجد Database.\n- لا يوجد لوحة تحكم.\n- لا يوجد CRUD.\n- لا يوجد دفع أو طلبات حقيقية.\n- لا تستخدم WebGL أو 3D أو ألعاب أو Canvas.\n- أي بيانات تكون Static Mock داخل الملفات.\n- الشات بوت يكون Fake/Static Chatbot UI فقط، يرد من ردود جاهزة محلياً بدون ذكاء اصطناعي حقيقي وبدون اتصال خارجي.\n\n---\n\n# Structure المطلوب\n\n## 1. Header / Navigation\n- شعار نصي بسيط: Nord Pipe Kitchen\n- وصف صغير: Scandinavian Restaurant Plumbing Guide\n- روابط تنقل:\n - Overview\n - Kitchen Plumbing\n - Maintenance\n - Safety Docs\n - FAQ\n - Chat Assistant\n - GitHub Style Notes\n- زر CTA صغير: View Guide\n- اجعل الهيدر Sticky بشكل ناعم مع ظل خفيف جداً.\n\n## 2. Hero Section\nالعنوان الرئيسي بالعربي:\n\"دليل سباكة مطعم إسكندنافي بنظام بسيط ونظيف\"\n\nنص فرعي:\n\"موقع توثيقي ثابت يشرح كيف يحافظ مطعم Nord Pipe Kitchen على تدفق المياه، نظافة المطبخ، صيانة الأحواض، وفحص خطوط التصريف بطريقة عملية وهادئة.\"\n\nأزرار:\n- ابدأ قراءة الدليل\n- افتح مساعد السباكة\n\nإضافة بطاقة جانبية شكلها مثل GitHub Repo Card تحتوي:\n- Repository: nord-pipe-kitchen-docs\n- Status: Static Preview\n- Version: v1.0.0\n- Last Updated: 2026\n- License: Sample Docs\n\n## 3. Overview Section\nبطاقات مختصرة:\n- نظام المياه الباردة والساخنة\n- أحواض التحضير والغسيل\n- فلاتر المطبخ\n- تصريف الدهون\n- الصيانة اليومية\n- فحص التسريب\n\nكل بطاقة تحتوي أيقونة بسيطة نصية أو SVG عادي، عنوان، وصف قصير.\n\n## 4. Restaurant Context Section\nاعرض قصة قصيرة عن المطعم:\nمطعم صغير يقدم أكلات شمالية، يعتمد على مطبخ مفتوح، لذلك يهتم بالنظافة، هدوء التصميم، وترتيب منطقة الغسيل. استخدم تصميم يشبه كتالوج Scandinavian مع صور وهمية مثل مستطيلات بلون خشب فاتح.\n\nأضف قائمة \"قيم التشغيل\":\n- الهدوء في الخدمة\n- نظافة مرئية للعميل\n- تقليل هدر المياه\n- صيانة مبكرة قبل الأعطال\n- توثيق كل خطوة بشكل واضح\n\n## 5. Kitchen Plumbing Docs\nقسم توثيقي مفصل مثل صفحة Documentation:\n\n### Water Flow Map\nاعرض خريطة نصية/بطاقات توضح المسار:\nمدخل المياه → فلتر أولي → سخان آمن → أحواض التحضير → غسالة الصحون → مصيدة الدهون → التصريف.\n\n### Sink Stations\nجدول ثابت يحتوي:\n- Station Name\n- Usage\n- Daily Check\n- Risk Level\nمثلاً:\nPrep Sink / غسل الخضار / فحص الصنبور / Low\nDish Sink / تنظيف أدوات / فحص انسداد / Medium\nHand Wash / غسل اليدين / صابون وماء / Low\nFloor Drain / تصريف أرضي / رائحة أو انسداد / Medium\n\n### Preventive Maintenance\nTimeline أفقي أو عمودي:\n- كل صباح: فحص سريع للصنابير\n- بعد الظهر: تنظيف مصفاة الحوض\n- نهاية اليوم: فحص مصيدة الدهون\n- أسبوعياً: اختبار التصريف\n- شهرياً: مراجعة الوصلات\n\n## 6. Safety Documentation\nقسم safety بأسلوب cards:\n- لا تخلط مواد التنظيف القوية قرب منطقة الطعام\n- أغلق صمام المياه عند وجود تسريب واضح\n- لا تترك الدهون تدخل التصريف مباشرة\n- استخدم لافتة أرضية عند وجود ماء\n- بلّغ مسؤول الصيانة عند سماع صوت غير طبيعي\n\nأريد شكل Warning / Note / Tip مثل GitHub markdown callouts:\n> NOTE\nمعلومة هادئة باللون الأزرق.\n\n> WARNING\nتحذير بلون أصفر/برتقالي ناعم.\n\n> TIP\nنصيحة بلون أخضر فاتح.\n\n## 7. Static Chatbot Interaction\nأريد زر Chat Assistant ثابت في أسفل الصفحة على اليمين. عند الضغط يفتح نافذة صغيرة:\nالعنوان: مساعد السباكة للمطعم\nالحالة: Static demo\n\nداخل الشات:\n- رسائل ترحيب جاهزة.\n- أزرار أسئلة سريعة:\n 1. ماذا أفعل عند انسداد الحوض؟\n 2. كيف أفحص تسريب بسيط؟\n 3. متى ننظف مصيدة الدهون؟\n 4. ما خطوات نهاية اليوم؟\n- عند الضغط على أي سؤال تظهر إجابة جاهزة بدون API.\n- أضف Input شكلي فقط يمكن أن يقبل نص ويرد برد عام ثابت مثل: \"هذه نسخة ثابتة، استخدم الأسئلة السريعة للحصول على إرشادات نموذجية.\" \n- لا يوجد اتصال خارجي ولا OpenAI ولا أي خدمة.\n\n## 8. GitHub Reference Style\nأضف قسم يشبه README:\n\n```md\n# Nord Pipe Kitchen Docs\nStatic documentation for restaurant plumbing routines.\n\n## Sections\n- Overview\n- Kitchen Plumbing\n- Maintenance\n- Safety\n- FAQ\n\n## Usage\nOpen the static page in browser.\n```\n\nوتحتها بطاقات:\n- File Structure\n- Design Tokens\n- Content Model\n- Static Chatbot Rules\n\nاجعلها تبدو مثل GitHub documentation لكن بتصميم مطعم اسكندنافي وليس شكل تقني جاف جداً.\n\n## 9. FAQ\nأسئلة وأجوبة ثابتة Accordion:\n- هل الموقع يعتمد على بيانات حقيقية؟ لا، محتوى تجريبي ثابت.\n- هل الشات بوت حقيقي؟ لا، تفاعل ثابت فقط.\n- هل يمكن استخدامه كصفحة تدريب داخل مطعم؟ نعم كنموذج عرض.\n- هل يحتاج سيرفر؟ لا، يمكن فتحه كموقع Static.\n- هل التصميم مناسب للموبايل؟ نعم لازم Responsive.\n\n## 10. Footer\n- شعار صغير\n- روابط داخلية\n- عبارة: Built as a static GitHub-style documentation site\n- سنة 2026\n\n---\n\n# Visual Style\n- Scandinavian design.\n- Minimal clean layout.\n- خلفية Off-white.\n- بطاقات بيضاء بحواف دائرية.\n- ألوان هادئة: #F7F5EF, #E8EEF0, #9BB7B4, #D8C7A3, #2F3A3D.\n- استخدم مساحات كبيرة، ظلال خفيفة، حدود رفيعة.\n- الخط يكون واضح وحديث، يدعم العربية جيداً.\n- الاتجاه RTL للنص العربي مع إمكانية ظهور كلمات إنجليزية داخلية بشكل مرتب.\n- لا تستخدم صور خارجية إلزامية؛ placeholders أو gradients كافية.\n\n# Responsive\n- Desktop: Layout واسع مع sidebar docs أو cards grid.\n- Tablet: أقسام مرنة.\n- Mobile: Navbar تتحول لقائمة بسيطة، البطاقات عمود واحد، الشات لا يغطي الصفحة كلها.\n\n# المطلوب تسليمه\n- موقع Front-End ثابت كامل.\n- محتوى عربي واضح وليس Lorem Ipsum.\n- تفاعل بسيط للـ Accordion والـ Chatbot فقط.\n- كود مرتب وسهل التعديل.\n- لا تضيف أي Backend أو Database أو Auth.\n- كل البيانات تكون داخل ملفات المشروع كـ Mock Static Content.\n\nأريده يبدو كأنه مشروع جاهز للعرض في GitHub Pages: مطعم + دليل سباكة + توثيق + مساعد دردشة ثابت، بتصميم إسكندنافي أنيق وهادئ." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00140/tests/grade.py b/tasks/dasyn_260638_00140/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00140/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00140/tests/test.sh b/tasks/dasyn_260638_00140/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00140/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00140/tests/webdev/__init__.py b/tasks/dasyn_260638_00140/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00140/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00140/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00140/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00140/tests/webdev/shot.py b/tasks/dasyn_260638_00140/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00140/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00140/tests/webdev/verdict.py b/tasks/dasyn_260638_00140/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00140/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00147/environment/Dockerfile b/tasks/dasyn_260638_00147/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00147/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00147/environment/setup/setup.sh b/tasks/dasyn_260638_00147/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00147/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00147/tests/grade.json b/tasks/dasyn_260638_00147/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..e942f4aa9eeacb14f1d8df8dfd14c0b0c97201e4 --- /dev/null +++ b/tasks/dasyn_260638_00147/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "I need a simple elegant static portfolio website in Nuxt for my online bakery course brand. Make it look like a polished course creator site with sections for hero, about the instructor, course modules, student results, pricing card, FAQ and contact info. Please include a dark mode toggle, use only mock/static content, and add a small reference-style info block inspired by Wikipedia explaining basic bread making terms. No backend or login needed, just a clean responsive static site." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00147/tests/grade.py b/tasks/dasyn_260638_00147/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00147/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00147/tests/test.sh b/tasks/dasyn_260638_00147/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00147/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00147/tests/webdev/__init__.py b/tasks/dasyn_260638_00147/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00147/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00147/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00147/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00147/tests/webdev/shot.py b/tasks/dasyn_260638_00147/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00147/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00147/tests/webdev/verdict.py b/tasks/dasyn_260638_00147/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00147/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00171/environment/Dockerfile b/tasks/dasyn_260638_00171/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00171/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00171/environment/setup/setup.sh b/tasks/dasyn_260638_00171/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00171/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00171/tests/grade.json b/tasks/dasyn_260638_00171/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..db82d9afb9ef4ed68a3819d1e3dc761694e7938d --- /dev/null +++ b/tasks/dasyn_260638_00171/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "عايزك تبني لي موقع بورتفوليو ثابت بـ Astro لمجتمع سفر اسمه مثلا Nomad Circles، الفكرة إنه يعرض رحلات وتجارب ناس مسافرين ومجموعات صغيرة زي إحساس Airbnb بس مش نسخ مباشر، يعني كروت أماكن وتجارب وقصص أعضاء المجتمع بشكل أنيق جدا. الموقع كله يكون Static فقط من غير تسجيل دخول ولا داتا بيز ولا API ولا باك اند، أي بيانات أو صور أو تقييمات تكون mock content عادي داخل المشروع. عايز الستايل يكون جراديانت واضح وفخم، ألوان مبهجة للسفر زي أزرق وبنفسجي وبرتقالي مع مساحات بيضا، والصفحة تحسها احترافية ومعقدة مش مجرد landing page بسيطة. اعمل hero قوي فيه عنوان وتسويق للمجتمع وزرار استكشاف وزرار مشاهدة القصص، وبعده أقسام: أماكن مميزة، رحلات مجتمعية قادمة لكن كبيانات وهمية، قصص المسافرين، خريطة مصورة أو section بصري عادي بدون خرائط حقيقية، إحصائيات، testimonials، pricing أو membership cards بشكل static، وFAQ. كمان عايز chatbot widget في الركن يكون تفاعلي فرونت إند فقط، يفتح ويقفل ويرد بردود جاهزة عن السفر والحجوزات والمجتمع والأسئلة الشائعة من غير أي ذكاء اصطناعي حقيقي أو اتصال خارجي. اهتم جدا بالـ responsive design للموبايل والتابلت، animations خفيفة، hover states، navigation sticky، sections كثيرة ومنظمة، accessibility كويسة، وخلّي الكود نظيف بمكونات Astro مرتبة. المهم الموقع يشتغل بالكامل كـ static site بدون أي خدمات خارجية، ويكون شكله قريب من مواقع السفر الكبيرة من ناحية الجودة والثقة والإلهام." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00171/tests/grade.py b/tasks/dasyn_260638_00171/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00171/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00171/tests/test.sh b/tasks/dasyn_260638_00171/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00171/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00171/tests/webdev/__init__.py b/tasks/dasyn_260638_00171/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00171/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00171/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00171/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00171/tests/webdev/shot.py b/tasks/dasyn_260638_00171/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00171/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00171/tests/webdev/verdict.py b/tasks/dasyn_260638_00171/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00171/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00185/environment/Dockerfile b/tasks/dasyn_260638_00185/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00185/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00185/environment/setup/setup.sh b/tasks/dasyn_260638_00185/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00185/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00185/tests/grade.json b/tasks/dasyn_260638_00185/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..73ca5d4daf27d55f1af2f48776ea538d8afac8c4 --- /dev/null +++ b/tasks/dasyn_260638_00185/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a premium static landing page for a fictional political campaign called \"Future Civic Alliance\" focused on technology, digital inclusion, cybersecurity awareness, AI literacy, and modern public services. The visual direction should feel like an art-deco campaign poster redesigned for a modern tech audience, with inspiration from polished Dribbble landing page shots: geometric gold linework, deep navy and black backgrounds, ivory typography, emerald accents, symmetrical layouts, elegant borders, subtle grain texture, and dramatic editorial spacing. This must be a pure front-end static website only, no backend, no database, no login, no real donation processing, no external API, and no live data. Use static/mock/sample content where needed. Build it as a responsive React landing page with GSAP animations.\n\nWebsite goal: make the campaign feel visionary, trustworthy, civic, and technology-forward without looking like a generic SaaS page. It should look like a refined political movement for the digital age. Please create complete page sections and realistic copy, not placeholders like lorem ipsum.\n\nMain sections:\n1. Hero Section\n- Full screen or near full screen art-deco inspired hero.\n- Campaign name: Future Civic Alliance.\n- Main headline: \"A Smarter Public Future, Built With People First.\"\n- Supporting text about using technology to make government services more transparent, accessible, secure, and human.\n- Two CTA buttons: \"Read The Platform\" and \"Join The Movement\".\n- Include a stylized candidate/card area with fictional candidate name \"Elena Marquez\" and title \"Candidate for Digital Reform Council\".\n- Use decorative geometric lines, radial shapes, civic badge motifs, abstract circuit patterns, and art-deco framing.\n- Add GSAP entrance animation for headline, badge, buttons, and background shapes.\n\n2. Campaign Pillars\n- Four feature cards with icons or simple line-art style symbols: Digital Access For All, Secure Public Infrastructure, Ethical AI Education, Transparent Civic Tools.\n- Each card should include a short persuasive paragraph.\n- Cards should animate on scroll with GSAP, staggered fade/slide.\n\n3. Platform Overview\n- A more detailed section explaining the technology-focused political plan.\n- Include three horizontal blocks or timeline-style items: Modernize Services, Protect Citizen Data, Train The Next Generation.\n- Use art-deco separators and polished editorial layout.\n- Add sample metrics like \"42 community workshops planned\", \"18 public service redesign goals\", \"100% privacy-first policy pledge\" but clearly present them as campaign goals/sample static content, not live stats.\n\n4. Candidate Message\n- A strong quote section from Elena Marquez.\n- Include a portrait placeholder/card style using gradients and decorative frame, not requiring real image downloads.\n- Copy should sound like a campaign speech: optimistic, practical, civic-minded.\n\n5. Events Preview\n- Static mock event cards, no calendar integration.\n- Example events: \"Town Hall: AI and Public Trust\", \"Digital Skills Weekend\", \"Cyber Safety for Families\".\n- Include dates, location text, and short descriptions.\n- Add a small note that event details are sample/static for the demo.\n\n6. Volunteer / Sign-up Form\n- Include a front-end only form section with fields: name, email, ZIP/postcode, area of interest dropdown, message.\n- The form should not submit to a server. On submit, show a friendly static success message or inline confirmation using client-side JavaScript only.\n- Style the form as an elegant art-deco pledge card with gold borders, dark panels, and accessible focus states.\n\n7. Issue Comparison Strip\n- A visually interesting section comparing \"Old Systems\" vs \"Future-Ready Civic Tech\".\n- Keep it tasteful and non-hostile, more policy focused than attack-ad style.\n- Use two columns with short bullets and animated progress lines or decorative dividers.\n\n8. Footer\n- Include campaign navigation links, fictional disclaimer text, social link labels only, and small line: \"Static demo website. No real campaign data collected.\"\n- No real payment links or real organizations.\n\nDesign requirements:\n- Art-deco style, polished political campaign branding, technology domain.\n- Color palette: midnight navy, black, antique gold, ivory, muted emerald, small warm red accent only if needed.\n- Typography should feel elegant: strong serif-like display headings paired with clean sans-serif body text. Use CSS/font fallback if not importing fonts.\n- Fully responsive for mobile, tablet, and desktop.\n- Medium complexity: not a huge app, but it should feel like a complete designed landing page.\n- Use GSAP for scroll reveal animations and hero motion. Keep animations smooth and not distracting.\n- Add hover states for cards, buttons, and navigation.\n- Include sticky or elegant top navigation with links to sections.\n- Ensure good contrast, accessible labels, keyboard-friendly form controls, and semantic HTML.\n- Use mock/static content only and keep everything renderable as a static site without any external service.\n\nDeliverable: a complete React static landing page with clean component structure, CSS styling, GSAP animation setup, responsive layout, and all content included locally in the code. The final result should look like a high-end Dribbble concept for an art-deco technology political campaign landing page, not a plain template." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00185/tests/grade.py b/tasks/dasyn_260638_00185/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00185/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00185/tests/test.sh b/tasks/dasyn_260638_00185/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00185/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00185/tests/webdev/__init__.py b/tasks/dasyn_260638_00185/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00185/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00185/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00185/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00185/tests/webdev/shot.py b/tasks/dasyn_260638_00185/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00185/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00185/tests/webdev/verdict.py b/tasks/dasyn_260638_00185/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00185/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00310/environment/Dockerfile b/tasks/dasyn_260638_00310/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00310/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00310/environment/setup/setup.sh b/tasks/dasyn_260638_00310/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00310/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00310/tests/grade.json b/tasks/dasyn_260638_00310/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..9d5c32fc0bb54348de6cc0fed5d505b0c5203717 --- /dev/null +++ b/tasks/dasyn_260638_00310/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a modern static Next.js website for “MediBite Pharmacy Reviews” — a community-style review site for local pharmacies, inspired by Reddit discussion cards but with the layout polish of a restaurant review website. No backend, no login, no real APIs: use mock/static sample data only.\n\nPages/Sections:\n- Home landing page with hero: “Find trusted pharmacies near you”\n- Featured pharmacy review cards with ratings, tags, opening hours, location text, and short user comments\n- Reddit-style review feed with upvote/downvote buttons as visual-only UI, comment count, flair tags like “Fast Service”, “24/7”, “Affordable”, “Insurance Friendly”\n- Pharmacy detail section with menu-like service categories: Prescriptions, Vaccines, Health Checks, Delivery, OTC Products\n- Top Rated Pharmacies leaderboard\n- Comparison table for pharmacy services\n- Static AI chatbot widget in the bottom corner called “MediBot” with prewritten sample chat messages and quick questions like “Which pharmacy is open late?” and “Where can I get vaccines?”\n- Review submission mock form, visual only, no functionality required\n- FAQ and safety disclaimer section\n- Contact/location cards with fake sample addresses\n\nDesign:\n- Clean modern healthcare look, white/soft green/blue palette\n- Mobile responsive\n- Card-based Reddit-inspired layout\n- Restaurant-site feeling: ratings, service menu, popular picks, opening hours, review highlights\n- Add subtle hover states and polished UI components\n- Use only static content and local mock data, no external services." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00310/tests/grade.py b/tasks/dasyn_260638_00310/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00310/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00310/tests/test.sh b/tasks/dasyn_260638_00310/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00310/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00310/tests/webdev/__init__.py b/tasks/dasyn_260638_00310/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00310/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00310/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00310/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00310/tests/webdev/shot.py b/tasks/dasyn_260638_00310/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00310/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00310/tests/webdev/verdict.py b/tasks/dasyn_260638_00310/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00310/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00317/environment/Dockerfile b/tasks/dasyn_260638_00317/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00317/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00317/environment/setup/setup.sh b/tasks/dasyn_260638_00317/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00317/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00317/tests/grade.json b/tasks/dasyn_260638_00317/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..97eb8008f9d49172fb6d41397c93670a37069122 --- /dev/null +++ b/tasks/dasyn_260638_00317/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Make a static React neomorphic dental expo comparison site, Medium-like clean layout, mock sponsor/package cards, event details, and simple RSVP form." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00317/tests/grade.py b/tasks/dasyn_260638_00317/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00317/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00317/tests/test.sh b/tasks/dasyn_260638_00317/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00317/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00317/tests/webdev/__init__.py b/tasks/dasyn_260638_00317/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00317/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00317/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00317/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00317/tests/webdev/shot.py b/tasks/dasyn_260638_00317/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00317/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00317/tests/webdev/verdict.py b/tasks/dasyn_260638_00317/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00317/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00319/environment/Dockerfile b/tasks/dasyn_260638_00319/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00319/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00319/environment/setup/setup.sh b/tasks/dasyn_260638_00319/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00319/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00319/tests/grade.json b/tasks/dasyn_260638_00319/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..71788615ad74174515c06429a00c641ab06afee0 --- /dev/null +++ b/tasks/dasyn_260638_00319/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Build a bold static React editorial documentation website for a nonprofit called Open Shelter Playbook. The site is not an app, no backend, no login, no database, no external APIs: just a polished front-end that can run with static/mock content. The goal is to publish practical field documentation for volunteers who help operate temporary community shelters during heat waves, storms, and local emergencies.\n\nOverall direction: make it feel like a documentation hub mixed with a modern media/editorial site. Use a visual rhythm inspired by Bilibili: colorful section cards, energetic thumbnails, sticky category navigation, compact metadata badges, lively hover states, and a feed-like browsing experience. Do not copy Bilibili branding, mascot, logos, or exact UI, just use the idea of a bright content platform with dense but friendly information architecture.\n\nPages/sections needed:\n- Hero landing area: big headline, nonprofit mission statement, emergency documentation search-looking bar that is only decorative/static, and quick links like Start Here, Shelter Setup, Volunteer Roles, Supplies, Accessibility, Safety.\n- Infinite-scroll documentation feed: implement a front-end infinite-scroll interaction using a local array of sample articles. As the user scrolls, more mock documentation cards appear. No network requests. Include at least 24 sample docs total, loaded in chunks.\n- Featured playbooks: large editorial cards for Heat Wave Shelter Setup, Overnight Intake Desk, Food Distribution Line, Pet-Friendly Shelter Corner, and Closing Checklist.\n- Category rail: sticky horizontal/side category nav with bright tags, showing docs grouped by topic.\n- Article preview layout: each card should include title, short summary, reading time, difficulty badge, role badge, last-reviewed date, and a small illustrated placeholder block.\n- Documentation article template section: include one expanded sample article on the page with table of contents, callout boxes, step-by-step checklist, do/don't panel, printable note styling, and related documents.\n- Nonprofit trust area: explain that the content is community reviewed, plain-language, field tested, and designed for volunteers.\n- Footer: nonprofit links, accessibility note, Creative Commons style static notice, emergency disclaimer.\n\nDesign requirements:\n- Bold typography, large headlines, strong black/white contrast with accent colors like electric blue, coral, lemon yellow, and soft violet.\n- Editorial/documentation feel, not corporate SaaS.\n- Layout should be responsive for desktop and mobile.\n- Use cards, badges, tabs, sticky nav, scroll progress indicator, and playful micro-interactions with CSS only.\n- Use static placeholder illustrations or CSS shapes, no image downloads required.\n- Infinite scroll should feel smooth and obvious, with a small “loading more guides...” transition even though it is just local content.\n- Include accessible semantics, keyboard-friendly controls where relevant, good contrast, and reduced-motion consideration.\n\nTech: React. A single static site is fine, can be Vite-style. Use local mock data in the code. No real API integrations, no authentication, no backend routes, no database, no server rendering requirement." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00319/tests/grade.py b/tasks/dasyn_260638_00319/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00319/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00319/tests/test.sh b/tasks/dasyn_260638_00319/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00319/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00319/tests/webdev/__init__.py b/tasks/dasyn_260638_00319/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00319/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00319/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00319/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00319/tests/webdev/shot.py b/tasks/dasyn_260638_00319/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00319/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00319/tests/webdev/verdict.py b/tasks/dasyn_260638_00319/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00319/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00321/environment/Dockerfile b/tasks/dasyn_260638_00321/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00321/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00321/environment/setup/setup.sh b/tasks/dasyn_260638_00321/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00321/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00321/tests/grade.json b/tasks/dasyn_260638_00321/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..db9a874e1805fbabc43bc39eaca461e734003b2b --- /dev/null +++ b/tasks/dasyn_260638_00321/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "I need a polished static landing page built in Next.js for a community recruitment platform called TalentCircle. It is not a real app yet, just a marketing/demo website, so please use mock data only and no backend, no login, no database, no external API. The idea is a place where local creative communities, bootcamp graduates, junior developers, designers, and small companies can discover each other. I want the visual direction to be very clean Swiss design: strong grid, lots of whitespace, bold typography, precise spacing, black/white base with one confident accent color, and a premium editorial feeling. But for the content browsing layout take inspiration from Netflix, like horizontal rows of talent cards, featured collections, big hero banner, category strips, spotlight profiles, and smooth hover states. It should still feel professional for recruitment, not entertainment. Please make it complex enough to look like a real product landing page: hero section with headline and search bar, stats, featured talent communities, role categories, recruiter benefits, candidate benefits, testimonial cards, pricing/CTA section, FAQ, footer, and a mock talent directory section. The search interaction should work on the static mock content only, filtering sample profiles or roles on the page without any server. Add filters like role, location, availability, seniority, and community tag, all using local state. Also include empty states and clear results count. Make it responsive for mobile/tablet/desktop and make sure all buttons, search, tabs, filter chips, carousel-like rows if used, and navigation anchors actually work on the static page. Use realistic placeholder names, roles, and community descriptions, but no real people. Please do not add authentication or posting jobs or saving profiles because this is only a static front-end landing page." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00321/tests/grade.py b/tasks/dasyn_260638_00321/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00321/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00321/tests/test.sh b/tasks/dasyn_260638_00321/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00321/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00321/tests/webdev/__init__.py b/tasks/dasyn_260638_00321/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00321/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00321/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00321/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00321/tests/webdev/shot.py b/tasks/dasyn_260638_00321/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00321/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00321/tests/webdev/verdict.py b/tasks/dasyn_260638_00321/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00321/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00326/environment/Dockerfile b/tasks/dasyn_260638_00326/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00326/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00326/environment/setup/setup.sh b/tasks/dasyn_260638_00326/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00326/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00326/tests/grade.json b/tasks/dasyn_260638_00326/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..b641ef29c4935a261fb78d4207db93a9f6971c93 --- /dev/null +++ b/tasks/dasyn_260638_00326/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "# Build a Luxury Static Website for an EdTech Gala Dinner Event\n\nCreate a premium, high-end restaurant-style event website for **The Learning Table Summit 2026** — an exclusive edtech networking dinner where educators, founders, investors, curriculum designers, and AI learning specialists meet for one elegant evening.\n\nUse **React + Tailwind CSS**. This must be a **pure static front-end website only**. No backend, no database, no login, no booking system, no payments, no real API integrations. Use mock/static content for menu, speakers, schedule, sponsors, and RSVP sections.\n\n---\n\n## Overall Style\n\nTheme: **Luxury restaurant + modern edtech conference**\n\nVisual direction:\n- Deep navy / charcoal background\n- Champagne gold accents\n- Warm ivory text blocks\n- Elegant serif headings + clean sans-serif body text\n- Premium fine-dining layout mixed with futuristic learning/technology details\n- Lots of whitespace, polished cards, subtle gradients, soft shadows\n- High-end editorial feel, like a private members club dinner invitation\n\nSuggested colors:\n- Background: #08111F, #101827, #F8F1E7\n- Gold: #D7B46A\n- Accent blue: #5DADEC\n- Muted text: #B8C0CC\n- Wine accent: #6E2435\n\n---\n\n## Required Pages / Sections\n\n### 1. Hero Section\n\nLeft side:\n- Small badge: `Private EdTech Dining Experience • June 2026`\n- Large headline: `Where Learning Leaders Dine, Debate & Design the Future`\n- Short description:\n `An intimate luxury dinner event for innovators shaping the next generation of education technology, personalized learning, and AI-assisted classrooms.`\n- CTA buttons:\n - `View Evening Program`\n - `Explore Tasting Menu`\n\nRight side:\n- Elegant restaurant table / abstract luxury dinner visual using static image placeholders or CSS cards\n- Floating glassmorphism cards:\n - `72 Curated Guests`\n - `5-Course Learning Menu`\n - `12 Thought Leaders`\n - `1 Private Evening`\n\nAdd subtle animated cursor effect: a soft golden glow following the cursor, and gentle hover reactions on premium cards/buttons. Keep it tasteful, no game/canvas stuff.\n\n---\n\n### 2. Trust / Event Stats Bar\n\nHorizontal luxury stats strip:\n- `25+ Institutions Represented`\n- `12 EdTech Founders`\n- `8 Fireside Dialogues`\n- `5 Course Culinary Journey`\n- `1 Curated Networking Salon`\n\nUse gold dividers and soft glass background.\n\n---\n\n### 3. About the Evening\n\nTitle: `A Dinner Designed Like a Curriculum`\n\nCopy should explain that every course of the meal is paired with a conversation topic:\n- Appetizer: Access & Equity\n- First Course: AI Tutors\n- Main Course: Learning Analytics\n- Dessert: Human-Centered Schools\n- Digestif: Future Signals\n\nLayout: split section with editorial text on one side, timeline/menu pairing on the other.\n\n---\n\n### 4. Tasting Menu Section\n\nRestaurant-style menu cards with edtech themed names. Static sample items only.\n\nMenu categories:\n\n**Opening Bites**\n- Microlearning Tartlet\n- Adaptive Pathway Crostini\n- Scholarship Garden Spoon\n\n**Main Course**\n- Personalized Learning Risotto\n- AI Mentor Sea Bass\n- Classroom Cloud Wellington\n\n**Dessert**\n- Knowledge Graph Mille-Feuille\n- Data-Driven Chocolate Sphere\n- Future Classroom Sorbet\n\nEach menu card should include:\n- Course name\n- Short poetic description\n- Dietary tag examples: `Vegetarian`, `Gluten-Free Option`, `Chef’s Signature`\n\nMake it look like a Michelin-level menu page.\n\n---\n\n### 5. Featured Speakers / Table Hosts\n\nCreate elegant profile cards for fictional speakers, no real people.\n\nExample cards:\n- Dr. Elena Marquez — Learning Experience Architect\n- Noah Sterling — Founder, Adaptive Campus Studio\n- Priya Voss — AI Curriculum Strategist\n- Marcus Bell — Digital Equity Researcher\n- Lina Hart — School Innovation Director\n- Theo Camden — Education Investment Partner\n\nEach card:\n- Placeholder portrait block or gradient avatar\n- Name\n- Role\n- One-line topic\n- Small gold label such as `Table Host`, `Fireside Guest`, `Salon Moderator`\n\nNo links to social media needed, keep static.\n\n---\n\n### 6. Evening Program\n\nCreate a vertical luxury event schedule:\n\n- 6:00 PM — Champagne Arrival & Learning Salon\n- 6:30 PM — Welcome Toast: The Future of Intelligent Classrooms\n- 7:00 PM — First Course Conversation: Equity by Design\n- 7:45 PM — Main Course Debate: AI, Teachers, and Trust\n- 8:30 PM — Dessert Roundtable: Measuring Meaningful Learning\n- 9:15 PM — Closing Notes & Private Networking\n\nDesign should feel like a printed invitation card with gold rule lines.\n\n---\n\n### 7. Venue Section\n\nCreate a luxury restaurant venue area.\n\nVenue name: `The Atrium Room at Maison Aurelia`\nLocation: `Mock location: 18 Scholar’s Lane, Westbridge District`\n\nInclude:\n- Elegant image placeholder\n- Venue highlights:\n - Private dining room\n - Sommelier-curated pairings\n - Quiet salon seating\n - Presentation-ready acoustic setup\n - Limited guest list\n\nNo map API. If map needed, use a decorative static map-style card only.\n\n---\n\n### 8. Sponsor / Partner Strip\n\nUse mock/static partner logos only, text-based logo blocks are fine.\n\nExample partners:\n- LumaLearn\n- Chalk & Circuit\n- NovaClass\n- Pedagogy House\n- Atlas Academy Lab\n- MentorGrid\n\nMake it feel premium, not like startup clutter.\n\n---\n\n### 9. RSVP / Invitation Section\n\nImportant: This is static only. Do not create real form submission.\n\nDesign a beautiful invitation panel with fields visually shown only:\n- Full Name\n- Organization\n- Dietary Notes\n- Preferred Conversation Topic\n\nButton: `Request Invitation`\n\nAdd small note: `Static preview only — form is not connected.`\n\nMake it look complete visually but no backend functionality.\n\n---\n\n### 10. Footer\n\nFooter content:\n- Event name\n- Short tagline\n- Static contact text: `hello@learningtable.example`\n- Links: Program, Menu, Venue, Speakers\n- Copyright 2026\n\n---\n\n## Interaction Details\n\nAdd refined static front-end interactions:\n- Custom cursor glow effect in gold/champagne\n- Button hover shimmer\n- Menu card tilt or lift on hover using CSS only\n- Smooth scrolling anchor links\n- Section reveal animations if easy with CSS/React state, but no external services\n- Sticky elegant top navigation with translucent blur\n\nNo heavy 3D, no WebGL, no canvas game, no physics.\n\n---\n\n## Deliverable\n\nPlease build the full static website in React with Tailwind CSS. It should be responsive for desktop, tablet, and mobile. Use mock images/placeholders and static sample content. The final result should feel like a luxury restaurant event website for an exclusive edtech dinner summit." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00326/tests/grade.py b/tasks/dasyn_260638_00326/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00326/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00326/tests/test.sh b/tasks/dasyn_260638_00326/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00326/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00326/tests/webdev/__init__.py b/tasks/dasyn_260638_00326/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00326/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00326/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00326/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00326/tests/webdev/shot.py b/tasks/dasyn_260638_00326/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00326/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00326/tests/webdev/verdict.py b/tasks/dasyn_260638_00326/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00326/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00327/environment/Dockerfile b/tasks/dasyn_260638_00327/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00327/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00327/environment/setup/setup.sh b/tasks/dasyn_260638_00327/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00327/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00327/tests/grade.json b/tasks/dasyn_260638_00327/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..b376f156c435a6d83d70c8767ab479c0911ea080 --- /dev/null +++ b/tasks/dasyn_260638_00327/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "ابني لي موقع مدونة شخصية ثابتة عن تجارب الإقامة في الفنادق الفاخرة، يكون التصميم elegant وهادئ مثل صفحات editorial، باستخدام React و GSAP للحركات الناعمة عند التمرير وظهور الصور والعناوين. أريد صفحة رئيسية فيها hero كبير، مقالات مختارة، قسم عن الكاتب، تصنيفات مثل boutique hotels و spa retreats و city stays، وصفحات/أقسام لعدة تدوينات بمحتوى وصور وهمية فقط. خلي الشكل مرتب كأنه مشروع منشور على GitHub مع README بسيط وتعليمات تشغيل، بدون تسجيل دخول أو قاعدة بيانات أو API أو أي خدمات خارجية، فقط static site جاهز للعرض." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00327/tests/grade.py b/tasks/dasyn_260638_00327/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00327/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00327/tests/test.sh b/tasks/dasyn_260638_00327/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00327/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00327/tests/webdev/__init__.py b/tasks/dasyn_260638_00327/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00327/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00327/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00327/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00327/tests/webdev/shot.py b/tasks/dasyn_260638_00327/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00327/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00327/tests/webdev/verdict.py b/tasks/dasyn_260638_00327/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00327/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00328/environment/Dockerfile b/tasks/dasyn_260638_00328/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00328/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00328/environment/setup/setup.sh b/tasks/dasyn_260638_00328/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00328/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00328/tests/grade.json b/tasks/dasyn_260638_00328/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..30690bd970012e4aca4da2e61641477dd5f7a036 --- /dev/null +++ b/tasks/dasyn_260638_00328/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a minimalist Astro static website for an interior design news/product showcase, same visual mood like my attached Xiaohongshu screenshots. It should feature curated furniture and decor items as short news cards, clean white space, soft beige tones, editorial titles, product highlights, and a simple homepage with hero, trending design picks, latest room styling news, and featured product section. Use only static/mock content, no API or backend. Add a small confetti animation when user clicks save/favorite on a product card, and make it responsive for mobile first." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00328/tests/grade.py b/tasks/dasyn_260638_00328/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00328/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00328/tests/test.sh b/tasks/dasyn_260638_00328/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00328/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00328/tests/webdev/__init__.py b/tasks/dasyn_260638_00328/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00328/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00328/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00328/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00328/tests/webdev/shot.py b/tasks/dasyn_260638_00328/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00328/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00328/tests/webdev/verdict.py b/tasks/dasyn_260638_00328/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00328/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00343/environment/Dockerfile b/tasks/dasyn_260638_00343/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00343/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00343/environment/setup/setup.sh b/tasks/dasyn_260638_00343/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00343/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00343/tests/grade.json b/tasks/dasyn_260638_00343/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..7f2fe2ac72942c2946c01d41a5d2422e34d083cd --- /dev/null +++ b/tasks/dasyn_260638_00343/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Nuxt static retro Notion-style tutoring membership editorial site, with search over mock lessons" +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00343/tests/grade.py b/tasks/dasyn_260638_00343/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00343/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00343/tests/test.sh b/tasks/dasyn_260638_00343/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00343/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00343/tests/webdev/__init__.py b/tasks/dasyn_260638_00343/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00343/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00343/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00343/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00343/tests/webdev/shot.py b/tasks/dasyn_260638_00343/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00343/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00343/tests/webdev/verdict.py b/tasks/dasyn_260638_00343/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00343/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00372/environment/Dockerfile b/tasks/dasyn_260638_00372/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00372/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00372/environment/setup/setup.sh b/tasks/dasyn_260638_00372/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00372/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00372/tests/grade.json b/tasks/dasyn_260638_00372/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..7116c3ca2772e7c101c14bf5595a53273f2ea65e --- /dev/null +++ b/tasks/dasyn_260638_00372/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "أحتاج موقع ويكي سفر ثابت بواجهة Vue فقط، ستايل brutalist واضح وقاسي بالأبيض والأسود مع ألوان تنبيه بسيطة. الصفحة الرئيسية فيها خلفية فيديو قصيرة مثل إحساس TikTok عمودية/سريعة، لكن استخدم فيديو تجريبي محلي أو placeholder فقط بدون APIs. الأقسام: وجهات مشهورة، دليل سريع لكل مدينة، نصائح السفر، صفحة مقال/توثيق عن مدينة مختارة. المحتوى كله mock/static، والتصميم يكون بسيط وسهل القراءة كأنه documentation-site للسفر." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00372/tests/grade.py b/tasks/dasyn_260638_00372/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00372/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00372/tests/test.sh b/tasks/dasyn_260638_00372/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00372/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00372/tests/webdev/__init__.py b/tasks/dasyn_260638_00372/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00372/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00372/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00372/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00372/tests/webdev/shot.py b/tasks/dasyn_260638_00372/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00372/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00372/tests/webdev/verdict.py b/tasks/dasyn_260638_00372/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00372/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00375/environment/Dockerfile b/tasks/dasyn_260638_00375/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00375/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00375/environment/setup/setup.sh b/tasks/dasyn_260638_00375/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00375/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00375/tests/grade.json b/tasks/dasyn_260638_00375/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..eb03fa646f838c24ec550430a172475f54d9c711 --- /dev/null +++ b/tasks/dasyn_260638_00375/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Create a clean modern static React website for a government digital services changelog, kind of inspired by Spotify’s polished cards, dark accents, rounded sections, and smooth editorial layout. It should be a simple public-facing page where citizens can read recent updates to online services, policy notices, maintenance improvements, and accessibility fixes. Use only mock/static changelog entries, no login, no backend, no APIs. I want a hero section with a short title like “What’s new in public digital services”, filter-style category pills that are just visual, a timeline of updates, a featured release card, and a footer with basic government links. Keep it responsive, trustworthy, readable, and not too corporate, with subtle green/black/white Spotify-like inspiration but still appropriate for a government site." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00375/tests/grade.py b/tasks/dasyn_260638_00375/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00375/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00375/tests/test.sh b/tasks/dasyn_260638_00375/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00375/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00375/tests/webdev/__init__.py b/tasks/dasyn_260638_00375/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00375/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00375/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00375/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00375/tests/webdev/shot.py b/tasks/dasyn_260638_00375/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00375/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00375/tests/webdev/verdict.py b/tasks/dasyn_260638_00375/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00375/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00381/environment/Dockerfile b/tasks/dasyn_260638_00381/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00381/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00381/environment/setup/setup.sh b/tasks/dasyn_260638_00381/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00381/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00381/tests/grade.json b/tasks/dasyn_260638_00381/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..9541353642f8cfcab05ae62de23c3173a2779548 --- /dev/null +++ b/tasks/dasyn_260638_00381/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "Make a simple static event website in Tailwind for a sports political campaign rally, like a candidate promising better stadiums and youth football programs. Use soft neomorphism design, light grey background, rounded cards, hero section, event date, speaker list, agenda, and YouTube style video thumbnail section but only use mock images/no real API. Add smooth page transitions between Home, Agenda and About pages." +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00381/tests/grade.py b/tasks/dasyn_260638_00381/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00381/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00381/tests/test.sh b/tasks/dasyn_260638_00381/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00381/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00381/tests/webdev/__init__.py b/tasks/dasyn_260638_00381/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00381/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00381/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00381/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00381/tests/webdev/shot.py b/tasks/dasyn_260638_00381/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00381/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00381/tests/webdev/verdict.py b/tasks/dasyn_260638_00381/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00381/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + } diff --git a/tasks/dasyn_260638_00386/environment/Dockerfile b/tasks/dasyn_260638_00386/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce6f530017c2adc1e19c10584de3dd22e3030cf3 --- /dev/null +++ b/tasks/dasyn_260638_00386/environment/Dockerfile @@ -0,0 +1,3 @@ +# The task's image, pinned by digest (the same as [environment].docker_image). +# Setup runs at start from [environment.healthcheck]; environment/setup/ is its readable copy. +FROM docker.io/xiaomimimo/mimo-v2.6-rl-oss@sha256:6e30e61bdbe1504470cd1f705b120d317da9e7f57df3ba04a906db6b2e95e14d diff --git a/tasks/dasyn_260638_00386/environment/setup/setup.sh b/tasks/dasyn_260638_00386/environment/setup/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..36a4e568a6baeee360a4b505a1b1eaa03bc21ff2 --- /dev/null +++ b/tasks/dasyn_260638_00386/environment/setup/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Runs once, as root, before the agent starts: Harbor's [environment.healthcheck] unpacks this folder into +# /var/lib/mimo and runs it. Generated by mimo_harbor; see its README for how each step maps to Xiaomi's harness. +M=/var/lib/mimo +[ -f "$M/ready" ] && exit 0 +chmod 700 "$M" +fail() { echo "setup: $*" >&2; exit 1; } +# the answer-leak blocklist (mimoagent), applied to /etc/hosts by the agent right after it installs +write_blocklist() { cp "$M/files/blocklist" "$M/blocklist"; } + +# Webdev: verl recipes/design webdev-eval, as the explorer runs it. No blocklist: npm and CDNs are fair game. +mkdir -p /workspace/dist + +touch "$M/ready" +echo "setup done" diff --git a/tasks/dasyn_260638_00386/tests/grade.json b/tasks/dasyn_260638_00386/tests/grade.json new file mode 100644 index 0000000000000000000000000000000000000000..6335dc4e323258a06db04b3c748b1963b9091dd6 --- /dev/null +++ b/tasks/dasyn_260638_00386/tests/grade.json @@ -0,0 +1,4 @@ +{ + "cwd": "/workspace", + "query": "عايز موقع ثابت لتقييمات فندق فاخر، صفحة تسويقية شكلها شيك بتدرجات ألوان وخلفيات تتحرك parallax، وفيه كروت مراجعات وصور غرف وترتيب زي ستايل انستجرام بس بمحتوى وهمي جاهز بدون تسجيل ولا باك اند" +} \ No newline at end of file diff --git a/tasks/dasyn_260638_00386/tests/grade.py b/tasks/dasyn_260638_00386/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..598b461f0bcb56f216662c30ce1226a4722f7d4e --- /dev/null +++ b/tasks/dasyn_260638_00386/tests/grade.py @@ -0,0 +1,88 @@ +"""Grade a Webdev task as the explorer does (verl recipes/design webdev-eval): render, shrink, judge. + +No index.html in dist/ scores 0. A render that fails, or a judge that never answers, writes no reward (not scored): +neither says anything about the page.""" +import base64 +import io +import json +import os +import random +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, "/tests") +os.environ["WEBDEV_GRADE_HTTP"] = "1" # serve over loopback http so React/Vue/ES-module sites actually run +from webdev.eval_rubric import build_prompt # noqa: E402 +from webdev.shot import _build_shot_cmd, _parse_render_env, _parse_shot_b64 # noqa: E402 +from webdev.verdict import parse_verdict # noqa: E402 + +cfg = json.loads(Path("/tests/grade.json").read_text()) +V = Path("/logs/verifier") +V.mkdir(parents=True, exist_ok=True) +dist = Path(cfg["cwd"]) / "dist" + + +def done(reward: float | None, why: str, **extra) -> None: + (V / "result.json").write_text(json.dumps({"reward": reward, "summary": why, **extra}, indent=1)) + print(why) + if reward is None: + print("not scored", file=sys.stderr) + sys.exit(1) + (V / "reward.txt").write_text(f"{reward}\n") + sys.exit(0) + + +files = sorted(str(p.relative_to(dist)) for p in dist.rglob("*") if p.is_file())[:200] if dist.is_dir() else [] +if "index.html" not in files: + done(0.0, "The agent delivered nothing to dist/." if not files else "dist/ has no index.html, so there is no page to open.", + delivered=files) +res = subprocess.run(["sh", "-c", _build_shot_cmd(f"file://{dist}/index.html")], capture_output=True, text=True, + timeout=150) # SHOT_TIMEOUT_S +shot = {"output": (res.stdout or "") + "\n" + (res.stderr or "")} +shot_b64, console_errors = _parse_shot_b64(shot) +render_env = _parse_render_env(shot) +if render_env.get("proxy_failed") or not shot_b64: + print(shot["output"][-2000:], file=sys.stderr) + done(None, "external assets were unreachable on every route" if render_env.get("proxy_failed") + else "the screenshot produced no image") +jpg = base64.b64decode(shot_b64) +try: # eval_mode._shrink: the judge refuses shots over 20 MP; proportional, quality 75 + from PIL import Image + Image.MAX_IMAGE_PIXELS = None + im = Image.open(io.BytesIO(jpg)) + size = im.size + if im.width * im.height > 20e6: + k = (20e6 / (im.width * im.height)) ** 0.5 + im = im.convert("RGB").resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) + b = io.BytesIO(); im.save(b, "JPEG", quality=75); jpg = b.getvalue(); size = im.size +except ImportError: + size = None +(V / "screenshot.jpg").write_bytes(jpg) +content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(jpg).decode()}}, + {"type": "text", "text": build_prompt().format(query=cfg["query"][:1500])}] # QUERY_CAP +url = os.environ.get("WEBDEV_JUDGE_URL", "https://router.huggingface.co/v1").rstrip("/") + "/chat/completions" +body = json.dumps({"model": os.environ["WEBDEV_JUDGE_MODEL"], "temperature": 1.0, + "messages": [{"role": "user", "content": content}]}).encode() +verdict, last = None, "" +for attempt in range(4): # JUDGE_RETRIES, with eval_mode's backoff + if attempt: + time.sleep(min(60.0, 3.0 * (3 ** (attempt - 1))) * (0.5 + random.random())) + try: + req = urllib.request.Request(url, data=body, method="POST", headers={ + "Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('WEBDEV_JUDGE_KEY', '')}"}) + with urllib.request.urlopen(req, timeout=180) as r: # JUDGE_TIMEOUT_S + msg = json.loads(r.read())["choices"][0]["message"] + v = parse_verdict(msg.get("content") or msg.get("reasoning_content") or "") + if "_failed" not in v: + verdict = v + break + last = v["_failed"] + except Exception as e: # noqa: BLE001 + last = f"{type(e).__name__}: {e}"[:200] +if not verdict: + done(None, f"judge unavailable: {last}") +done(verdict["score"], verdict.get("reason", ""), dims=verdict["dims"], visual=verdict["visual"], screenshot_size=size, + console_errors=console_errors[:1500] if console_errors not in ("", "[]") else "") diff --git a/tasks/dasyn_260638_00386/tests/test.sh b/tasks/dasyn_260638_00386/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba8a6a224063b344f312cabdd49fe92619340d94 --- /dev/null +++ b/tasks/dasyn_260638_00386/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Webdev grading: a full-page render of dist/index.html, judged by a vision model against the brief. +mkdir -p /logs/verifier +cd /tests && python3 /tests/grade.py diff --git a/tasks/dasyn_260638_00386/tests/webdev/__init__.py b/tasks/dasyn_260638_00386/tests/webdev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dasyn_260638_00386/tests/webdev/eval_rubric.py b/tasks/dasyn_260638_00386/tests/webdev/eval_rubric.py new file mode 100644 index 0000000000000000000000000000000000000000..87dc27cc90bcd61341080b7a167bb558c55247df --- /dev/null +++ b/tasks/dasyn_260638_00386/tests/webdev/eval_rubric.py @@ -0,0 +1,117 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The seven-dimension evaluation rubric. **The wording below is the ruler itself.** + +One vision call returns seven dimensions, and the evaluation score is an equal-weight mean +of three of them:: + + score = (visual + query_fulfillment + premium_assets) / 3 + visual = mean(layout_integrity, typography_hierarchy, color_harmony, + whitespace, content_richness) + +``BANDS`` and ``RICHNESS`` are kept **byte for byte** as the run that produced this arm's +published numbers used them, and they are in Chinese for the same reason. They are not +documentation of a scoring policy -- they ARE the scoring policy, handed to the judge model +verbatim. Translating or rewording them measures something else and makes every historical +result incomparable. To change the rubric, copy this file and change ``RUBRIC_ID``; a test +pins the rendered prompt's hash so an accidental edit fails loudly instead of silently +shifting the reward distribution. + +Two deliberate differences from the earlier four-term formula: + +* The fourth term (a static code check, weight 0.1) is gone. Its dominant component was an + INVERSE indicator: bucketing by ``premium_assets``, rows in [0, 0.2) averaged 0.900 on it + while rows in [0.8, 1.0] averaged only 0.425, with ``visual`` rising monotonically across + the same buckets. It was paying a bonus for not daring to reference external assets -- + the highest-scoring arm on that term was the one that referenced the fewest (0.823, + against 0.638 and 0.648 for the RL arms). +* The remaining three are equal-weight rather than 0.6 / 0.1 / 0.2. ``premium_assets`` + separates the arms most sharply (0.417 against 0.619, a gap of 0.20, where ``visual`` + differs by 0.042 and ``query`` by 0.054), so equal weighting stops a 0.6-weighted + ``visual`` from drowning out the dimension that actually discriminates. +""" + +BANDS = """1. layout_integrity(布局完整性) +- [0.0, 0.2):布局严重损坏,核心内容大面积重叠、截断、溢出或无法阅读 +- [0.2, 0.4):多处明显布局错误,显著影响主要内容使用 +- [0.4, 0.6):主体可用,但有一处严重或多处明显的对齐、重叠、超框问题 +- [0.6, 0.8):整体完整,仅有少量轻微对齐、间距或边界问题 +- [0.8, 1.0]:布局完整稳定,未见可感知的重叠、错位、截断或溢出 + +2. typography_hierarchy(排版层级) +- [0.0, 0.2):文字普遍不可读,字号/层级严重失控 +- [0.2, 0.4):标题正文层级混乱,多处字号、行高或字重明显不当 +- [0.4, 0.6):基本可读,但层级辨识或排版节奏存在明显缺陷 +- [0.6, 0.8):层级清楚、阅读顺畅,仅有少量轻微排版问题 +- [0.8, 1.0]:标题、正文、辅助文字层级鲜明且比例、行高、字重均成熟 + +3. color_harmony(配色与对比) +- [0.0, 0.2):配色严重冲突或关键文字几乎无法辨认 +- [0.2, 0.4):多处颜色不协调、对比不足,明显损害观感或可读性 +- [0.4, 0.6):基本可用,但色彩体系、对比或一致性有明显问题 +- [0.6, 0.8):配色协调且可读,仅有少量轻微不一致或对比问题 +- [0.8, 1.0]:色彩体系统一成熟,对比清晰,无明显问题 + +4. whitespace(留白与密度) +- [0.0, 0.2):页面极度拥挤或空洞,信息组织基本失效 +- [0.2, 0.4):多处明显过密/过空,严重破坏浏览节奏 +- [0.4, 0.6):整体可浏览,但局部密度、间距或区块节奏有明显问题 +- [0.6, 0.8):留白与内容密度总体合理,仅有少量轻微问题 +- [0.8, 1.0]:留白、间距和区块节奏自然一致,密度控制成熟 + +{richness} +{nq}. query_fulfillment(需求实现度) +- [0.0, 0.2):截图可见内容基本没有实现 query,或主题完全错误 +- [0.2, 0.4):只实现少量表面元素,多数核心要求缺失 +- [0.4, 0.6):实现主要方向,但多个关键板块、要素或功能界面明显缺失 +- [0.6, 0.8):主体要求已实现,仅有少量次要缺失或偏差 +- [0.8, 1.0]:截图可见范围内完整、准确地实现 query 的主题、板块、要素和功能界面 + +{na}. premium_assets(高级素材与质感) +- [0.0, 0.2):无有效视觉素材,或主要依赖简陋 emoji、裸占位、低质/模糊图像 +- [0.2, 0.4):素材较普通或粗糙,缺乏统一设计感;少量装饰不能形成质感 +- [0.4, 0.6):素材清晰且基本协调,但主要是普通图片或纯 CSS 视觉,没有高级素材 +- [0.6, 0.8):使用了高品质真实图片、艺术化图像、成体系插画或精致 mockup,整体质感良好但仍有小缺陷 +- [0.8, 1.0]:高级素材质量突出、体系完整,并与版式高度融合,达到成熟专业作品水准""" + +RICHNESS = """5. content_richness(内容丰富度) +- [0.0, 0.2):近乎空壳,一屏都撑不满,只有标题、空架子或极少占位内容 +- [0.2, 0.4):只有 1–2 个简单板块,内容高度重复、空泛或以占位为主 +- [0.4, 0.6):已有若干实际板块,但数量或内容深度明显不足以支撑完整网站 +- [0.6, 0.8):板块较完整、内容较具体,仅少数部分偏单薄 +- [0.8, 1.0]:约 4 个及以上成形板块,内容具体充实,足以支撑完整网站体验""" + + +VISUAL_KEYS = ("layout_integrity", "typography_hierarchy", "color_harmony", "whitespace", "content_richness") +SCORE_KEYS = ("visual", "query_fulfillment", "premium_assets") # 等权平均的三项 +ALL_KEYS = VISUAL_KEYS + ("query_fulfillment", "premium_assets") +RUBRIC_ID = "rva1:mean(visual,query,asset)" + + +def build_prompt() -> str: + """评测用的 7 维 prompt(含 content_richness)。`{query}` 占位符留给调用方 format。""" + dims = BANDS.format(richness=RICHNESS, nq=6, na=7) + return f"""你是网页 UI 评审。只依据 fullpage 截图可见证据评分。前 5 项构成 visual:前四项只评客观视觉问题,第五项评完整网站所需的信息量;第 6 项依据 query;第 7 项评素材品质。各维独立判断,不要因为某一维表现好或差而连带改变其它维。 + +query: {{query}} + +每个维度输出 0 到 1 的连续分数,可使用任意小数。先依据该维的五段描述确定分数所在区间,再根据问题严重程度、数量和影响在区间内连续取值;不要只输出区间端点或固定档位。五段边界统一为 [0.0,0.2)、[0.2,0.4)、[0.4,0.6)、[0.6,0.8)、[0.8,1.0]。临界情况选择与可见证据最匹配的相邻区间。premium_assets 没有高级素材时不得进入 [0.6,1.0]。 + +{dims} + +空白、严重加载失败或完全不可见时,所有维度输出 0。仅输出 JSON,不要 markdown: +{{{{"layout_integrity":0.0,"typography_hierarchy":0.0,"color_harmony":0.0,"whitespace":0.0,"content_richness":0.0,"query_fulfillment":0.0,"premium_assets":0.0,"reason":"核心依据"}}}}""" + + +__all__ = ["BANDS", "RICHNESS", "VISUAL_KEYS", "SCORE_KEYS", "ALL_KEYS", "RUBRIC_ID", "build_prompt"] diff --git a/tasks/dasyn_260638_00386/tests/webdev/shot.py b/tasks/dasyn_260638_00386/tests/webdev/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..794ba20c5f48e921ba955557bfc73d6bd6c5fc84 --- /dev/null +++ b/tasks/dasyn_260638_00386/tests/webdev/shot.py @@ -0,0 +1,249 @@ +# Copyright 2026 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""In-pod full-page screenshot pipeline: playwright inside the agent's own sandbox. + +Only the EVALUATION path uses this. Training ships the workspace to the grading service and +lets it render; evaluation renders here instead, so that it does not depend on that service +running -- evaluation is usually done in an environment that has no such long-lived service. + +``_SHOT_SCRIPT`` is kept **byte for byte**. Every non-obvious line in it encodes a failure +that was actually hit and diagnosed in a pod: proxy auth handed to the wrong playwright +field, a loopback bypass that the dict API silently drops, blank ``file://`` renders of +runtime-rendered pages, reveal-on-scroll content captured at opacity 0, sticky headers +painted at an in-flight scroll offset, parallax backgrounds going black below the fold. Read +the inline comments before changing any of it; none of these failures announce themselves -- +they all arrive as a plausible-looking screenshot that scores badly. + +The sandbox image must carry node, playwright and chromium. A missing chromium surfaces as +``render_failed``, which the caller masks, rather than as a bad score. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shlex + +_SHOT_SCRIPT = r''' +import sys, json, base64, argparse +from playwright.sync_api import sync_playwright +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--actions-b64", default="") +ap.add_argument("--proxy", default="") # comma-separated failover chain; empty entry = direct +ap.add_argument("--vw", type=int, default=1440) +ap.add_argument("--vh", type=int, default=900) +ap.add_argument("--serve-root", default="") # serve this dir over local http and rewrite --url onto it +a = ap.parse_args() +if a.serve_root: + import threading, functools + from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler + class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, *args, **kw): # keep stdout clean for SHOT_B64 parsing + pass + _handler = functools.partial(_QuietHandler, directory=a.serve_root) + _srv = ThreadingHTTPServer(("127.0.0.1", 0), _handler) + threading.Thread(target=_srv.serve_forever, daemon=True).start() + _page = a.url.rsplit("/", 1)[-1] if a.url.rsplit("/", 1)[-1].endswith(".html") else "index.html" + a.url = "http://127.0.0.1:%d/%s" % (_srv.server_address[1], _page) +actions = json.loads(base64.b64decode(a.actions_b64).decode()) if a.actions_b64 else [] +BASE_LAUNCH = {"headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage", + "--proxy-bypass-list=127.0.0.1;localhost"]} + +def _proxy_cfg(purl): + from urllib.parse import urlparse as _up + _pu = _up(purl) + cfg = {"server": _pu.scheme + "://" + _pu.hostname + ":" + str(_pu.port)} + if _pu.username: + cfg["username"] = _pu.username + cfg["password"] = _pu.password or "" + return cfg + +proxy_chain = [s.strip() for s in a.proxy.split(",")] if a.proxy else [""] +if a.proxy and "" not in proxy_chain: + proxy_chain.append("") +FATAL_NET = ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED", + "ERR_SOCKS_CONNECTION_FAILED", "ERR_NAME_NOT_RESOLVED", + "ERR_INTERNET_DISCONNECTED", "ERR_CONNECTION_TIMED_OUT", + "ERR_CONNECTION_REFUSED", "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", + "ERR_EMPTY_RESPONSE") +errs = [] +fatal = [] # fatal external request failures of the CURRENT load attempt +render_env = {"proxy_failed": False, "recovered": None, "attempts": [], "fatal": []} + +def _on_request_failed(req): + try: + u = req.url or "" + if not u.startswith("http") or u.startswith("http://127.0.0.1") or u.startswith("http://localhost"): + return # local server / file:// subresources are page defects, not env + f = req.failure or "" + if any(k in f for k in FATAL_NET): + fatal.append(f + " " + u[:120]) + except Exception: + pass + +SETTLE_JS = """async () => { + try { + document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important'); + if (document.body) document.body.style.setProperty('scroll-behavior', 'auto', 'important'); + } catch (e) {} + if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} } + const H = () => Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= Math.min(H(), 30000); y += step) { + window.scrollTo(0, y); + await new Promise(r => setTimeout(r, 120)); + } + window.scrollTo(0, H()); + await new Promise(r => setTimeout(r, 400)); + window.scrollTo(0, 0); + await new Promise(r => setTimeout(r, 300)); +}""" +FREEZE_CSS = ("*,*::before,*::after{animation-delay:0s !important;animation-duration:.01s !important;" + "transition-delay:0s !important;transition-duration:.01s !important;" + "background-attachment:scroll !important;scroll-behavior:auto !important;}") + +with sync_playwright() as p: + b = None + pg = None + + def _open(purl): + global b, pg + if b is not None: + try: + b.close() + except Exception: + pass + kw = dict(BASE_LAUNCH) + if purl: + kw["proxy"] = _proxy_cfg(purl) + b = p.chromium.launch(**kw) + pg = b.new_context(viewport={"width": a.vw, "height": a.vh}).new_page() + pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) + pg.on("pageerror", lambda e: errs.append("pageerror: " + str(e))) + pg.on("requestfailed", _on_request_failed) + + def _load(): + del fatal[:] + try: + resp = pg.goto(a.url, wait_until="load", timeout=25000) + if resp is not None and a.url.startswith("http") and resp.status >= 500: + fatal.append("PAGE_HTTP_%d %s" % (resp.status, a.url[:120])) + except Exception as e: + errs.append("goto failed: " + str(e)) + pg.wait_for_timeout(2000) + + for i, purl in enumerate(proxy_chain): + label = (purl.split("@")[-1] or "direct") if purl else "direct" + try: + _open(purl) + _load() + except Exception as e: + errs.append("launch failed via " + label + ": " + str(e)) + del fatal[:] + fatal.append("LAUNCH_FAILED " + label) + if fatal: + render_env["attempts"].append({"via": label, "fatal": fatal[:3]}) + if pg is not None and not fatal[0].startswith("LAUNCH_FAILED"): + _load() + if not fatal and pg is not None: + if render_env["attempts"]: + render_env["recovered"] = "via " + label + break + render_env["proxy_failed"] = bool(fatal) or pg is None + render_env["fatal"] = fatal[:5] + if pg is None: # every route failed to even open a browser: report env, no shot + sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") + sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") + sys.exit(0) + try: + pg.evaluate(SETTLE_JS) + pg.add_style_tag(content=FREEZE_CSS) + pg.wait_for_timeout(300) + except Exception as e: + errs.append("settle failed: " + str(e)) + for act in actions: + t = act.get("type") + try: + if t == "click": + pg.click(act["selector"], timeout=5000) + elif t == "fill": + pg.fill(act["selector"], act.get("value", ""), timeout=5000) + pg.wait_for_timeout(800) + except Exception as e: + errs.append("action " + json.dumps(act) + " failed: " + str(e)) + try: + pg.evaluate("window.scrollTo(0, 0)") + pg.wait_for_timeout(250) + except Exception as e: + errs.append("scroll-top failed: " + str(e)) + png = pg.screenshot(full_page=True, type="jpeg", quality=75) + b.close() +sys.stdout.write("SHOT_B64:" + base64.b64encode(png).decode() + "\n") +sys.stdout.write("CONSOLE_ERRORS:" + json.dumps(errs[:15]) + "\n") +sys.stdout.write("RENDER_ENV:" + json.dumps(render_env) + "\n") +''' + + +def _build_shot_cmd(url: str, *, actions_b64: str = "", proxy: str = "") -> str: + """Pod-side command that runs _SHOT_SCRIPT against `url`. Shared by ScreenshotTool + (feeds the multimodal grader) and capture_fullpage (lands the JPEG to disk). + + ``WEBDEV_GRADE_HTTP=1`` switches ``file://`` rendering to a loopback http server inside + the shot script (see ``--serve-root``) so runtime-rendered pages actually execute. **The + launcher sets this on**, and it must stay on: browsers block module loading, fetch and + XHR on the file protocol, so a React, Vue or ES-module deliverable renders as an empty + body no matter how good it is -- measured at 44 of 182 shots blank, essentially all of + them runtime-rendered. Since React is named in 30% of the training briefs, the old + default was scoring a large share of the task pool as necessarily broken and teaching the + policy to avoid the very stack the brief asked for. + + Scores across this boundary are NOT comparable: a React page goes from certainly-0 to + gradeable. Set it to 0 only to reproduce a pre-flip run. + """ + script_b64 = base64.b64encode(_SHOT_SCRIPT.encode()).decode() + serve_root = "" + if os.environ.get("WEBDEV_GRADE_HTTP") == "1" and url.startswith("file://"): + serve_root = os.path.dirname(url[len("file://") :]) or "/" + return ( + f"echo {script_b64} | base64 -d > /tmp/_webdev_shot.py && " + f"python3 /tmp/_webdev_shot.py --url {shlex.quote(url)} " + f"--actions-b64 {shlex.quote(actions_b64)} --proxy {shlex.quote(proxy)}" + + (f" --serve-root {shlex.quote(serve_root)}" if serve_root else "") + ) + + +def _parse_shot_b64(r: dict) -> tuple[str, str]: + """Pull (SHOT_B64, CONSOLE_ERRORS) out of an env.execute result; empty b64 on miss.""" + out = r.get("output") or "" + shot_b64, console_errors = "", "[]" + for line in out.splitlines(): + if line.startswith("SHOT_B64:"): + shot_b64 = line[len("SHOT_B64:") :].strip() + elif line.startswith("CONSOLE_ERRORS:"): + console_errors = line[len("CONSOLE_ERRORS:") :].strip() + return shot_b64, console_errors + + +def _parse_render_env(r: dict) -> dict: + """Pull the RENDER_ENV json out of an env.execute result. {} when absent + (old pod script) or unparseable — callers treat that as env-healthy.""" + for line in (r.get("output") or "").splitlines(): + if line.startswith("RENDER_ENV:"): + try: + return json.loads(line[len("RENDER_ENV:") :].strip()) + except Exception: + return {} + return {} diff --git a/tasks/dasyn_260638_00386/tests/webdev/verdict.py b/tasks/dasyn_260638_00386/tests/webdev/verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c518c94320dcd63aa1980e088f802392375d29b5 --- /dev/null +++ b/tasks/dasyn_260638_00386/tests/webdev/verdict.py @@ -0,0 +1,42 @@ +# Copyright 2026 Xiaomi / the verl authors. Apache-2.0 (see ../LICENSE-verl.txt). +# `parse_verdict` copied unchanged from XiaomiMiMo/verl recipes/design/webdev/eval_mode.py. +import json +import re + +from .eval_rubric import ALL_KEYS, VISUAL_KEYS + +_JSON_RE = re.compile(r"\{.*\}", re.DOTALL) + + +def parse_verdict(raw_text: str) -> dict: + """Judge JSON -> per-dimension scores, ``visual``, ``score``, ``reason``. + + Returns ``{"_failed": why}`` when it cannot be parsed. A missing dimension counts as a + parse failure rather than defaulting to 0: defaulting would turn "the judge forgot to + mention a dimension" into "the page scores 0 on it", inventing a low score out of + nothing. + """ + m = _JSON_RE.search(raw_text or "") + if not m: + return {"_failed": f"no json in judge output: {(raw_text or '')[:160]}"} + try: + data = json.loads(m.group(0)) + except Exception as e: # noqa: BLE001 + return {"_failed": f"json error: {type(e).__name__}: {e}"} + dims: dict[str, float] = {} + for k in ALL_KEYS: + v = data.get(k) + if v is None: + return {"_failed": f"judge omitted dimension {k!r}"} + try: + dims[k] = max(0.0, min(1.0, float(v))) + except (TypeError, ValueError): + return {"_failed": f"dimension {k!r} is not a number: {v!r}"} + visual = sum(dims[k] for k in VISUAL_KEYS) / len(VISUAL_KEYS) + score = (visual + dims["query_fulfillment"] + dims["premium_assets"]) / 3.0 + return { + "dims": dims, + "visual": round(visual, 4), + "score": round(score, 4), + "reason": str(data.get("reason", ""))[:500], + }